three.js 792 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. */
  5. var THREE = THREE || { REVISION: '55dev' };
  6. self.console = self.console || {
  7. info: function () {},
  8. log: function () {},
  9. debug: function () {},
  10. warn: function () {},
  11. error: function () {}
  12. };
  13. self.Int32Array = self.Int32Array || Array;
  14. self.Float32Array = self.Float32Array || Array;
  15. // Shims for "startsWith", "endsWith", and "trim" for browsers where this is not yet implemented
  16. // not sure we should have this, or at least not have it here
  17. // http://stackoverflow.com/questions/646628/javascript-startswith
  18. // http://stackoverflow.com/questions/498970/how-do-i-trim-a-string-in-javascript
  19. // http://wiki.ecmascript.org/doku.php?id=harmony%3astring_extras
  20. String.prototype.startsWith = String.prototype.startsWith || function ( str ) {
  21. return this.slice( 0, str.length ) === str;
  22. };
  23. String.prototype.endsWith = String.prototype.endsWith || function ( str ) {
  24. var t = String( str );
  25. var index = this.lastIndexOf( t );
  26. return ( -1 < index && index ) === (this.length - t.length);
  27. };
  28. String.prototype.trim = String.prototype.trim || function () {
  29. return this.replace( /^\s+|\s+$/g, '' );
  30. };
  31. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  32. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  33. // requestAnimationFrame polyfill by Erik Möller
  34. // fixes from Paul Irish and Tino Zijdel
  35. ( function () {
  36. var lastTime = 0;
  37. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  38. for ( var x = 0; x < vendors.length && !window.requestAnimationFrame; ++ x ) {
  39. window.requestAnimationFrame = window[ vendors[ x ] + 'RequestAnimationFrame' ];
  40. window.cancelAnimationFrame = window[ vendors[ x ] + 'CancelAnimationFrame' ] || window[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  41. }
  42. if ( window.requestAnimationFrame === undefined ) {
  43. window.requestAnimationFrame = function ( callback, element ) {
  44. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  45. var id = window.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  46. lastTime = currTime + timeToCall;
  47. return id;
  48. };
  49. }
  50. window.cancelAnimationFrame = window.cancelAnimationFrame || function ( id ) { window.clearTimeout( id ) };
  51. }() );
  52. // GL STATE CONSTANTS
  53. THREE.CullFaceNone = 0;
  54. THREE.CullFaceBack = 1;
  55. THREE.CullFaceFront = 2;
  56. THREE.CullFaceFrontBack = 3;
  57. THREE.FrontFaceDirectionCW = 0;
  58. THREE.FrontFaceDirectionCCW = 1;
  59. // SHADOWING TYPES
  60. THREE.BasicShadowMap = 0;
  61. THREE.PCFShadowMap = 1;
  62. THREE.PCFSoftShadowMap = 2;
  63. // MATERIAL CONSTANTS
  64. // side
  65. THREE.FrontSide = 0;
  66. THREE.BackSide = 1;
  67. THREE.DoubleSide = 2;
  68. // shading
  69. THREE.NoShading = 0;
  70. THREE.FlatShading = 1;
  71. THREE.SmoothShading = 2;
  72. // colors
  73. THREE.NoColors = 0;
  74. THREE.FaceColors = 1;
  75. THREE.VertexColors = 2;
  76. // blending modes
  77. THREE.NoBlending = 0;
  78. THREE.NormalBlending = 1;
  79. THREE.AdditiveBlending = 2;
  80. THREE.SubtractiveBlending = 3;
  81. THREE.MultiplyBlending = 4;
  82. THREE.CustomBlending = 5;
  83. // custom blending equations
  84. // (numbers start from 100 not to clash with other
  85. // mappings to OpenGL constants defined in Texture.js)
  86. THREE.AddEquation = 100;
  87. THREE.SubtractEquation = 101;
  88. THREE.ReverseSubtractEquation = 102;
  89. // custom blending destination factors
  90. THREE.ZeroFactor = 200;
  91. THREE.OneFactor = 201;
  92. THREE.SrcColorFactor = 202;
  93. THREE.OneMinusSrcColorFactor = 203;
  94. THREE.SrcAlphaFactor = 204;
  95. THREE.OneMinusSrcAlphaFactor = 205;
  96. THREE.DstAlphaFactor = 206;
  97. THREE.OneMinusDstAlphaFactor = 207;
  98. // custom blending source factors
  99. //THREE.ZeroFactor = 200;
  100. //THREE.OneFactor = 201;
  101. //THREE.SrcAlphaFactor = 204;
  102. //THREE.OneMinusSrcAlphaFactor = 205;
  103. //THREE.DstAlphaFactor = 206;
  104. //THREE.OneMinusDstAlphaFactor = 207;
  105. THREE.DstColorFactor = 208;
  106. THREE.OneMinusDstColorFactor = 209;
  107. THREE.SrcAlphaSaturateFactor = 210;
  108. // TEXTURE CONSTANTS
  109. THREE.MultiplyOperation = 0;
  110. THREE.MixOperation = 1;
  111. THREE.AddOperation = 2;
  112. // Mapping modes
  113. THREE.UVMapping = function () {};
  114. THREE.CubeReflectionMapping = function () {};
  115. THREE.CubeRefractionMapping = function () {};
  116. THREE.SphericalReflectionMapping = function () {};
  117. THREE.SphericalRefractionMapping = function () {};
  118. // Wrapping modes
  119. THREE.RepeatWrapping = 1000;
  120. THREE.ClampToEdgeWrapping = 1001;
  121. THREE.MirroredRepeatWrapping = 1002;
  122. // Filters
  123. THREE.NearestFilter = 1003;
  124. THREE.NearestMipMapNearestFilter = 1004;
  125. THREE.NearestMipMapLinearFilter = 1005;
  126. THREE.LinearFilter = 1006;
  127. THREE.LinearMipMapNearestFilter = 1007;
  128. THREE.LinearMipMapLinearFilter = 1008;
  129. // Data types
  130. THREE.UnsignedByteType = 1009;
  131. THREE.ByteType = 1010;
  132. THREE.ShortType = 1011;
  133. THREE.UnsignedShortType = 1012;
  134. THREE.IntType = 1013;
  135. THREE.UnsignedIntType = 1014;
  136. THREE.FloatType = 1015;
  137. // Pixel types
  138. //THREE.UnsignedByteType = 1009;
  139. THREE.UnsignedShort4444Type = 1016;
  140. THREE.UnsignedShort5551Type = 1017;
  141. THREE.UnsignedShort565Type = 1018;
  142. // Pixel formats
  143. THREE.AlphaFormat = 1019;
  144. THREE.RGBFormat = 1020;
  145. THREE.RGBAFormat = 1021;
  146. THREE.LuminanceFormat = 1022;
  147. THREE.LuminanceAlphaFormat = 1023;
  148. // Compressed texture formats
  149. THREE.RGB_S3TC_DXT1_Format = 2001;
  150. THREE.RGBA_S3TC_DXT1_Format = 2002;
  151. THREE.RGBA_S3TC_DXT3_Format = 2003;
  152. THREE.RGBA_S3TC_DXT5_Format = 2004;
  153. /*
  154. // Potential future PVRTC compressed texture formats
  155. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  156. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  157. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  158. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  159. */
  160. /**
  161. * @author mrdoob / http://mrdoob.com/
  162. */
  163. THREE.Color = function ( value ) {
  164. if ( value !== undefined ) this.set( value );
  165. return this;
  166. };
  167. THREE.Color.prototype = {
  168. constructor: THREE.Color,
  169. r: 1, g: 1, b: 1,
  170. set: function ( value ) {
  171. switch ( typeof value ) {
  172. case "number":
  173. this.setHex( value );
  174. break;
  175. case "string":
  176. this.setStyle( value );
  177. break;
  178. }
  179. },
  180. setHex: function ( hex ) {
  181. hex = Math.floor( hex );
  182. this.r = ( hex >> 16 & 255 ) / 255;
  183. this.g = ( hex >> 8 & 255 ) / 255;
  184. this.b = ( hex & 255 ) / 255;
  185. return this;
  186. },
  187. setRGB: function ( r, g, b ) {
  188. this.r = r;
  189. this.g = g;
  190. this.b = b;
  191. return this;
  192. },
  193. setHSV: function ( h, s, v ) {
  194. // based on MochiKit implementation by Bob Ippolito
  195. // h,s,v ranges are < 0.0 - 1.0 >
  196. var i, f, p, q, t;
  197. if ( v === 0 ) {
  198. this.r = this.g = this.b = 0;
  199. } else {
  200. i = Math.floor( h * 6 );
  201. f = ( h * 6 ) - i;
  202. p = v * ( 1 - s );
  203. q = v * ( 1 - ( s * f ) );
  204. t = v * ( 1 - ( s * ( 1 - f ) ) );
  205. if ( i === 0 ) {
  206. this.r = v;
  207. this.g = t;
  208. this.b = p;
  209. } else if ( i === 1 ) {
  210. this.r = q;
  211. this.g = v;
  212. this.b = p;
  213. } else if ( i === 2 ) {
  214. this.r = p;
  215. this.g = v;
  216. this.b = t;
  217. } else if ( i === 3 ) {
  218. this.r = p;
  219. this.g = q;
  220. this.b = v;
  221. } else if ( i === 4 ) {
  222. this.r = t;
  223. this.g = p;
  224. this.b = v;
  225. } else if ( i === 5 ) {
  226. this.r = v;
  227. this.g = p;
  228. this.b = q;
  229. }
  230. }
  231. return this;
  232. },
  233. setStyle: function ( style ) {
  234. // rgb(255,0,0)
  235. if ( /^rgb\((\d+),(\d+),(\d+)\)$/i.test( style ) ) {
  236. var color = /^rgb\((\d+),(\d+),(\d+)\)$/i.exec( style );
  237. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  238. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  239. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  240. return this;
  241. }
  242. // rgb(100%,0%,0%)
  243. if ( /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.test( style ) ) {
  244. var color = /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.exec( style );
  245. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  246. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  247. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  248. return this;
  249. }
  250. // #ff0000
  251. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  252. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  253. this.setHex( parseInt( color[ 1 ], 16 ) );
  254. return this;
  255. }
  256. // #f00
  257. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  258. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  259. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  260. return this;
  261. }
  262. // red
  263. if ( /^(\w+)$/i.test( style ) ) {
  264. this.setHex( THREE.ColorKeywords[ style ] );
  265. return this;
  266. }
  267. },
  268. copy: function ( color ) {
  269. this.r = color.r;
  270. this.g = color.g;
  271. this.b = color.b;
  272. return this;
  273. },
  274. copyGammaToLinear: function ( color ) {
  275. this.r = color.r * color.r;
  276. this.g = color.g * color.g;
  277. this.b = color.b * color.b;
  278. return this;
  279. },
  280. copyLinearToGamma: function ( color ) {
  281. this.r = Math.sqrt( color.r );
  282. this.g = Math.sqrt( color.g );
  283. this.b = Math.sqrt( color.b );
  284. return this;
  285. },
  286. convertGammaToLinear: function () {
  287. var r = this.r, g = this.g, b = this.b;
  288. this.r = r * r;
  289. this.g = g * g;
  290. this.b = b * b;
  291. return this;
  292. },
  293. convertLinearToGamma: function () {
  294. this.r = Math.sqrt( this.r );
  295. this.g = Math.sqrt( this.g );
  296. this.b = Math.sqrt( this.b );
  297. return this;
  298. },
  299. getHex: function () {
  300. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  301. },
  302. getHexString: function () {
  303. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  304. },
  305. getStyle: function () {
  306. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  307. },
  308. getHSV: function ( hsv ) {
  309. // based on MochiKit implementation by Bob Ippolito
  310. // h,s,v ranges are < 0.0 - 1.0 >
  311. var r = this.r;
  312. var g = this.g;
  313. var b = this.b;
  314. var max = Math.max( Math.max( r, g ), b );
  315. var min = Math.min( Math.min( r, g ), b );
  316. var hue;
  317. var saturation;
  318. var value = max;
  319. if ( min === max ) {
  320. hue = 0;
  321. saturation = 0;
  322. } else {
  323. var delta = ( max - min );
  324. saturation = delta / max;
  325. if ( r === max ) {
  326. hue = ( g - b ) / delta;
  327. } else if ( g === max ) {
  328. hue = 2 + ( ( b - r ) / delta );
  329. } else {
  330. hue = 4 + ( ( r - g ) / delta );
  331. }
  332. hue /= 6;
  333. if ( hue < 0 ) {
  334. hue += 1;
  335. }
  336. if ( hue > 1 ) {
  337. hue -= 1;
  338. }
  339. }
  340. if ( hsv === undefined ) {
  341. hsv = { h: 0, s: 0, v: 0 };
  342. }
  343. hsv.h = hue;
  344. hsv.s = saturation;
  345. hsv.v = value;
  346. return hsv;
  347. },
  348. add: function ( color ) {
  349. this.r += color.r;
  350. this.g += color.g;
  351. this.b += color.b;
  352. return this;
  353. },
  354. addColors: function ( color1, color2 ) {
  355. this.r = color1.r + color2.r;
  356. this.g = color1.g + color2.g;
  357. this.b = color1.b + color2.b;
  358. return this;
  359. },
  360. addScalar: function ( s ) {
  361. this.r += s;
  362. this.g += s;
  363. this.b += s;
  364. return this;
  365. },
  366. multiply: function ( color ) {
  367. this.r *= color.r;
  368. this.g *= color.g;
  369. this.b *= color.b;
  370. return this;
  371. },
  372. multiplyScalar: function ( s ) {
  373. this.r *= s;
  374. this.g *= s;
  375. this.b *= s;
  376. return this;
  377. },
  378. lerp: function ( color, alpha ) {
  379. this.r += ( color.r - this.r ) * alpha;
  380. this.g += ( color.g - this.g ) * alpha;
  381. this.b += ( color.b - this.b ) * alpha;
  382. return this;
  383. },
  384. clone: function () {
  385. return new THREE.Color().setRGB( this.r, this.g, this.b );
  386. }
  387. };
  388. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF,
  389. "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2,
  390. "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50,
  391. "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B,
  392. "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B,
  393. "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F,
  394. "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3,
  395. "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222,
  396. "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700,
  397. "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4,
  398. "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00,
  399. "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3,
  400. "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA,
  401. "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32,
  402. "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3,
  403. "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC,
  404. "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD,
  405. "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6,
  406. "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9,
  407. "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F,
  408. "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE,
  409. "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA,
  410. "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0,
  411. "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  412. /**
  413. * @author mrdoob / http://mrdoob.com/
  414. * @author philogb / http://blog.thejit.org/
  415. * @author egraether / http://egraether.com/
  416. * @author zz85 / http://www.lab4games.net/zz85/blog
  417. */
  418. THREE.Vector2 = function ( x, y ) {
  419. this.x = x || 0;
  420. this.y = y || 0;
  421. };
  422. THREE.Vector2.prototype = {
  423. constructor: THREE.Vector2,
  424. set: function ( x, y ) {
  425. this.x = x;
  426. this.y = y;
  427. return this;
  428. },
  429. setX: function ( x ) {
  430. this.x = x;
  431. return this;
  432. },
  433. setY: function ( y ) {
  434. this.y = y;
  435. return this;
  436. },
  437. setComponent: function ( index, value ) {
  438. switch ( index ) {
  439. case 0: this.x = value; break;
  440. case 1: this.y = value; break;
  441. default: throw new Error( "index is out of range: " + index );
  442. }
  443. },
  444. getComponent: function ( index ) {
  445. switch ( index ) {
  446. case 0: return this.x;
  447. case 1: return this.y;
  448. default: throw new Error( "index is out of range: " + index );
  449. }
  450. },
  451. copy: function ( v ) {
  452. this.x = v.x;
  453. this.y = v.y;
  454. return this;
  455. },
  456. add: function ( v, w ) {
  457. if ( w !== undefined ) {
  458. console.warn( 'DEPRECATED: Vector2\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  459. return this.addVectors( v, w );
  460. }
  461. this.x += v.x;
  462. this.y += v.y;
  463. return this;
  464. },
  465. addVectors: function ( a, b ) {
  466. this.x = a.x + b.x;
  467. this.y = a.y + b.y;
  468. return this;
  469. },
  470. addScalar: function ( s ) {
  471. this.x += s;
  472. this.y += s;
  473. return this;
  474. },
  475. sub: function ( v, w ) {
  476. if ( w !== undefined ) {
  477. console.warn( 'DEPRECATED: Vector2\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  478. return this.subVectors( v, w );
  479. }
  480. this.x -= v.x;
  481. this.y -= v.y;
  482. return this;
  483. },
  484. subVectors: function ( a, b ) {
  485. this.x = a.x - b.x;
  486. this.y = a.y - b.y;
  487. return this;
  488. },
  489. multiplyScalar: function ( s ) {
  490. this.x *= s;
  491. this.y *= s;
  492. return this;
  493. },
  494. divideScalar: function ( s ) {
  495. if ( s !== 0 ) {
  496. this.x /= s;
  497. this.y /= s;
  498. } else {
  499. this.set( 0, 0 );
  500. }
  501. return this;
  502. },
  503. min: function ( v ) {
  504. if ( this.x > v.x ) {
  505. this.x = v.x;
  506. }
  507. if ( this.y > v.y ) {
  508. this.y = v.y;
  509. }
  510. return this;
  511. },
  512. max: function ( v ) {
  513. if ( this.x < v.x ) {
  514. this.x = v.x;
  515. }
  516. if ( this.y < v.y ) {
  517. this.y = v.y;
  518. }
  519. return this;
  520. },
  521. clamp: function ( min, max ) {
  522. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  523. if ( this.x < min.x ) {
  524. this.x = min.x;
  525. } else if ( this.x > max.x ) {
  526. this.x = max.x;
  527. }
  528. if ( this.y < min.y ) {
  529. this.y = min.y;
  530. } else if ( this.y > max.y ) {
  531. this.y = max.y;
  532. }
  533. return this;
  534. },
  535. negate: function() {
  536. return this.multiplyScalar( - 1 );
  537. },
  538. dot: function ( v ) {
  539. return this.x * v.x + this.y * v.y;
  540. },
  541. lengthSq: function () {
  542. return this.x * this.x + this.y * this.y;
  543. },
  544. length: function () {
  545. return Math.sqrt( this.x * this.x + this.y * this.y );
  546. },
  547. normalize: function () {
  548. return this.divideScalar( this.length() );
  549. },
  550. distanceTo: function ( v ) {
  551. return Math.sqrt( this.distanceToSquared( v ) );
  552. },
  553. distanceToSquared: function ( v ) {
  554. var dx = this.x - v.x, dy = this.y - v.y;
  555. return dx * dx + dy * dy;
  556. },
  557. setLength: function ( l ) {
  558. var oldLength = this.length();
  559. if ( oldLength !== 0 && l !== oldLength ) {
  560. this.multiplyScalar( l / oldLength );
  561. }
  562. return this;
  563. },
  564. lerp: function ( v, alpha ) {
  565. this.x += ( v.x - this.x ) * alpha;
  566. this.y += ( v.y - this.y ) * alpha;
  567. return this;
  568. },
  569. equals: function( v ) {
  570. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  571. },
  572. clone: function () {
  573. return new THREE.Vector2( this.x, this.y );
  574. }
  575. };
  576. /**
  577. * @author mrdoob / http://mrdoob.com/
  578. * @author *kile / http://kile.stravaganza.org/
  579. * @author philogb / http://blog.thejit.org/
  580. * @author mikael emtinger / http://gomo.se/
  581. * @author egraether / http://egraether.com/
  582. * @author WestLangley / http://github.com/WestLangley
  583. */
  584. THREE.Vector3 = function ( x, y, z ) {
  585. this.x = x || 0;
  586. this.y = y || 0;
  587. this.z = z || 0;
  588. };
  589. THREE.Vector3.prototype = {
  590. constructor: THREE.Vector3,
  591. set: function ( x, y, z ) {
  592. this.x = x;
  593. this.y = y;
  594. this.z = z;
  595. return this;
  596. },
  597. setX: function ( x ) {
  598. this.x = x;
  599. return this;
  600. },
  601. setY: function ( y ) {
  602. this.y = y;
  603. return this;
  604. },
  605. setZ: function ( z ) {
  606. this.z = z;
  607. return this;
  608. },
  609. setComponent: function ( index, value ) {
  610. switch ( index ) {
  611. case 0: this.x = value; break;
  612. case 1: this.y = value; break;
  613. case 2: this.z = value; break;
  614. default: throw new Error( "index is out of range: " + index );
  615. }
  616. },
  617. getComponent: function ( index ) {
  618. switch ( index ) {
  619. case 0: return this.x;
  620. case 1: return this.y;
  621. case 2: return this.z;
  622. default: throw new Error( "index is out of range: " + index );
  623. }
  624. },
  625. copy: function ( v ) {
  626. this.x = v.x;
  627. this.y = v.y;
  628. this.z = v.z;
  629. return this;
  630. },
  631. add: function ( v, w ) {
  632. if ( w !== undefined ) {
  633. console.warn( 'DEPRECATED: Vector3\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  634. return this.addVectors( v, w );
  635. }
  636. this.x += v.x;
  637. this.y += v.y;
  638. this.z += v.z;
  639. return this;
  640. },
  641. addScalar: function ( s ) {
  642. this.x += s;
  643. this.y += s;
  644. this.z += s;
  645. return this;
  646. },
  647. addVectors: function ( a, b ) {
  648. this.x = a.x + b.x;
  649. this.y = a.y + b.y;
  650. this.z = a.z + b.z;
  651. return this;
  652. },
  653. sub: function ( v, w ) {
  654. if ( w !== undefined ) {
  655. console.warn( 'DEPRECATED: Vector3\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  656. return this.subVectors( v, w );
  657. }
  658. this.x -= v.x;
  659. this.y -= v.y;
  660. this.z -= v.z;
  661. return this;
  662. },
  663. subVectors: function ( a, b ) {
  664. this.x = a.x - b.x;
  665. this.y = a.y - b.y;
  666. this.z = a.z - b.z;
  667. return this;
  668. },
  669. multiply: function ( v, w ) {
  670. if ( w !== undefined ) {
  671. console.warn( 'DEPRECATED: Vector3\'s .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  672. return this.multiplyVectors( v, w );
  673. }
  674. this.x *= v.x;
  675. this.y *= v.y;
  676. this.z *= v.z;
  677. return this;
  678. },
  679. multiplyScalar: function ( s ) {
  680. this.x *= s;
  681. this.y *= s;
  682. this.z *= s;
  683. return this;
  684. },
  685. multiplyVectors: function ( a, b ) {
  686. this.x = a.x * b.x;
  687. this.y = a.y * b.y;
  688. this.z = a.z * b.z;
  689. return this;
  690. },
  691. applyMatrix3: function ( m ) {
  692. var x = this.x;
  693. var y = this.y;
  694. var z = this.z;
  695. var e = m.elements;
  696. this.x = e[0] * x + e[3] * y + e[6] * z;
  697. this.y = e[1] * x + e[4] * y + e[7] * z;
  698. this.z = e[2] * x + e[5] * y + e[8] * z;
  699. return this;
  700. },
  701. applyMatrix4: function ( m ) {
  702. var x = this.x;
  703. var y = this.y;
  704. var z = this.z;
  705. var e = m.elements;
  706. var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] );
  707. this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
  708. this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
  709. this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
  710. return this;
  711. },
  712. applyQuaternion: function ( q ) {
  713. var x = this.x;
  714. var y = this.y;
  715. var z = this.z;
  716. var qx = q.x;
  717. var qy = q.y;
  718. var qz = q.z;
  719. var qw = q.w;
  720. // calculate quat * vector
  721. var ix = qw * x + qy * z - qz * y;
  722. var iy = qw * y + qz * x - qx * z;
  723. var iz = qw * z + qx * y - qy * x;
  724. var iw = -qx * x - qy * y - qz * z;
  725. // calculate result * inverse quat
  726. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  727. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  728. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  729. return this;
  730. },
  731. divide: function ( v ) {
  732. this.x /= v.x;
  733. this.y /= v.y;
  734. this.z /= v.z;
  735. return this;
  736. },
  737. divideScalar: function ( s ) {
  738. if ( s !== 0 ) {
  739. this.x /= s;
  740. this.y /= s;
  741. this.z /= s;
  742. } else {
  743. this.x = 0;
  744. this.y = 0;
  745. this.z = 0;
  746. }
  747. return this;
  748. },
  749. min: function ( v ) {
  750. if ( this.x > v.x ) {
  751. this.x = v.x;
  752. }
  753. if ( this.y > v.y ) {
  754. this.y = v.y;
  755. }
  756. if ( this.z > v.z ) {
  757. this.z = v.z;
  758. }
  759. return this;
  760. },
  761. max: function ( v ) {
  762. if ( this.x < v.x ) {
  763. this.x = v.x;
  764. }
  765. if ( this.y < v.y ) {
  766. this.y = v.y;
  767. }
  768. if ( this.z < v.z ) {
  769. this.z = v.z;
  770. }
  771. return this;
  772. },
  773. clamp: function ( min, max ) {
  774. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  775. if ( this.x < min.x ) {
  776. this.x = min.x;
  777. } else if ( this.x > max.x ) {
  778. this.x = max.x;
  779. }
  780. if ( this.y < min.y ) {
  781. this.y = min.y;
  782. } else if ( this.y > max.y ) {
  783. this.y = max.y;
  784. }
  785. if ( this.z < min.z ) {
  786. this.z = min.z;
  787. } else if ( this.z > max.z ) {
  788. this.z = max.z;
  789. }
  790. return this;
  791. },
  792. negate: function() {
  793. return this.multiplyScalar( - 1 );
  794. },
  795. dot: function ( v ) {
  796. return this.x * v.x + this.y * v.y + this.z * v.z;
  797. },
  798. lengthSq: function () {
  799. return this.x * this.x + this.y * this.y + this.z * this.z;
  800. },
  801. length: function () {
  802. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  803. },
  804. lengthManhattan: function () {
  805. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  806. },
  807. normalize: function () {
  808. return this.divideScalar( this.length() );
  809. },
  810. setLength: function ( l ) {
  811. var oldLength = this.length();
  812. if ( oldLength !== 0 && l !== oldLength ) {
  813. this.multiplyScalar( l / oldLength );
  814. }
  815. return this;
  816. },
  817. lerp: function ( v, alpha ) {
  818. this.x += ( v.x - this.x ) * alpha;
  819. this.y += ( v.y - this.y ) * alpha;
  820. this.z += ( v.z - this.z ) * alpha;
  821. return this;
  822. },
  823. cross: function ( v, w ) {
  824. if ( w !== undefined ) {
  825. console.warn( 'DEPRECATED: Vector3\'s .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  826. return this.crossVectors( v, w );
  827. }
  828. var x = this.x, y = this.y, z = this.z;
  829. this.x = y * v.z - z * v.y;
  830. this.y = z * v.x - x * v.z;
  831. this.z = x * v.y - y * v.x;
  832. return this;
  833. },
  834. crossVectors: function ( a, b ) {
  835. this.x = a.y * b.z - a.z * b.y;
  836. this.y = a.z * b.x - a.x * b.z;
  837. this.z = a.x * b.y - a.y * b.x;
  838. return this;
  839. },
  840. angleTo: function ( v ) {
  841. return Math.acos( this.dot( v ) / this.length() / v.length() );
  842. },
  843. distanceTo: function ( v ) {
  844. return Math.sqrt( this.distanceToSquared( v ) );
  845. },
  846. distanceToSquared: function ( v ) {
  847. var dx = this.x - v.x;
  848. var dy = this.y - v.y;
  849. var dz = this.z - v.z;
  850. return dx * dx + dy * dy + dz * dz;
  851. },
  852. getPositionFromMatrix: function ( m ) {
  853. this.x = m.elements[12];
  854. this.y = m.elements[13];
  855. this.z = m.elements[14];
  856. return this;
  857. },
  858. setEulerFromRotationMatrix: function ( m, order ) {
  859. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  860. // clamp, to handle numerical problems
  861. function clamp( x ) {
  862. return Math.min( Math.max( x, -1 ), 1 );
  863. }
  864. var te = m.elements;
  865. var m11 = te[0], m12 = te[4], m13 = te[8];
  866. var m21 = te[1], m22 = te[5], m23 = te[9];
  867. var m31 = te[2], m32 = te[6], m33 = te[10];
  868. if ( order === undefined || order === 'XYZ' ) {
  869. this.y = Math.asin( clamp( m13 ) );
  870. if ( Math.abs( m13 ) < 0.99999 ) {
  871. this.x = Math.atan2( - m23, m33 );
  872. this.z = Math.atan2( - m12, m11 );
  873. } else {
  874. this.x = Math.atan2( m32, m22 );
  875. this.z = 0;
  876. }
  877. } else if ( order === 'YXZ' ) {
  878. this.x = Math.asin( - clamp( m23 ) );
  879. if ( Math.abs( m23 ) < 0.99999 ) {
  880. this.y = Math.atan2( m13, m33 );
  881. this.z = Math.atan2( m21, m22 );
  882. } else {
  883. this.y = Math.atan2( - m31, m11 );
  884. this.z = 0;
  885. }
  886. } else if ( order === 'ZXY' ) {
  887. this.x = Math.asin( clamp( m32 ) );
  888. if ( Math.abs( m32 ) < 0.99999 ) {
  889. this.y = Math.atan2( - m31, m33 );
  890. this.z = Math.atan2( - m12, m22 );
  891. } else {
  892. this.y = 0;
  893. this.z = Math.atan2( m21, m11 );
  894. }
  895. } else if ( order === 'ZYX' ) {
  896. this.y = Math.asin( - clamp( m31 ) );
  897. if ( Math.abs( m31 ) < 0.99999 ) {
  898. this.x = Math.atan2( m32, m33 );
  899. this.z = Math.atan2( m21, m11 );
  900. } else {
  901. this.x = 0;
  902. this.z = Math.atan2( - m12, m22 );
  903. }
  904. } else if ( order === 'YZX' ) {
  905. this.z = Math.asin( clamp( m21 ) );
  906. if ( Math.abs( m21 ) < 0.99999 ) {
  907. this.x = Math.atan2( - m23, m22 );
  908. this.y = Math.atan2( - m31, m11 );
  909. } else {
  910. this.x = 0;
  911. this.y = Math.atan2( m13, m33 );
  912. }
  913. } else if ( order === 'XZY' ) {
  914. this.z = Math.asin( - clamp( m12 ) );
  915. if ( Math.abs( m12 ) < 0.99999 ) {
  916. this.x = Math.atan2( m32, m22 );
  917. this.y = Math.atan2( m13, m11 );
  918. } else {
  919. this.x = Math.atan2( - m23, m33 );
  920. this.y = 0;
  921. }
  922. }
  923. return this;
  924. },
  925. setEulerFromQuaternion: function ( q, order ) {
  926. // q is assumed to be normalized
  927. // clamp, to handle numerical problems
  928. function clamp( x ) {
  929. return Math.min( Math.max( x, -1 ), 1 );
  930. }
  931. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  932. var sqx = q.x * q.x;
  933. var sqy = q.y * q.y;
  934. var sqz = q.z * q.z;
  935. var sqw = q.w * q.w;
  936. if ( order === undefined || order === 'XYZ' ) {
  937. this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  938. this.y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  939. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  940. } else if ( order === 'YXZ' ) {
  941. this.x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  942. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  943. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  944. } else if ( order === 'ZXY' ) {
  945. this.x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  946. this.y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  947. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  948. } else if ( order === 'ZYX' ) {
  949. this.x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  950. this.y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  951. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  952. } else if ( order === 'YZX' ) {
  953. this.x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  954. this.y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  955. this.z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  956. } else if ( order === 'XZY' ) {
  957. this.x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  958. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  959. this.z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  960. }
  961. return this;
  962. },
  963. getScaleFromMatrix: function ( m ) {
  964. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  965. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  966. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  967. this.x = sx;
  968. this.y = sy;
  969. this.z = sz;
  970. return this;
  971. },
  972. equals: function ( v ) {
  973. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  974. },
  975. clone: function () {
  976. return new THREE.Vector3( this.x, this.y, this.z );
  977. }
  978. };
  979. /**
  980. * @author supereggbert / http://www.paulbrunt.co.uk/
  981. * @author philogb / http://blog.thejit.org/
  982. * @author mikael emtinger / http://gomo.se/
  983. * @author egraether / http://egraether.com/
  984. * @author WestLangley / http://github.com/WestLangley
  985. */
  986. THREE.Vector4 = function ( x, y, z, w ) {
  987. this.x = x || 0;
  988. this.y = y || 0;
  989. this.z = z || 0;
  990. this.w = ( w !== undefined ) ? w : 1;
  991. };
  992. THREE.Vector4.prototype = {
  993. constructor: THREE.Vector4,
  994. set: function ( x, y, z, w ) {
  995. this.x = x;
  996. this.y = y;
  997. this.z = z;
  998. this.w = w;
  999. return this;
  1000. },
  1001. setX: function ( x ) {
  1002. this.x = x;
  1003. return this;
  1004. },
  1005. setY: function ( y ) {
  1006. this.y = y;
  1007. return this;
  1008. },
  1009. setZ: function ( z ) {
  1010. this.z = z;
  1011. return this;
  1012. },
  1013. setW: function ( w ) {
  1014. this.w = w;
  1015. return this;
  1016. },
  1017. setComponent: function ( index, value ) {
  1018. switch ( index ) {
  1019. case 0: this.x = value; break;
  1020. case 1: this.y = value; break;
  1021. case 2: this.z = value; break;
  1022. case 3: this.w = value; break;
  1023. default: throw new Error( "index is out of range: " + index );
  1024. }
  1025. },
  1026. getComponent: function ( index ) {
  1027. switch ( index ) {
  1028. case 0: return this.x;
  1029. case 1: return this.y;
  1030. case 2: return this.z;
  1031. case 3: return this.w;
  1032. default: throw new Error( "index is out of range: " + index );
  1033. }
  1034. },
  1035. copy: function ( v ) {
  1036. this.x = v.x;
  1037. this.y = v.y;
  1038. this.z = v.z;
  1039. this.w = ( v.w !== undefined ) ? v.w : 1;
  1040. return this;
  1041. },
  1042. add: function ( v, w ) {
  1043. if ( w !== undefined ) {
  1044. console.warn( 'DEPRECATED: Vector4\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1045. return this.addVectors( v, w );
  1046. }
  1047. this.x += v.x;
  1048. this.y += v.y;
  1049. this.z += v.z;
  1050. this.w += v.w;
  1051. return this;
  1052. },
  1053. addScalar: function ( s ) {
  1054. this.x += s;
  1055. this.y += s;
  1056. this.z += s;
  1057. this.w += s;
  1058. return this;
  1059. },
  1060. addVectors: function ( a, b ) {
  1061. this.x = a.x + b.x;
  1062. this.y = a.y + b.y;
  1063. this.z = a.z + b.z;
  1064. this.w = a.w + b.w;
  1065. return this;
  1066. },
  1067. sub: function ( v, w ) {
  1068. if ( w !== undefined ) {
  1069. console.warn( 'DEPRECATED: Vector4\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1070. return this.subVectors( v, w );
  1071. }
  1072. this.x -= v.x;
  1073. this.y -= v.y;
  1074. this.z -= v.z;
  1075. this.w -= v.w;
  1076. return this;
  1077. },
  1078. subVectors: function ( a, b ) {
  1079. this.x = a.x - b.x;
  1080. this.y = a.y - b.y;
  1081. this.z = a.z - b.z;
  1082. this.w = a.w - b.w;
  1083. return this;
  1084. },
  1085. multiplyScalar: function ( s ) {
  1086. this.x *= s;
  1087. this.y *= s;
  1088. this.z *= s;
  1089. this.w *= s;
  1090. return this;
  1091. },
  1092. applyMatrix4: function ( m ) {
  1093. var x = this.x;
  1094. var y = this.y;
  1095. var z = this.z;
  1096. var w = this.w;
  1097. var e = m.elements;
  1098. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1099. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1100. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1101. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1102. return this;
  1103. },
  1104. divideScalar: function ( s ) {
  1105. if ( s !== 0 ) {
  1106. this.x /= s;
  1107. this.y /= s;
  1108. this.z /= s;
  1109. this.w /= s;
  1110. } else {
  1111. this.x = 0;
  1112. this.y = 0;
  1113. this.z = 0;
  1114. this.w = 1;
  1115. }
  1116. return this;
  1117. },
  1118. min: function ( v ) {
  1119. if ( this.x > v.x ) {
  1120. this.x = v.x;
  1121. }
  1122. if ( this.y > v.y ) {
  1123. this.y = v.y;
  1124. }
  1125. if ( this.z > v.z ) {
  1126. this.z = v.z;
  1127. }
  1128. if ( this.w > v.w ) {
  1129. this.w = v.w;
  1130. }
  1131. return this;
  1132. },
  1133. max: function ( v ) {
  1134. if ( this.x < v.x ) {
  1135. this.x = v.x;
  1136. }
  1137. if ( this.y < v.y ) {
  1138. this.y = v.y;
  1139. }
  1140. if ( this.z < v.z ) {
  1141. this.z = v.z;
  1142. }
  1143. if ( this.w < v.w ) {
  1144. this.w = v.w;
  1145. }
  1146. return this;
  1147. },
  1148. clamp: function ( min, max ) {
  1149. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1150. if ( this.x < min.x ) {
  1151. this.x = min.x;
  1152. } else if ( this.x > max.x ) {
  1153. this.x = max.x;
  1154. }
  1155. if ( this.y < min.y ) {
  1156. this.y = min.y;
  1157. } else if ( this.y > max.y ) {
  1158. this.y = max.y;
  1159. }
  1160. if ( this.z < min.z ) {
  1161. this.z = min.z;
  1162. } else if ( this.z > max.z ) {
  1163. this.z = max.z;
  1164. }
  1165. if ( this.w < min.w ) {
  1166. this.w = min.w;
  1167. } else if ( this.w > max.w ) {
  1168. this.w = max.w;
  1169. }
  1170. return this;
  1171. },
  1172. negate: function() {
  1173. return this.multiplyScalar( -1 );
  1174. },
  1175. dot: function ( v ) {
  1176. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1177. },
  1178. lengthSq: function () {
  1179. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1180. },
  1181. length: function () {
  1182. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1183. },
  1184. lengthManhattan: function () {
  1185. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1186. },
  1187. normalize: function () {
  1188. return this.divideScalar( this.length() );
  1189. },
  1190. setLength: function ( l ) {
  1191. var oldLength = this.length();
  1192. if ( oldLength !== 0 && l !== oldLength ) {
  1193. this.multiplyScalar( l / oldLength );
  1194. }
  1195. return this;
  1196. },
  1197. lerp: function ( v, alpha ) {
  1198. this.x += ( v.x - this.x ) * alpha;
  1199. this.y += ( v.y - this.y ) * alpha;
  1200. this.z += ( v.z - this.z ) * alpha;
  1201. this.w += ( v.w - this.w ) * alpha;
  1202. return this;
  1203. },
  1204. equals: function ( v ) {
  1205. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1206. },
  1207. clone: function () {
  1208. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1209. },
  1210. setAxisAngleFromQuaternion: function ( q ) {
  1211. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1212. // q is assumed to be normalized
  1213. this.w = 2 * Math.acos( q.w );
  1214. var s = Math.sqrt( 1 - q.w * q.w );
  1215. if ( s < 0.0001 ) {
  1216. this.x = 1;
  1217. this.y = 0;
  1218. this.z = 0;
  1219. } else {
  1220. this.x = q.x / s;
  1221. this.y = q.y / s;
  1222. this.z = q.z / s;
  1223. }
  1224. return this;
  1225. },
  1226. setAxisAngleFromRotationMatrix: function ( m ) {
  1227. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1228. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1229. var angle, x, y, z, // variables for result
  1230. epsilon = 0.01, // margin to allow for rounding errors
  1231. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1232. te = m.elements,
  1233. m11 = te[0], m12 = te[4], m13 = te[8],
  1234. m21 = te[1], m22 = te[5], m23 = te[9],
  1235. m31 = te[2], m32 = te[6], m33 = te[10];
  1236. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1237. && ( Math.abs( m13 - m31 ) < epsilon )
  1238. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1239. // singularity found
  1240. // first check for identity matrix which must have +1 for all terms
  1241. // in leading diagonal and zero in other terms
  1242. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1243. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1244. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1245. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1246. // this singularity is identity matrix so angle = 0
  1247. this.set( 1, 0, 0, 0 );
  1248. return this; // zero angle, arbitrary axis
  1249. }
  1250. // otherwise this singularity is angle = 180
  1251. angle = Math.PI;
  1252. var xx = ( m11 + 1 ) / 2;
  1253. var yy = ( m22 + 1 ) / 2;
  1254. var zz = ( m33 + 1 ) / 2;
  1255. var xy = ( m12 + m21 ) / 4;
  1256. var xz = ( m13 + m31 ) / 4;
  1257. var yz = ( m23 + m32 ) / 4;
  1258. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1259. if ( xx < epsilon ) {
  1260. x = 0;
  1261. y = 0.707106781;
  1262. z = 0.707106781;
  1263. } else {
  1264. x = Math.sqrt( xx );
  1265. y = xy / x;
  1266. z = xz / x;
  1267. }
  1268. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1269. if ( yy < epsilon ) {
  1270. x = 0.707106781;
  1271. y = 0;
  1272. z = 0.707106781;
  1273. } else {
  1274. y = Math.sqrt( yy );
  1275. x = xy / y;
  1276. z = yz / y;
  1277. }
  1278. } else { // m33 is the largest diagonal term so base result on this
  1279. if ( zz < epsilon ) {
  1280. x = 0.707106781;
  1281. y = 0.707106781;
  1282. z = 0;
  1283. } else {
  1284. z = Math.sqrt( zz );
  1285. x = xz / z;
  1286. y = yz / z;
  1287. }
  1288. }
  1289. this.set( x, y, z, angle );
  1290. return this; // return 180 deg rotation
  1291. }
  1292. // as we have reached here there are no singularities so we can handle normally
  1293. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1294. + ( m13 - m31 ) * ( m13 - m31 )
  1295. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1296. if ( Math.abs( s ) < 0.001 ) s = 1;
  1297. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1298. // caught by singularity test above, but I've left it in just in case
  1299. this.x = ( m32 - m23 ) / s;
  1300. this.y = ( m13 - m31 ) / s;
  1301. this.z = ( m21 - m12 ) / s;
  1302. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1303. return this;
  1304. }
  1305. };
  1306. /**
  1307. * @author bhouston / http://exocortex.com
  1308. */
  1309. THREE.Box2 = function ( min, max ) {
  1310. this.min = min !== undefined ? min.clone() : new THREE.Vector2( Infinity, Infinity );
  1311. this.max = max !== undefined ? max.clone() : new THREE.Vector2( -Infinity, -Infinity );
  1312. };
  1313. THREE.Box2.prototype = {
  1314. constructor: THREE.Box2,
  1315. set: function ( min, max ) {
  1316. this.min.copy( min );
  1317. this.max.copy( max );
  1318. return this;
  1319. },
  1320. setFromPoints: function ( points ) {
  1321. if ( points.length > 0 ) {
  1322. var point = points[ 0 ];
  1323. this.min.copy( point );
  1324. this.max.copy( point );
  1325. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1326. point = points[ i ];
  1327. if ( point.x < this.min.x ) {
  1328. this.min.x = point.x;
  1329. } else if ( point.x > this.max.x ) {
  1330. this.max.x = point.x;
  1331. }
  1332. if ( point.y < this.min.y ) {
  1333. this.min.y = point.y;
  1334. } else if ( point.y > this.max.y ) {
  1335. this.max.y = point.y;
  1336. }
  1337. }
  1338. } else {
  1339. this.makeEmpty();
  1340. }
  1341. return this;
  1342. },
  1343. setFromCenterAndSize: function ( center, size ) {
  1344. var halfSize = THREE.Box2.__v1.copy( size ).multiplyScalar( 0.5 );
  1345. this.min.copy( center ).sub( halfSize );
  1346. this.max.copy( center ).add( halfSize );
  1347. return this;
  1348. },
  1349. copy: function ( box ) {
  1350. this.min.copy( box.min );
  1351. this.max.copy( box.max );
  1352. return this;
  1353. },
  1354. makeEmpty: function () {
  1355. this.min.x = this.min.y = Infinity;
  1356. this.max.x = this.max.y = -Infinity;
  1357. return this;
  1358. },
  1359. empty: function () {
  1360. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1361. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  1362. },
  1363. center: function ( optionalTarget ) {
  1364. var result = optionalTarget || new THREE.Vector2();
  1365. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1366. },
  1367. size: function ( optionalTarget ) {
  1368. var result = optionalTarget || new THREE.Vector2();
  1369. return result.subVectors( this.max, this.min );
  1370. },
  1371. expandByPoint: function ( point ) {
  1372. this.min.min( point );
  1373. this.max.max( point );
  1374. return this;
  1375. },
  1376. expandByVector: function ( vector ) {
  1377. this.min.sub( vector );
  1378. this.max.add( vector );
  1379. return this;
  1380. },
  1381. expandByScalar: function ( scalar ) {
  1382. this.min.addScalar( -scalar );
  1383. this.max.addScalar( scalar );
  1384. return this;
  1385. },
  1386. containsPoint: function ( point ) {
  1387. if ( ( this.min.x <= point.x ) && ( point.x <= this.max.x ) &&
  1388. ( this.min.y <= point.y ) && ( point.y <= this.max.y ) ) {
  1389. return true;
  1390. }
  1391. return false;
  1392. },
  1393. containsBox: function ( box ) {
  1394. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1395. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  1396. return true;
  1397. }
  1398. return false;
  1399. },
  1400. getParameter: function ( point ) {
  1401. // This can potentially have a divide by zero if the box
  1402. // has a size dimension of 0.
  1403. return new THREE.Vector2(
  1404. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1405. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  1406. );
  1407. },
  1408. isIntersectionBox: function ( box ) {
  1409. // using 6 splitting planes to rule out intersections.
  1410. if ( ( box.max.x < this.min.x ) ||
  1411. ( box.min.x > this.max.x ) ||
  1412. ( box.max.y < this.min.y ) ||
  1413. ( box.min.y > this.max.y ) ) {
  1414. return false;
  1415. }
  1416. return true;
  1417. },
  1418. clampPoint: function ( point, optionalTarget ) {
  1419. var result = optionalTarget || new THREE.Vector2();
  1420. return result.copy( point ).clamp( this.min, this.max );
  1421. },
  1422. distanceToPoint: function ( point ) {
  1423. var clampedPoint = THREE.Box2.__v1.copy( point ).clamp( this.min, this.max );
  1424. return clampedPoint.sub( point ).length();
  1425. },
  1426. intersect: function ( box ) {
  1427. this.min.max( box.min );
  1428. this.max.min( box.max );
  1429. return this;
  1430. },
  1431. union: function ( box ) {
  1432. this.min.min( box.min );
  1433. this.max.max( box.max );
  1434. return this;
  1435. },
  1436. translate: function ( offset ) {
  1437. this.min.add( offset );
  1438. this.max.add( offset );
  1439. return this;
  1440. },
  1441. equals: function ( box ) {
  1442. return box.min.equals( this.min ) && box.max.equals( this.max );
  1443. },
  1444. clone: function () {
  1445. return new THREE.Box2().copy( this );
  1446. }
  1447. };
  1448. THREE.Box2.__v1 = new THREE.Vector2();
  1449. /**
  1450. * @author bhouston / http://exocortex.com
  1451. */
  1452. THREE.Box3 = function ( min, max ) {
  1453. this.min = min !== undefined ? min.clone() : new THREE.Vector3( Infinity, Infinity, Infinity );
  1454. this.max = max !== undefined ? max.clone() : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  1455. };
  1456. THREE.Box3.prototype = {
  1457. constructor: THREE.Box3,
  1458. set: function ( min, max ) {
  1459. this.min.copy( min );
  1460. this.max.copy( max );
  1461. return this;
  1462. },
  1463. setFromPoints: function ( points ) {
  1464. if ( points.length > 0 ) {
  1465. var p = points[ 0 ];
  1466. this.min.copy( p );
  1467. this.max.copy( p );
  1468. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1469. p = points[ i ];
  1470. if ( p.x < this.min.x ) {
  1471. this.min.x = p.x;
  1472. } else if ( p.x > this.max.x ) {
  1473. this.max.x = p.x;
  1474. }
  1475. if ( p.y < this.min.y ) {
  1476. this.min.y = p.y;
  1477. } else if ( p.y > this.max.y ) {
  1478. this.max.y = p.y;
  1479. }
  1480. if ( p.z < this.min.z ) {
  1481. this.min.z = p.z;
  1482. } else if ( p.z > this.max.z ) {
  1483. this.max.z = p.z;
  1484. }
  1485. }
  1486. } else {
  1487. this.makeEmpty();
  1488. }
  1489. return this;
  1490. },
  1491. setFromCenterAndSize: function ( center, size ) {
  1492. var halfSize = THREE.Box3.__v1.copy( size ).multiplyScalar( 0.5 );
  1493. this.min.copy( center ).sub( halfSize );
  1494. this.max.copy( center ).add( halfSize );
  1495. return this;
  1496. },
  1497. copy: function ( box ) {
  1498. this.min.copy( box.min );
  1499. this.max.copy( box.max );
  1500. return this;
  1501. },
  1502. makeEmpty: function () {
  1503. this.min.x = this.min.y = this.min.z = Infinity;
  1504. this.max.x = this.max.y = this.max.z = -Infinity;
  1505. return this;
  1506. },
  1507. empty: function () {
  1508. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1509. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  1510. },
  1511. center: function ( optionalTarget ) {
  1512. var result = optionalTarget || new THREE.Vector3();
  1513. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1514. },
  1515. size: function ( optionalTarget ) {
  1516. var result = optionalTarget || new THREE.Vector3();
  1517. return result.subVectors( this.max, this.min );
  1518. },
  1519. expandByPoint: function ( point ) {
  1520. this.min.min( point );
  1521. this.max.max( point );
  1522. return this;
  1523. },
  1524. expandByVector: function ( vector ) {
  1525. this.min.sub( vector );
  1526. this.max.add( vector );
  1527. return this;
  1528. },
  1529. expandByScalar: function ( scalar ) {
  1530. this.min.addScalar( -scalar );
  1531. this.max.addScalar( scalar );
  1532. return this;
  1533. },
  1534. containsPoint: function ( point ) {
  1535. if ( ( this.min.x <= point.x ) && ( point.x <= this.max.x ) &&
  1536. ( this.min.y <= point.y ) && ( point.y <= this.max.y ) &&
  1537. ( this.min.z <= point.z ) && ( point.z <= this.max.z ) ) {
  1538. return true;
  1539. }
  1540. return false;
  1541. },
  1542. containsBox: function ( box ) {
  1543. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1544. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  1545. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  1546. return true;
  1547. }
  1548. return false;
  1549. },
  1550. getParameter: function ( point ) {
  1551. // This can potentially have a divide by zero if the box
  1552. // has a size dimension of 0.
  1553. return new THREE.Vector3(
  1554. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1555. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  1556. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  1557. );
  1558. },
  1559. isIntersectionBox: function ( box ) {
  1560. // using 6 splitting planes to rule out intersections.
  1561. if ( ( box.max.x < this.min.x ) || ( box.min.x > this.max.x ) ||
  1562. ( box.max.y < this.min.y ) || ( box.min.y > this.max.y ) ||
  1563. ( box.max.z < this.min.z ) || ( box.min.z > this.max.z ) ) {
  1564. return false;
  1565. }
  1566. return true;
  1567. },
  1568. clampPoint: function ( point, optionalTarget ) {
  1569. var result = optionalTarget || new THREE.Vector3();
  1570. return new THREE.Vector3().copy( point ).clamp( this.min, this.max );
  1571. },
  1572. distanceToPoint: function ( point ) {
  1573. var clampedPoint = THREE.Box3.__v1.copy( point ).clamp( this.min, this.max );
  1574. return clampedPoint.sub( point ).length();
  1575. },
  1576. getBoundingSphere: function ( optionalTarget ) {
  1577. var result = optionalTarget || new THREE.Sphere();
  1578. result.center = this.center();
  1579. result.radius = this.size( THREE.Box3.__v0 ).length() * 0.5;
  1580. return result;
  1581. },
  1582. intersect: function ( box ) {
  1583. this.min.max( box.min );
  1584. this.max.min( box.max );
  1585. return this;
  1586. },
  1587. union: function ( box ) {
  1588. this.min.min( box.min );
  1589. this.max.max( box.max );
  1590. return this;
  1591. },
  1592. transform: function ( matrix ) {
  1593. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  1594. var newPoints = [
  1595. THREE.Box3.__v0.set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ),
  1596. THREE.Box3.__v0.set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ), // 000
  1597. THREE.Box3.__v1.set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ), // 001
  1598. THREE.Box3.__v2.set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ), // 010
  1599. THREE.Box3.__v3.set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ), // 011
  1600. THREE.Box3.__v4.set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ), // 100
  1601. THREE.Box3.__v5.set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ), // 101
  1602. THREE.Box3.__v6.set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ), // 110
  1603. THREE.Box3.__v7.set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ) // 111
  1604. ];
  1605. this.makeEmpty();
  1606. this.setFromPoints( newPoints );
  1607. return this;
  1608. },
  1609. translate: function ( offset ) {
  1610. this.min.add( offset );
  1611. this.max.add( offset );
  1612. return this;
  1613. },
  1614. equals: function ( box ) {
  1615. return box.min.equals( this.min ) && box.max.equals( this.max );
  1616. },
  1617. clone: function () {
  1618. return new THREE.Box3().copy( this );
  1619. }
  1620. };
  1621. THREE.Box3.__v0 = new THREE.Vector3();
  1622. THREE.Box3.__v1 = new THREE.Vector3();
  1623. THREE.Box3.__v2 = new THREE.Vector3();
  1624. THREE.Box3.__v3 = new THREE.Vector3();
  1625. THREE.Box3.__v4 = new THREE.Vector3();
  1626. THREE.Box3.__v5 = new THREE.Vector3();
  1627. THREE.Box3.__v6 = new THREE.Vector3();
  1628. THREE.Box3.__v7 = new THREE.Vector3();
  1629. /**
  1630. * @author alteredq / http://alteredqualia.com/
  1631. * @author WestLangley / http://github.com/WestLangley
  1632. * @author bhouston / http://exocortex.com
  1633. */
  1634. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  1635. this.elements = new Float32Array(9);
  1636. this.set(
  1637. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0,
  1638. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0,
  1639. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1
  1640. );
  1641. };
  1642. THREE.Matrix3.prototype = {
  1643. constructor: THREE.Matrix3,
  1644. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  1645. var te = this.elements;
  1646. te[0] = n11; te[3] = n12; te[6] = n13;
  1647. te[1] = n21; te[4] = n22; te[7] = n23;
  1648. te[2] = n31; te[5] = n32; te[8] = n33;
  1649. return this;
  1650. },
  1651. identity: function () {
  1652. this.set(
  1653. 1, 0, 0,
  1654. 0, 1, 0,
  1655. 0, 0, 1
  1656. );
  1657. return this;
  1658. },
  1659. copy: function ( m ) {
  1660. var me = m.elements;
  1661. this.set(
  1662. me[0], me[3], me[6],
  1663. me[1], me[4], me[7],
  1664. me[2], me[5], me[8]
  1665. );
  1666. return this;
  1667. },
  1668. multiplyVector3Array: function ( a ) {
  1669. var tmp = THREE.Matrix3.__v1;
  1670. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  1671. tmp.x = a[ i ];
  1672. tmp.y = a[ i + 1 ];
  1673. tmp.z = a[ i + 2 ];
  1674. this.multiplyVector3( tmp );
  1675. a[ i ] = tmp.x;
  1676. a[ i + 1 ] = tmp.y;
  1677. a[ i + 2 ] = tmp.z;
  1678. }
  1679. return a;
  1680. },
  1681. multiplyScalar: function ( s ) {
  1682. var te = this.elements;
  1683. te[0] *= s; te[3] *= s; te[6] *= s;
  1684. te[1] *= s; te[4] *= s; te[7] *= s;
  1685. te[2] *= s; te[5] *= s; te[8] *= s;
  1686. return this;
  1687. },
  1688. determinant: function () {
  1689. var te = this.elements;
  1690. var a = te[0], b = te[1], c = te[2],
  1691. d = te[3], e = te[4], f = te[5],
  1692. g = te[6], h = te[7], i = te[8];
  1693. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  1694. },
  1695. getInverse: function ( matrix, throwOnInvertible ) {
  1696. // input: THREE.Matrix4
  1697. // ( based on http://code.google.com/p/webgl-mjs/ )
  1698. var me = matrix.elements;
  1699. var te = this.elements;
  1700. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  1701. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  1702. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  1703. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  1704. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  1705. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  1706. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  1707. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  1708. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  1709. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  1710. // no inverse
  1711. if ( det === 0 ) {
  1712. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  1713. if ( throwOnInvertible || false ) {
  1714. throw new Error( msg );
  1715. } else {
  1716. console.warn( msg );
  1717. }
  1718. this.identity();
  1719. return this;
  1720. }
  1721. this.multiplyScalar( 1.0 / det );
  1722. return this;
  1723. },
  1724. transpose: function () {
  1725. var tmp, m = this.elements;
  1726. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  1727. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  1728. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  1729. return this;
  1730. },
  1731. transposeIntoArray: function ( r ) {
  1732. var m = this.elements;
  1733. r[ 0 ] = m[ 0 ];
  1734. r[ 1 ] = m[ 3 ];
  1735. r[ 2 ] = m[ 6 ];
  1736. r[ 3 ] = m[ 1 ];
  1737. r[ 4 ] = m[ 4 ];
  1738. r[ 5 ] = m[ 7 ];
  1739. r[ 6 ] = m[ 2 ];
  1740. r[ 7 ] = m[ 5 ];
  1741. r[ 8 ] = m[ 8 ];
  1742. return this;
  1743. },
  1744. clone: function () {
  1745. var te = this.elements;
  1746. return new THREE.Matrix3(
  1747. te[0], te[3], te[6],
  1748. te[1], te[4], te[7],
  1749. te[2], te[5], te[8]
  1750. );
  1751. }
  1752. };
  1753. THREE.Matrix3.__v1 = new THREE.Vector3();
  1754. /**
  1755. * @author mrdoob / http://mrdoob.com/
  1756. * @author supereggbert / http://www.paulbrunt.co.uk/
  1757. * @author philogb / http://blog.thejit.org/
  1758. * @author jordi_ros / http://plattsoft.com
  1759. * @author D1plo1d / http://github.com/D1plo1d
  1760. * @author alteredq / http://alteredqualia.com/
  1761. * @author mikael emtinger / http://gomo.se/
  1762. * @author timknip / http://www.floorplanner.com/
  1763. * @author bhouston / http://exocortex.com
  1764. */
  1765. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1766. this.elements = new Float32Array( 16 );
  1767. this.set(
  1768. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0, n14 || 0,
  1769. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0, n24 || 0,
  1770. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1, n34 || 0,
  1771. n41 || 0, n42 || 0, n43 || 0, ( n44 !== undefined ) ? n44 : 1
  1772. );
  1773. };
  1774. THREE.Matrix4.prototype = {
  1775. constructor: THREE.Matrix4,
  1776. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1777. var te = this.elements;
  1778. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  1779. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  1780. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  1781. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  1782. return this;
  1783. },
  1784. identity: function () {
  1785. this.set(
  1786. 1, 0, 0, 0,
  1787. 0, 1, 0, 0,
  1788. 0, 0, 1, 0,
  1789. 0, 0, 0, 1
  1790. );
  1791. return this;
  1792. },
  1793. copy: function ( m ) {
  1794. var me = m.elements;
  1795. this.set(
  1796. me[0], me[4], me[8], me[12],
  1797. me[1], me[5], me[9], me[13],
  1798. me[2], me[6], me[10], me[14],
  1799. me[3], me[7], me[11], me[15]
  1800. );
  1801. return this;
  1802. },
  1803. setRotationFromEuler: function ( v, order ) {
  1804. var te = this.elements;
  1805. var x = v.x, y = v.y, z = v.z;
  1806. var a = Math.cos( x ), b = Math.sin( x );
  1807. var c = Math.cos( y ), d = Math.sin( y );
  1808. var e = Math.cos( z ), f = Math.sin( z );
  1809. if ( order === undefined || order === 'XYZ' ) {
  1810. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1811. te[0] = c * e;
  1812. te[4] = - c * f;
  1813. te[8] = d;
  1814. te[1] = af + be * d;
  1815. te[5] = ae - bf * d;
  1816. te[9] = - b * c;
  1817. te[2] = bf - ae * d;
  1818. te[6] = be + af * d;
  1819. te[10] = a * c;
  1820. } else if ( order === 'YXZ' ) {
  1821. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1822. te[0] = ce + df * b;
  1823. te[4] = de * b - cf;
  1824. te[8] = a * d;
  1825. te[1] = a * f;
  1826. te[5] = a * e;
  1827. te[9] = - b;
  1828. te[2] = cf * b - de;
  1829. te[6] = df + ce * b;
  1830. te[10] = a * c;
  1831. } else if ( order === 'ZXY' ) {
  1832. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1833. te[0] = ce - df * b;
  1834. te[4] = - a * f;
  1835. te[8] = de + cf * b;
  1836. te[1] = cf + de * b;
  1837. te[5] = a * e;
  1838. te[9] = df - ce * b;
  1839. te[2] = - a * d;
  1840. te[6] = b;
  1841. te[10] = a * c;
  1842. } else if ( order === 'ZYX' ) {
  1843. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1844. te[0] = c * e;
  1845. te[4] = be * d - af;
  1846. te[8] = ae * d + bf;
  1847. te[1] = c * f;
  1848. te[5] = bf * d + ae;
  1849. te[9] = af * d - be;
  1850. te[2] = - d;
  1851. te[6] = b * c;
  1852. te[10] = a * c;
  1853. } else if ( order === 'YZX' ) {
  1854. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1855. te[0] = c * e;
  1856. te[4] = bd - ac * f;
  1857. te[8] = bc * f + ad;
  1858. te[1] = f;
  1859. te[5] = a * e;
  1860. te[9] = - b * e;
  1861. te[2] = - d * e;
  1862. te[6] = ad * f + bc;
  1863. te[10] = ac - bd * f;
  1864. } else if ( order === 'XZY' ) {
  1865. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1866. te[0] = c * e;
  1867. te[4] = - f;
  1868. te[8] = d * e;
  1869. te[1] = ac * f + bd;
  1870. te[5] = a * e;
  1871. te[9] = ad * f - bc;
  1872. te[2] = bc * f - ad;
  1873. te[6] = b * e;
  1874. te[10] = bd * f + ac;
  1875. }
  1876. return this;
  1877. },
  1878. setRotationFromQuaternion: function ( q ) {
  1879. var te = this.elements;
  1880. var x = q.x, y = q.y, z = q.z, w = q.w;
  1881. var x2 = x + x, y2 = y + y, z2 = z + z;
  1882. var xx = x * x2, xy = x * y2, xz = x * z2;
  1883. var yy = y * y2, yz = y * z2, zz = z * z2;
  1884. var wx = w * x2, wy = w * y2, wz = w * z2;
  1885. te[0] = 1 - ( yy + zz );
  1886. te[4] = xy - wz;
  1887. te[8] = xz + wy;
  1888. te[1] = xy + wz;
  1889. te[5] = 1 - ( xx + zz );
  1890. te[9] = yz - wx;
  1891. te[2] = xz - wy;
  1892. te[6] = yz + wx;
  1893. te[10] = 1 - ( xx + yy );
  1894. return this;
  1895. },
  1896. lookAt: function ( eye, target, up ) {
  1897. var te = this.elements;
  1898. var x = THREE.Matrix4.__v1;
  1899. var y = THREE.Matrix4.__v2;
  1900. var z = THREE.Matrix4.__v3;
  1901. z.subVectors( eye, target ).normalize();
  1902. if ( z.length() === 0 ) {
  1903. z.z = 1;
  1904. }
  1905. x.crossVectors( up, z ).normalize();
  1906. if ( x.length() === 0 ) {
  1907. z.x += 0.0001;
  1908. x.crossVectors( up, z ).normalize();
  1909. }
  1910. y.crossVectors( z, x );
  1911. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  1912. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  1913. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  1914. return this;
  1915. },
  1916. multiply: function ( m, n ) {
  1917. if ( n !== undefined ) {
  1918. console.warn( 'DEPRECATED: Matrix4\'s .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  1919. return this.multiplyMatrices( m, n );
  1920. }
  1921. return this.multiplyMatrices( this, m );
  1922. },
  1923. multiplyMatrices: function ( a, b ) {
  1924. var ae = a.elements;
  1925. var be = b.elements;
  1926. var te = this.elements;
  1927. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  1928. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  1929. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  1930. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  1931. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  1932. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  1933. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  1934. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  1935. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  1936. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  1937. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  1938. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  1939. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  1940. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  1941. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  1942. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  1943. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  1944. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  1945. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  1946. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  1947. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  1948. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  1949. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  1950. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  1951. return this;
  1952. },
  1953. multiplyToArray: function ( a, b, r ) {
  1954. var te = this.elements;
  1955. this.multiplyMatrices( a, b );
  1956. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  1957. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  1958. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  1959. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  1960. return this;
  1961. },
  1962. multiplyScalar: function ( s ) {
  1963. var te = this.elements;
  1964. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  1965. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  1966. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  1967. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  1968. return this;
  1969. },
  1970. multiplyVector3Array: function ( a ) {
  1971. var tmp = THREE.Matrix4.__v1;
  1972. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  1973. tmp.x = a[ i ];
  1974. tmp.y = a[ i + 1 ];
  1975. tmp.z = a[ i + 2 ];
  1976. this.multiplyVector3( tmp );
  1977. a[ i ] = tmp.x;
  1978. a[ i + 1 ] = tmp.y;
  1979. a[ i + 2 ] = tmp.z;
  1980. }
  1981. return a;
  1982. },
  1983. rotateAxis: function ( v ) {
  1984. var te = this.elements;
  1985. var vx = v.x, vy = v.y, vz = v.z;
  1986. v.x = vx * te[0] + vy * te[4] + vz * te[8];
  1987. v.y = vx * te[1] + vy * te[5] + vz * te[9];
  1988. v.z = vx * te[2] + vy * te[6] + vz * te[10];
  1989. v.normalize();
  1990. return v;
  1991. },
  1992. crossVector: function ( a ) {
  1993. var te = this.elements;
  1994. var v = new THREE.Vector4();
  1995. v.x = te[0] * a.x + te[4] * a.y + te[8] * a.z + te[12] * a.w;
  1996. v.y = te[1] * a.x + te[5] * a.y + te[9] * a.z + te[13] * a.w;
  1997. v.z = te[2] * a.x + te[6] * a.y + te[10] * a.z + te[14] * a.w;
  1998. v.w = ( a.w ) ? te[3] * a.x + te[7] * a.y + te[11] * a.z + te[15] * a.w : 1;
  1999. return v;
  2000. },
  2001. determinant: function () {
  2002. var te = this.elements;
  2003. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  2004. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  2005. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  2006. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  2007. //TODO: make this more efficient
  2008. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2009. return (
  2010. n41 * (
  2011. +n14 * n23 * n32
  2012. -n13 * n24 * n32
  2013. -n14 * n22 * n33
  2014. +n12 * n24 * n33
  2015. +n13 * n22 * n34
  2016. -n12 * n23 * n34
  2017. ) +
  2018. n42 * (
  2019. +n11 * n23 * n34
  2020. -n11 * n24 * n33
  2021. +n14 * n21 * n33
  2022. -n13 * n21 * n34
  2023. +n13 * n24 * n31
  2024. -n14 * n23 * n31
  2025. ) +
  2026. n43 * (
  2027. +n11 * n24 * n32
  2028. -n11 * n22 * n34
  2029. -n14 * n21 * n32
  2030. +n12 * n21 * n34
  2031. +n14 * n22 * n31
  2032. -n12 * n24 * n31
  2033. ) +
  2034. n44 * (
  2035. -n13 * n22 * n31
  2036. -n11 * n23 * n32
  2037. +n11 * n22 * n33
  2038. +n13 * n21 * n32
  2039. -n12 * n21 * n33
  2040. +n12 * n23 * n31
  2041. )
  2042. );
  2043. },
  2044. transpose: function () {
  2045. var te = this.elements;
  2046. var tmp;
  2047. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  2048. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  2049. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  2050. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  2051. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  2052. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  2053. return this;
  2054. },
  2055. flattenToArray: function ( flat ) {
  2056. var te = this.elements;
  2057. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  2058. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  2059. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  2060. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  2061. return flat;
  2062. },
  2063. flattenToArrayOffset: function( flat, offset ) {
  2064. var te = this.elements;
  2065. flat[ offset ] = te[0];
  2066. flat[ offset + 1 ] = te[1];
  2067. flat[ offset + 2 ] = te[2];
  2068. flat[ offset + 3 ] = te[3];
  2069. flat[ offset + 4 ] = te[4];
  2070. flat[ offset + 5 ] = te[5];
  2071. flat[ offset + 6 ] = te[6];
  2072. flat[ offset + 7 ] = te[7];
  2073. flat[ offset + 8 ] = te[8];
  2074. flat[ offset + 9 ] = te[9];
  2075. flat[ offset + 10 ] = te[10];
  2076. flat[ offset + 11 ] = te[11];
  2077. flat[ offset + 12 ] = te[12];
  2078. flat[ offset + 13 ] = te[13];
  2079. flat[ offset + 14 ] = te[14];
  2080. flat[ offset + 15 ] = te[15];
  2081. return flat;
  2082. },
  2083. getPosition: function () {
  2084. var te = this.elements;
  2085. return THREE.Matrix4.__v1.set( te[12], te[13], te[14] );
  2086. },
  2087. setPosition: function ( v ) {
  2088. var te = this.elements;
  2089. te[12] = v.x;
  2090. te[13] = v.y;
  2091. te[14] = v.z;
  2092. return this;
  2093. },
  2094. getColumnX: function () {
  2095. var te = this.elements;
  2096. return THREE.Matrix4.__v1.set( te[0], te[1], te[2] );
  2097. },
  2098. getColumnY: function () {
  2099. var te = this.elements;
  2100. return THREE.Matrix4.__v1.set( te[4], te[5], te[6] );
  2101. },
  2102. getColumnZ: function() {
  2103. var te = this.elements;
  2104. return THREE.Matrix4.__v1.set( te[8], te[9], te[10] );
  2105. },
  2106. getInverse: function ( m, throwOnInvertible ) {
  2107. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2108. var te = this.elements;
  2109. var me = m.elements;
  2110. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2111. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2112. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2113. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2114. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2115. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2116. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2117. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2118. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2119. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2120. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2121. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2122. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2123. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2124. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2125. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2126. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2127. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2128. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2129. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2130. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 4 ] + me[ 2 ] * te[ 8 ] + me[ 3 ] * te[ 12 ];
  2131. if ( det == 0 ) {
  2132. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2133. if ( throwOnInvertible || false ) {
  2134. throw new Error( msg );
  2135. } else {
  2136. console.warn( msg );
  2137. }
  2138. this.identity();
  2139. return this;
  2140. }
  2141. this.multiplyScalar( 1 / det );
  2142. return this;
  2143. },
  2144. compose: function ( translation, rotation, scale ) {
  2145. var te = this.elements;
  2146. var mRotation = THREE.Matrix4.__m1;
  2147. var mScale = THREE.Matrix4.__m2;
  2148. mRotation.identity();
  2149. mRotation.setRotationFromQuaternion( rotation );
  2150. mScale.makeScale( scale );
  2151. this.multiplyMatrices( mRotation, mScale );
  2152. te[12] = translation.x;
  2153. te[13] = translation.y;
  2154. te[14] = translation.z;
  2155. return this;
  2156. },
  2157. decompose: function ( translation, rotation, scale ) {
  2158. var te = this.elements;
  2159. // grab the axis vectors
  2160. var x = THREE.Matrix4.__v1;
  2161. var y = THREE.Matrix4.__v2;
  2162. var z = THREE.Matrix4.__v3;
  2163. x.set( te[0], te[1], te[2] );
  2164. y.set( te[4], te[5], te[6] );
  2165. z.set( te[8], te[9], te[10] );
  2166. translation = ( translation instanceof THREE.Vector3 ) ? translation : new THREE.Vector3();
  2167. rotation = ( rotation instanceof THREE.Quaternion ) ? rotation : new THREE.Quaternion();
  2168. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  2169. scale.x = x.length();
  2170. scale.y = y.length();
  2171. scale.z = z.length();
  2172. translation.x = te[12];
  2173. translation.y = te[13];
  2174. translation.z = te[14];
  2175. // scale the rotation part
  2176. var matrix = THREE.Matrix4.__m1;
  2177. matrix.copy( this );
  2178. matrix.elements[0] /= scale.x;
  2179. matrix.elements[1] /= scale.x;
  2180. matrix.elements[2] /= scale.x;
  2181. matrix.elements[4] /= scale.y;
  2182. matrix.elements[5] /= scale.y;
  2183. matrix.elements[6] /= scale.y;
  2184. matrix.elements[8] /= scale.z;
  2185. matrix.elements[9] /= scale.z;
  2186. matrix.elements[10] /= scale.z;
  2187. rotation.setFromRotationMatrix( matrix );
  2188. return [ translation, rotation, scale ];
  2189. },
  2190. extractPosition: function ( m ) {
  2191. var te = this.elements;
  2192. var me = m.elements;
  2193. te[12] = me[12];
  2194. te[13] = me[13];
  2195. te[14] = me[14];
  2196. return this;
  2197. },
  2198. extractRotation: function ( m ) {
  2199. var te = this.elements;
  2200. var me = m.elements;
  2201. var vector = THREE.Matrix4.__v1;
  2202. var scaleX = 1 / vector.set( me[0], me[1], me[2] ).length();
  2203. var scaleY = 1 / vector.set( me[4], me[5], me[6] ).length();
  2204. var scaleZ = 1 / vector.set( me[8], me[9], me[10] ).length();
  2205. te[0] = me[0] * scaleX;
  2206. te[1] = me[1] * scaleX;
  2207. te[2] = me[2] * scaleX;
  2208. te[4] = me[4] * scaleY;
  2209. te[5] = me[5] * scaleY;
  2210. te[6] = me[6] * scaleY;
  2211. te[8] = me[8] * scaleZ;
  2212. te[9] = me[9] * scaleZ;
  2213. te[10] = me[10] * scaleZ;
  2214. return this;
  2215. },
  2216. //
  2217. translate: function ( v ) {
  2218. var te = this.elements;
  2219. var x = v.x, y = v.y, z = v.z;
  2220. te[12] = te[0] * x + te[4] * y + te[8] * z + te[12];
  2221. te[13] = te[1] * x + te[5] * y + te[9] * z + te[13];
  2222. te[14] = te[2] * x + te[6] * y + te[10] * z + te[14];
  2223. te[15] = te[3] * x + te[7] * y + te[11] * z + te[15];
  2224. return this;
  2225. },
  2226. rotateX: function ( angle ) {
  2227. var te = this.elements;
  2228. var m12 = te[4];
  2229. var m22 = te[5];
  2230. var m32 = te[6];
  2231. var m42 = te[7];
  2232. var m13 = te[8];
  2233. var m23 = te[9];
  2234. var m33 = te[10];
  2235. var m43 = te[11];
  2236. var c = Math.cos( angle );
  2237. var s = Math.sin( angle );
  2238. te[4] = c * m12 + s * m13;
  2239. te[5] = c * m22 + s * m23;
  2240. te[6] = c * m32 + s * m33;
  2241. te[7] = c * m42 + s * m43;
  2242. te[8] = c * m13 - s * m12;
  2243. te[9] = c * m23 - s * m22;
  2244. te[10] = c * m33 - s * m32;
  2245. te[11] = c * m43 - s * m42;
  2246. return this;
  2247. },
  2248. rotateY: function ( angle ) {
  2249. var te = this.elements;
  2250. var m11 = te[0];
  2251. var m21 = te[1];
  2252. var m31 = te[2];
  2253. var m41 = te[3];
  2254. var m13 = te[8];
  2255. var m23 = te[9];
  2256. var m33 = te[10];
  2257. var m43 = te[11];
  2258. var c = Math.cos( angle );
  2259. var s = Math.sin( angle );
  2260. te[0] = c * m11 - s * m13;
  2261. te[1] = c * m21 - s * m23;
  2262. te[2] = c * m31 - s * m33;
  2263. te[3] = c * m41 - s * m43;
  2264. te[8] = c * m13 + s * m11;
  2265. te[9] = c * m23 + s * m21;
  2266. te[10] = c * m33 + s * m31;
  2267. te[11] = c * m43 + s * m41;
  2268. return this;
  2269. },
  2270. rotateZ: function ( angle ) {
  2271. var te = this.elements;
  2272. var m11 = te[0];
  2273. var m21 = te[1];
  2274. var m31 = te[2];
  2275. var m41 = te[3];
  2276. var m12 = te[4];
  2277. var m22 = te[5];
  2278. var m32 = te[6];
  2279. var m42 = te[7];
  2280. var c = Math.cos( angle );
  2281. var s = Math.sin( angle );
  2282. te[0] = c * m11 + s * m12;
  2283. te[1] = c * m21 + s * m22;
  2284. te[2] = c * m31 + s * m32;
  2285. te[3] = c * m41 + s * m42;
  2286. te[4] = c * m12 - s * m11;
  2287. te[5] = c * m22 - s * m21;
  2288. te[6] = c * m32 - s * m31;
  2289. te[7] = c * m42 - s * m41;
  2290. return this;
  2291. },
  2292. rotateByAxis: function ( axis, angle ) {
  2293. var te = this.elements;
  2294. // optimize by checking axis
  2295. if ( axis.x === 1 && axis.y === 0 && axis.z === 0 ) {
  2296. return this.rotateX( angle );
  2297. } else if ( axis.x === 0 && axis.y === 1 && axis.z === 0 ) {
  2298. return this.rotateY( angle );
  2299. } else if ( axis.x === 0 && axis.y === 0 && axis.z === 1 ) {
  2300. return this.rotateZ( angle );
  2301. }
  2302. var x = axis.x, y = axis.y, z = axis.z;
  2303. var n = Math.sqrt(x * x + y * y + z * z);
  2304. x /= n;
  2305. y /= n;
  2306. z /= n;
  2307. var xx = x * x, yy = y * y, zz = z * z;
  2308. var c = Math.cos( angle );
  2309. var s = Math.sin( angle );
  2310. var oneMinusCosine = 1 - c;
  2311. var xy = x * y * oneMinusCosine;
  2312. var xz = x * z * oneMinusCosine;
  2313. var yz = y * z * oneMinusCosine;
  2314. var xs = x * s;
  2315. var ys = y * s;
  2316. var zs = z * s;
  2317. var r11 = xx + (1 - xx) * c;
  2318. var r21 = xy + zs;
  2319. var r31 = xz - ys;
  2320. var r12 = xy - zs;
  2321. var r22 = yy + (1 - yy) * c;
  2322. var r32 = yz + xs;
  2323. var r13 = xz + ys;
  2324. var r23 = yz - xs;
  2325. var r33 = zz + (1 - zz) * c;
  2326. var m11 = te[0], m21 = te[1], m31 = te[2], m41 = te[3];
  2327. var m12 = te[4], m22 = te[5], m32 = te[6], m42 = te[7];
  2328. var m13 = te[8], m23 = te[9], m33 = te[10], m43 = te[11];
  2329. var m14 = te[12], m24 = te[13], m34 = te[14], m44 = te[15];
  2330. te[0] = r11 * m11 + r21 * m12 + r31 * m13;
  2331. te[1] = r11 * m21 + r21 * m22 + r31 * m23;
  2332. te[2] = r11 * m31 + r21 * m32 + r31 * m33;
  2333. te[3] = r11 * m41 + r21 * m42 + r31 * m43;
  2334. te[4] = r12 * m11 + r22 * m12 + r32 * m13;
  2335. te[5] = r12 * m21 + r22 * m22 + r32 * m23;
  2336. te[6] = r12 * m31 + r22 * m32 + r32 * m33;
  2337. te[7] = r12 * m41 + r22 * m42 + r32 * m43;
  2338. te[8] = r13 * m11 + r23 * m12 + r33 * m13;
  2339. te[9] = r13 * m21 + r23 * m22 + r33 * m23;
  2340. te[10] = r13 * m31 + r23 * m32 + r33 * m33;
  2341. te[11] = r13 * m41 + r23 * m42 + r33 * m43;
  2342. return this;
  2343. },
  2344. scale: function ( v ) {
  2345. var te = this.elements;
  2346. var x = v.x, y = v.y, z = v.z;
  2347. te[0] *= x; te[4] *= y; te[8] *= z;
  2348. te[1] *= x; te[5] *= y; te[9] *= z;
  2349. te[2] *= x; te[6] *= y; te[10] *= z;
  2350. te[3] *= x; te[7] *= y; te[11] *= z;
  2351. return this;
  2352. },
  2353. getMaxScaleOnAxis: function () {
  2354. var te = this.elements;
  2355. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2356. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2357. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2358. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2359. },
  2360. //
  2361. makeTranslation: function ( offset ) {
  2362. this.set(
  2363. 1, 0, 0, offset.x,
  2364. 0, 1, 0, offset.y,
  2365. 0, 0, 1, offset.z,
  2366. 0, 0, 0, 1
  2367. );
  2368. return this;
  2369. },
  2370. makeRotationX: function ( theta ) {
  2371. var c = Math.cos( theta ), s = Math.sin( theta );
  2372. this.set(
  2373. 1, 0, 0, 0,
  2374. 0, c, -s, 0,
  2375. 0, s, c, 0,
  2376. 0, 0, 0, 1
  2377. );
  2378. return this;
  2379. },
  2380. makeRotationY: function ( theta ) {
  2381. var c = Math.cos( theta ), s = Math.sin( theta );
  2382. this.set(
  2383. c, 0, s, 0,
  2384. 0, 1, 0, 0,
  2385. -s, 0, c, 0,
  2386. 0, 0, 0, 1
  2387. );
  2388. return this;
  2389. },
  2390. makeRotationZ: function ( theta ) {
  2391. var c = Math.cos( theta ), s = Math.sin( theta );
  2392. this.set(
  2393. c, -s, 0, 0,
  2394. s, c, 0, 0,
  2395. 0, 0, 1, 0,
  2396. 0, 0, 0, 1
  2397. );
  2398. return this;
  2399. },
  2400. makeRotationAxis: function ( axis, angle ) {
  2401. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2402. var c = Math.cos( angle );
  2403. var s = Math.sin( angle );
  2404. var t = 1 - c;
  2405. var x = axis.x, y = axis.y, z = axis.z;
  2406. var tx = t * x, ty = t * y;
  2407. this.set(
  2408. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2409. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2410. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2411. 0, 0, 0, 1
  2412. );
  2413. return this;
  2414. },
  2415. makeScale: function ( factor ) {
  2416. this.set(
  2417. factor.x, 0, 0, 0,
  2418. 0, factor.y, 0, 0,
  2419. 0, 0, factor.z, 0,
  2420. 0, 0, 0, 1
  2421. );
  2422. return this;
  2423. },
  2424. makeFrustum: function ( left, right, bottom, top, near, far ) {
  2425. var te = this.elements;
  2426. var x = 2 * near / ( right - left );
  2427. var y = 2 * near / ( top - bottom );
  2428. var a = ( right + left ) / ( right - left );
  2429. var b = ( top + bottom ) / ( top - bottom );
  2430. var c = - ( far + near ) / ( far - near );
  2431. var d = - 2 * far * near / ( far - near );
  2432. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  2433. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  2434. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  2435. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  2436. return this;
  2437. },
  2438. makePerspective: function ( fov, aspect, near, far ) {
  2439. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  2440. var ymin = - ymax;
  2441. var xmin = ymin * aspect;
  2442. var xmax = ymax * aspect;
  2443. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  2444. },
  2445. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2446. var te = this.elements;
  2447. var w = right - left;
  2448. var h = top - bottom;
  2449. var p = far - near;
  2450. var x = ( right + left ) / w;
  2451. var y = ( top + bottom ) / h;
  2452. var z = ( far + near ) / p;
  2453. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  2454. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  2455. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  2456. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  2457. return this;
  2458. },
  2459. clone: function () {
  2460. var te = this.elements;
  2461. return new THREE.Matrix4(
  2462. te[0], te[4], te[8], te[12],
  2463. te[1], te[5], te[9], te[13],
  2464. te[2], te[6], te[10], te[14],
  2465. te[3], te[7], te[11], te[15]
  2466. );
  2467. }
  2468. };
  2469. THREE.Matrix4.__v1 = new THREE.Vector3();
  2470. THREE.Matrix4.__v2 = new THREE.Vector3();
  2471. THREE.Matrix4.__v3 = new THREE.Vector3();
  2472. THREE.Matrix4.__m1 = new THREE.Matrix4();
  2473. THREE.Matrix4.__m2 = new THREE.Matrix4();
  2474. /**
  2475. * @author bhouston / http://exocortex.com
  2476. */
  2477. THREE.Ray = function ( origin, direction ) {
  2478. this.origin = origin !== undefined ? origin.clone() : new THREE.Vector3();
  2479. this.direction = direction !== undefined ? direction.clone() : new THREE.Vector3();
  2480. };
  2481. THREE.Ray.prototype = {
  2482. constructor: THREE.Ray,
  2483. set: function ( origin, direction ) {
  2484. this.origin.copy( origin );
  2485. this.direction.copy( direction );
  2486. return this;
  2487. },
  2488. copy: function ( ray ) {
  2489. this.origin.copy( ray.origin );
  2490. this.direction.copy( ray.direction );
  2491. return this;
  2492. },
  2493. at: function( t, optionalTarget ) {
  2494. var result = optionalTarget || new THREE.Vector3();
  2495. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  2496. },
  2497. recast: function ( t ) {
  2498. this.origin.copy( this.at( t, THREE.Ray.__v1 ) );
  2499. return this;
  2500. },
  2501. closestPointToPoint: function ( point, optionalTarget ) {
  2502. var result = optionalTarget || new THREE.Vector3();
  2503. result.subVectors( point, this.origin );
  2504. var directionDistance = result.dot( this.direction );
  2505. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2506. },
  2507. distanceToPoint: function ( point ) {
  2508. var directionDistance = THREE.Ray.__v1.subVectors( point, this.origin ).dot( this.direction );
  2509. THREE.Ray.__v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2510. return THREE.Ray.__v1.distanceTo( point );
  2511. },
  2512. isIntersectionSphere: function( sphere ) {
  2513. return ( this.distanceToPoint( sphere.center ) <= sphere.radius );
  2514. },
  2515. isIntersectionPlane: function ( plane ) {
  2516. // check if the line and plane are non-perpendicular, if they
  2517. // eventually they will intersect.
  2518. var denominator = plane.normal.dot( this.direction );
  2519. if ( denominator != 0 ) {
  2520. return true;
  2521. }
  2522. // line is coplanar, return origin
  2523. if( plane.distanceToPoint( this.origin ) == 0 ) {
  2524. return true;
  2525. }
  2526. return false;
  2527. },
  2528. distanceToPlane: function ( plane ) {
  2529. var denominator = plane.normal.dot( this.direction );
  2530. if ( denominator == 0 ) {
  2531. // line is coplanar, return origin
  2532. if( plane.distanceToPoint( this.origin ) == 0 ) {
  2533. return 0;
  2534. }
  2535. // Unsure if this is the correct method to handle this case.
  2536. return undefined;
  2537. }
  2538. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  2539. return t;
  2540. },
  2541. intersectPlane: function ( plane, optionalTarget ) {
  2542. var t = this.distanceToPlane( plane );
  2543. if( t === undefined ) {
  2544. return undefined;
  2545. }
  2546. return this.at( t, optionalTarget );
  2547. },
  2548. transform: function ( matrix4 ) {
  2549. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  2550. this.origin.applyMatrix4( matrix4 );
  2551. this.direction.sub( this.origin );
  2552. return this;
  2553. },
  2554. equals: function ( ray ) {
  2555. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  2556. },
  2557. clone: function () {
  2558. return new THREE.Ray().copy( this );
  2559. }
  2560. };
  2561. THREE.Ray.__v1 = new THREE.Vector3();
  2562. THREE.Ray.__v2 = new THREE.Vector3();
  2563. /**
  2564. * @author bhouston / http://exocortex.com
  2565. * @author mrdoob / http://mrdoob.com/
  2566. */
  2567. THREE.Sphere = function ( center, radius ) {
  2568. this.center = center === undefined ? new THREE.Vector3() : center.clone();
  2569. this.radius = radius === undefined ? 0 : radius;
  2570. };
  2571. THREE.Sphere.prototype = {
  2572. constructor: THREE.Sphere,
  2573. set: function ( center, radius ) {
  2574. this.center.copy( center );
  2575. this.radius = radius;
  2576. return this;
  2577. },
  2578. setFromCenterAndPoints: function ( center, points ) {
  2579. var maxRadiusSq = 0;
  2580. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2581. var radiusSq = center.distanceToSquared( points[ i ] );
  2582. maxRadiusSq = Math.max( maxRadiusSq, radiusSq );
  2583. }
  2584. this.center = center;
  2585. this.radius = Math.sqrt( maxRadiusSq );
  2586. return this;
  2587. },
  2588. copy: function ( sphere ) {
  2589. this.center.copy( sphere.center );
  2590. this.radius = sphere.radius;
  2591. return this;
  2592. },
  2593. empty: function () {
  2594. return ( this.radius <= 0 );
  2595. },
  2596. containsPoint: function ( point ) {
  2597. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  2598. },
  2599. distanceToPoint: function ( point ) {
  2600. return ( point.distanceTo( this.center ) - this.radius );
  2601. },
  2602. intersectsSphere: function ( sphere ) {
  2603. var radiusSum = this.radius + sphere.radius;
  2604. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  2605. },
  2606. clampPoint: function ( point, optionalTarget ) {
  2607. var deltaLengthSq = this.center.distanceToSquared( point );
  2608. var result = optionalTarget || new THREE.Vector3();
  2609. result.copy( point );
  2610. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  2611. result.sub( this.center ).normalize();
  2612. result.multiplyScalar( this.radius ).add( this.center );
  2613. }
  2614. return result;
  2615. },
  2616. getBoundingBox: function ( optionalTarget ) {
  2617. var box = optionalTarget || new THREE.Box3();
  2618. box.set( this.center, this.center );
  2619. box.expandByScalar( this.radius );
  2620. return box;
  2621. },
  2622. transform: function ( matrix ) {
  2623. this.center.applyMatrix4( matrix );
  2624. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2625. return this;
  2626. },
  2627. translate: function ( offset ) {
  2628. this.center.add( offset );
  2629. return this;
  2630. },
  2631. equals: function ( sphere ) {
  2632. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  2633. },
  2634. clone: function () {
  2635. return new THREE.Sphere().copy( this );
  2636. }
  2637. };
  2638. /**
  2639. * @author mrdoob / http://mrdoob.com/
  2640. * @author alteredq / http://alteredqualia.com/
  2641. * @author bhouston / http://exocortex.com
  2642. */
  2643. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  2644. this.planes = [
  2645. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  2646. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  2647. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  2648. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  2649. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  2650. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  2651. ];
  2652. };
  2653. THREE.Frustum.prototype = {
  2654. set: function ( p0, p1, p2, p3, p4, p5 ) {
  2655. var planes = this.planes;
  2656. planes[0].copy( p0 );
  2657. planes[1].copy( p1 );
  2658. planes[2].copy( p2 );
  2659. planes[3].copy( p3 );
  2660. planes[4].copy( p4 );
  2661. planes[5].copy( p5 );
  2662. return this;
  2663. },
  2664. copy: function ( frustum ) {
  2665. var planes = this.planes;
  2666. for( var i = 0; i < 6; i ++ ) {
  2667. planes[i].copy( frustum.planes[i] );
  2668. }
  2669. return this;
  2670. },
  2671. setFromMatrix: function ( m ) {
  2672. var planes = this.planes;
  2673. var me = m.elements;
  2674. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  2675. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  2676. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  2677. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  2678. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  2679. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  2680. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  2681. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  2682. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  2683. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  2684. return this;
  2685. },
  2686. intersectsObject: function ( object ) {
  2687. // this method is expanded inlined for performance reasons.
  2688. var matrix = object.matrixWorld;
  2689. var planes = this.planes;
  2690. var center = matrix.getPosition();
  2691. var negRadius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  2692. for ( var i = 0; i < 6; i ++ ) {
  2693. var distance = planes[ i ].distanceToPoint( center );
  2694. if( distance < negRadius ) {
  2695. return false;
  2696. }
  2697. }
  2698. return true;
  2699. },
  2700. intersectsSphere: function ( sphere ) {
  2701. var planes = this.planes;
  2702. var center = sphere.center;
  2703. var negRadius = -sphere.radius;
  2704. for ( var i = 0; i < 6; i ++ ) {
  2705. var distance = planes[ i ].distanceToPoint( center );
  2706. if( distance < negRadius ) {
  2707. return false;
  2708. }
  2709. }
  2710. return true;
  2711. },
  2712. containsPoint: function ( point ) {
  2713. var planes = this.planes;
  2714. for ( var i = 0; i < 6; i ++ ) {
  2715. if( planes[ i ].distanceToPoint( point ) < 0 ) {
  2716. return false;
  2717. }
  2718. }
  2719. return true;
  2720. },
  2721. clone: function () {
  2722. var planes = this.planes;
  2723. return new THREE.Frustum( planes[0], planes[1], planes[2], planes[3], planes[4], planes[5] );
  2724. }
  2725. };
  2726. /**
  2727. * @author bhouston / http://exocortex.com
  2728. */
  2729. THREE.Plane = function ( normal, constant ) {
  2730. this.normal = normal !== undefined ? normal.clone() : new THREE.Vector3( 1, 0, 0 );
  2731. this.constant = constant !== undefined ? constant : 0;
  2732. };
  2733. THREE.Plane.prototype = {
  2734. constructor: THREE.Plane,
  2735. set: function ( normal, constant ) {
  2736. this.normal.copy( normal );
  2737. this.constant = constant;
  2738. return this;
  2739. },
  2740. setComponents: function ( x, y, z, w ) {
  2741. this.normal.set( x, y, z );
  2742. this.constant = w;
  2743. return this;
  2744. },
  2745. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  2746. this.normal.copy( normal ).normalize();
  2747. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  2748. return this;
  2749. },
  2750. setFromCoplanarPoints: function ( a, b, c ) {
  2751. var normal = THREE.Plane.__v1.subVectors( c, b ).cross( THREE.Plane.__v2.subVectors( a, b ) ).normalize();
  2752. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  2753. this.setFromNormalAndCoplanarPoint( normal, a );
  2754. return this;
  2755. },
  2756. copy: function ( plane ) {
  2757. this.normal.copy( plane.normal );
  2758. this.constant = plane.constant;
  2759. return this;
  2760. },
  2761. normalize: function () {
  2762. // Note: will lead to a divide by zero if the plane is invalid.
  2763. var inverseNormalLength = 1.0 / this.normal.length();
  2764. this.normal.multiplyScalar( inverseNormalLength );
  2765. this.constant *= inverseNormalLength;
  2766. return this;
  2767. },
  2768. negate: function () {
  2769. this.constant *= -1;
  2770. this.normal.negate();
  2771. return this;
  2772. },
  2773. distanceToPoint: function ( point ) {
  2774. return this.normal.dot( point ) + this.constant;
  2775. },
  2776. distanceToSphere: function ( sphere ) {
  2777. return this.distanceToPoint( sphere.center ) - sphere.radius;
  2778. },
  2779. projectPoint: function ( point, optionalTarget ) {
  2780. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  2781. },
  2782. orthoPoint: function ( point, optionalTarget ) {
  2783. var perpendicularMagnitude = this.distanceToPoint( point );
  2784. var result = optionalTarget || new THREE.Vector3();
  2785. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  2786. },
  2787. isIntersectionLine: function ( startPoint, endPoint ) {
  2788. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  2789. var startSign = this.distanceToPoint( startPoint );
  2790. var endSign = this.distanceToPoint( endPoint );
  2791. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  2792. },
  2793. intersectLine: function ( startPoint, endPoint, optionalTarget ) {
  2794. var result = optionalTarget || new THREE.Vector3();
  2795. var direction = THREE.Plane.__v1.subVectors( endPoint, startPoint );
  2796. var denominator = this.normal.dot( direction );
  2797. if ( denominator == 0 ) {
  2798. // line is coplanar, return origin
  2799. if( this.distanceToPoint( startPoint ) == 0 ) {
  2800. return result.copy( startPoint );
  2801. }
  2802. // Unsure if this is the correct method to handle this case.
  2803. return undefined;
  2804. }
  2805. var t = - ( startPoint.dot( this.normal ) + this.constant ) / denominator;
  2806. if( t < 0 || t > 1 ) {
  2807. return undefined;
  2808. }
  2809. return result.copy( direction ).multiplyScalar( t ).add( startPoint );
  2810. },
  2811. coplanarPoint: function ( optionalTarget ) {
  2812. var result = optionalTarget || new THREE.Vector3();
  2813. return result.copy( this.normal ).multiplyScalar( - this.constant );
  2814. },
  2815. transform: function ( matrix, optionalNormalMatrix ) {
  2816. // compute new normal based on theory here:
  2817. // http://www.songho.ca/opengl/gl_normaltransform.html
  2818. optionalNormalMatrix = optionalNormalMatrix || new THREE.Matrix3().getInverse( matrix ).transpose();
  2819. var newNormal = THREE.Plane.__v1.copy( this.normal ).applyMatrix3( optionalNormalMatrix );
  2820. var newCoplanarPoint = this.coplanarPoint( THREE.Plane.__v2 );
  2821. newCoplanarPoint.applyMatrix4( matrix );
  2822. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  2823. return this;
  2824. },
  2825. translate: function ( offset ) {
  2826. this.constant = this.constant - offset.dot( this.normal );
  2827. return this;
  2828. },
  2829. equals: function ( plane ) {
  2830. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  2831. },
  2832. clone: function () {
  2833. return new THREE.Plane().copy( this );
  2834. }
  2835. };
  2836. THREE.Plane.__vZero = new THREE.Vector3( 0, 0, 0 );
  2837. THREE.Plane.__v1 = new THREE.Vector3();
  2838. THREE.Plane.__v2 = new THREE.Vector3();
  2839. /**
  2840. * @author alteredq / http://alteredqualia.com/
  2841. */
  2842. THREE.Math = {
  2843. // Clamp value to range <a, b>
  2844. clamp: function ( x, a, b ) {
  2845. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  2846. },
  2847. // Clamp value to range <a, inf)
  2848. clampBottom: function ( x, a ) {
  2849. return x < a ? a : x;
  2850. },
  2851. // Linear mapping from range <a1, a2> to range <b1, b2>
  2852. mapLinear: function ( x, a1, a2, b1, b2 ) {
  2853. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  2854. },
  2855. // Random float from <0, 1> with 16 bits of randomness
  2856. // (standard Math.random() creates repetitive patterns when applied over larger space)
  2857. random16: function () {
  2858. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  2859. },
  2860. // Random integer from <low, high> interval
  2861. randInt: function ( low, high ) {
  2862. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  2863. },
  2864. // Random float from <low, high> interval
  2865. randFloat: function ( low, high ) {
  2866. return low + Math.random() * ( high - low );
  2867. },
  2868. // Random float from <-range/2, range/2> interval
  2869. randFloatSpread: function ( range ) {
  2870. return range * ( 0.5 - Math.random() );
  2871. },
  2872. sign: function ( x ) {
  2873. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  2874. },
  2875. degToRad: function ( degrees ) {
  2876. return degrees * THREE.Math.__d2r;
  2877. },
  2878. radToDeg: function ( radians ) {
  2879. return radians * THREE.Math.__r2d;
  2880. }
  2881. };
  2882. THREE.Math.__d2r = Math.PI / 180;
  2883. THREE.Math.__r2d = 180 / Math.PI;
  2884. /**
  2885. * @author mikael emtinger / http://gomo.se/
  2886. * @author alteredq / http://alteredqualia.com/
  2887. * @author WestLangley / http://github.com/WestLangley
  2888. * @author bhouston / http://exocortex.com
  2889. */
  2890. THREE.Quaternion = function( x, y, z, w ) {
  2891. this.x = x || 0;
  2892. this.y = y || 0;
  2893. this.z = z || 0;
  2894. this.w = ( w !== undefined ) ? w : 1;
  2895. };
  2896. THREE.Quaternion.prototype = {
  2897. constructor: THREE.Quaternion,
  2898. set: function ( x, y, z, w ) {
  2899. this.x = x;
  2900. this.y = y;
  2901. this.z = z;
  2902. this.w = w;
  2903. return this;
  2904. },
  2905. copy: function ( q ) {
  2906. this.x = q.x;
  2907. this.y = q.y;
  2908. this.z = q.z;
  2909. this.w = q.w;
  2910. return this;
  2911. },
  2912. setFromEuler: function ( v, order ) {
  2913. // http://www.mathworks.com/matlabcentral/fileexchange/
  2914. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2915. // content/SpinCalc.m
  2916. var c1 = Math.cos( v.x / 2 );
  2917. var c2 = Math.cos( v.y / 2 );
  2918. var c3 = Math.cos( v.z / 2 );
  2919. var s1 = Math.sin( v.x / 2 );
  2920. var s2 = Math.sin( v.y / 2 );
  2921. var s3 = Math.sin( v.z / 2 );
  2922. if ( order === undefined || order === 'XYZ' ) {
  2923. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2924. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2925. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2926. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2927. } else if ( order === 'YXZ' ) {
  2928. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2929. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2930. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2931. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2932. } else if ( order === 'ZXY' ) {
  2933. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2934. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2935. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2936. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2937. } else if ( order === 'ZYX' ) {
  2938. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2939. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2940. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2941. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2942. } else if ( order === 'YZX' ) {
  2943. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2944. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2945. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2946. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2947. } else if ( order === 'XZY' ) {
  2948. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2949. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2950. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2951. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2952. }
  2953. return this;
  2954. },
  2955. setFromAxisAngle: function ( axis, angle ) {
  2956. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2957. // axis have to be normalized
  2958. var halfAngle = angle / 2,
  2959. s = Math.sin( halfAngle );
  2960. this.x = axis.x * s;
  2961. this.y = axis.y * s;
  2962. this.z = axis.z * s;
  2963. this.w = Math.cos( halfAngle );
  2964. return this;
  2965. },
  2966. setFromRotationMatrix: function ( m ) {
  2967. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2968. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2969. var te = m.elements,
  2970. m11 = te[0], m12 = te[4], m13 = te[8],
  2971. m21 = te[1], m22 = te[5], m23 = te[9],
  2972. m31 = te[2], m32 = te[6], m33 = te[10],
  2973. trace = m11 + m22 + m33,
  2974. s;
  2975. if ( trace > 0 ) {
  2976. s = 0.5 / Math.sqrt( trace + 1.0 );
  2977. this.w = 0.25 / s;
  2978. this.x = ( m32 - m23 ) * s;
  2979. this.y = ( m13 - m31 ) * s;
  2980. this.z = ( m21 - m12 ) * s;
  2981. } else if ( m11 > m22 && m11 > m33 ) {
  2982. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2983. this.w = (m32 - m23 ) / s;
  2984. this.x = 0.25 * s;
  2985. this.y = (m12 + m21 ) / s;
  2986. this.z = (m13 + m31 ) / s;
  2987. } else if ( m22 > m33 ) {
  2988. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2989. this.w = (m13 - m31 ) / s;
  2990. this.x = (m12 + m21 ) / s;
  2991. this.y = 0.25 * s;
  2992. this.z = (m23 + m32 ) / s;
  2993. } else {
  2994. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2995. this.w = ( m21 - m12 ) / s;
  2996. this.x = ( m13 + m31 ) / s;
  2997. this.y = ( m23 + m32 ) / s;
  2998. this.z = 0.25 * s;
  2999. }
  3000. return this;
  3001. },
  3002. inverse: function () {
  3003. this.conjugate().normalize();
  3004. return this;
  3005. },
  3006. conjugate: function () {
  3007. this.x *= -1;
  3008. this.y *= -1;
  3009. this.z *= -1;
  3010. return this;
  3011. },
  3012. lengthSq: function () {
  3013. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  3014. },
  3015. length: function () {
  3016. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  3017. },
  3018. normalize: function () {
  3019. var l = this.length();
  3020. if ( l === 0 ) {
  3021. this.x = 0;
  3022. this.y = 0;
  3023. this.z = 0;
  3024. this.w = 1;
  3025. } else {
  3026. l = 1 / l;
  3027. this.x = this.x * l;
  3028. this.y = this.y * l;
  3029. this.z = this.z * l;
  3030. this.w = this.w * l;
  3031. }
  3032. return this;
  3033. },
  3034. multiply: function ( q, p ) {
  3035. if ( p !== undefined ) {
  3036. console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  3037. return this.multiplyQuaternions( q, p );
  3038. }
  3039. return this.multiplyQuaternions( this, q );
  3040. },
  3041. multiplyQuaternions: function ( a, b ) {
  3042. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  3043. var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w;
  3044. var qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  3045. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  3046. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  3047. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  3048. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  3049. return this;
  3050. },
  3051. slerp: function ( qb, t ) {
  3052. var x = this.x, y = this.y, z = this.z, w = this.w;
  3053. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  3054. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  3055. if ( cosHalfTheta < 0 ) {
  3056. this.w = -qb.w;
  3057. this.x = -qb.x;
  3058. this.y = -qb.y;
  3059. this.z = -qb.z;
  3060. cosHalfTheta = -cosHalfTheta;
  3061. } else {
  3062. this.copy( qb );
  3063. }
  3064. if ( cosHalfTheta >= 1.0 ) {
  3065. this.w = w;
  3066. this.x = x;
  3067. this.y = y;
  3068. this.z = z;
  3069. return this;
  3070. }
  3071. var halfTheta = Math.acos( cosHalfTheta );
  3072. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  3073. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  3074. this.w = 0.5 * ( w + this.w );
  3075. this.x = 0.5 * ( x + this.x );
  3076. this.y = 0.5 * ( y + this.y );
  3077. this.z = 0.5 * ( z + this.z );
  3078. return this;
  3079. }
  3080. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  3081. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  3082. this.w = ( w * ratioA + this.w * ratioB );
  3083. this.x = ( x * ratioA + this.x * ratioB );
  3084. this.y = ( y * ratioA + this.y * ratioB );
  3085. this.z = ( z * ratioA + this.z * ratioB );
  3086. return this;
  3087. },
  3088. equals: function ( v ) {
  3089. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  3090. },
  3091. clone: function () {
  3092. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  3093. }
  3094. }
  3095. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  3096. return qm.copy( qa ).slerp( qb, t );
  3097. }
  3098. /**
  3099. * Spline from Tween.js, slightly optimized (and trashed)
  3100. * http://sole.github.com/tween.js/examples/05_spline.html
  3101. *
  3102. * @author mrdoob / http://mrdoob.com/
  3103. * @author alteredq / http://alteredqualia.com/
  3104. */
  3105. THREE.Spline = function ( points ) {
  3106. this.points = points;
  3107. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3108. point, intPoint, weight, w2, w3,
  3109. pa, pb, pc, pd;
  3110. this.initFromArray = function( a ) {
  3111. this.points = [];
  3112. for ( var i = 0; i < a.length; i++ ) {
  3113. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3114. }
  3115. };
  3116. this.getPoint = function ( k ) {
  3117. point = ( this.points.length - 1 ) * k;
  3118. intPoint = Math.floor( point );
  3119. weight = point - intPoint;
  3120. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3121. c[ 1 ] = intPoint;
  3122. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3123. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3124. pa = this.points[ c[ 0 ] ];
  3125. pb = this.points[ c[ 1 ] ];
  3126. pc = this.points[ c[ 2 ] ];
  3127. pd = this.points[ c[ 3 ] ];
  3128. w2 = weight * weight;
  3129. w3 = weight * w2;
  3130. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3131. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3132. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3133. return v3;
  3134. };
  3135. this.getControlPointsArray = function () {
  3136. var i, p, l = this.points.length,
  3137. coords = [];
  3138. for ( i = 0; i < l; i ++ ) {
  3139. p = this.points[ i ];
  3140. coords[ i ] = [ p.x, p.y, p.z ];
  3141. }
  3142. return coords;
  3143. };
  3144. // approximate length by summing linear segments
  3145. this.getLength = function ( nSubDivisions ) {
  3146. var i, index, nSamples, position,
  3147. point = 0, intPoint = 0, oldIntPoint = 0,
  3148. oldPosition = new THREE.Vector3(),
  3149. tmpVec = new THREE.Vector3(),
  3150. chunkLengths = [],
  3151. totalLength = 0;
  3152. // first point has 0 length
  3153. chunkLengths[ 0 ] = 0;
  3154. if ( !nSubDivisions ) nSubDivisions = 100;
  3155. nSamples = this.points.length * nSubDivisions;
  3156. oldPosition.copy( this.points[ 0 ] );
  3157. for ( i = 1; i < nSamples; i ++ ) {
  3158. index = i / nSamples;
  3159. position = this.getPoint( index );
  3160. tmpVec.copy( position );
  3161. totalLength += tmpVec.distanceTo( oldPosition );
  3162. oldPosition.copy( position );
  3163. point = ( this.points.length - 1 ) * index;
  3164. intPoint = Math.floor( point );
  3165. if ( intPoint != oldIntPoint ) {
  3166. chunkLengths[ intPoint ] = totalLength;
  3167. oldIntPoint = intPoint;
  3168. }
  3169. }
  3170. // last point ends with total length
  3171. chunkLengths[ chunkLengths.length ] = totalLength;
  3172. return { chunks: chunkLengths, total: totalLength };
  3173. };
  3174. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3175. var i, j,
  3176. index, indexCurrent, indexNext,
  3177. linearDistance, realDistance,
  3178. sampling, position,
  3179. newpoints = [],
  3180. tmpVec = new THREE.Vector3(),
  3181. sl = this.getLength();
  3182. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3183. for ( i = 1; i < this.points.length; i++ ) {
  3184. //tmpVec.copy( this.points[ i - 1 ] );
  3185. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3186. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3187. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3188. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3189. indexNext = i / ( this.points.length - 1 );
  3190. for ( j = 1; j < sampling - 1; j++ ) {
  3191. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3192. position = this.getPoint( index );
  3193. newpoints.push( tmpVec.copy( position ).clone() );
  3194. }
  3195. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3196. }
  3197. this.points = newpoints;
  3198. };
  3199. // Catmull-Rom
  3200. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3201. var v0 = ( p2 - p0 ) * 0.5,
  3202. v1 = ( p3 - p1 ) * 0.5;
  3203. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3204. };
  3205. };
  3206. /**
  3207. * @author bhouston / http://exocortex.com
  3208. * @author mrdoob / http://mrdoob.com/
  3209. */
  3210. THREE.Triangle = function ( a, b, c ) {
  3211. this.a = new THREE.Vector3();
  3212. this.b = new THREE.Vector3();
  3213. this.c = new THREE.Vector3();
  3214. if( a !== undefined && b !== undefined && c !== undefined ) {
  3215. this.a.copy( a );
  3216. this.b.copy( b );
  3217. this.c.copy( c );
  3218. }
  3219. };
  3220. THREE.Triangle.normal = function( a, b, c, optionalTarget ) {
  3221. var result = optionalTarget || new THREE.Vector3();
  3222. result.subVectors( c, b );
  3223. THREE.Triangle.__v0.subVectors( a, b );
  3224. result.cross( THREE.Triangle.__v0 );
  3225. var resultLengthSq = result.lengthSq();
  3226. if( resultLengthSq > 0 ) {
  3227. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3228. }
  3229. return result.set( 0, 0, 0 );
  3230. };
  3231. // static/instance method to calculate barycoordinates
  3232. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3233. THREE.Triangle.barycoordFromPoint = function ( point, a, b, c, optionalTarget ) {
  3234. THREE.Triangle.__v0.subVectors( c, a );
  3235. THREE.Triangle.__v1.subVectors( b, a );
  3236. THREE.Triangle.__v2.subVectors( point, a );
  3237. var dot00 = THREE.Triangle.__v0.dot( THREE.Triangle.__v0 );
  3238. var dot01 = THREE.Triangle.__v0.dot( THREE.Triangle.__v1 );
  3239. var dot02 = THREE.Triangle.__v0.dot( THREE.Triangle.__v2 );
  3240. var dot11 = THREE.Triangle.__v1.dot( THREE.Triangle.__v1 );
  3241. var dot12 = THREE.Triangle.__v1.dot( THREE.Triangle.__v2 );
  3242. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3243. var result = optionalTarget || new THREE.Vector3();
  3244. // colinear or singular triangle
  3245. if( denom == 0 ) {
  3246. // arbitrary location outside of triangle?
  3247. // not sure if this is the best idea, maybe should be returning undefined
  3248. return result.set( -2, -1, -1 );
  3249. }
  3250. var invDenom = 1 / denom;
  3251. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3252. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3253. // barycoordinates must always sum to 1
  3254. return result.set( 1 - u - v, v, u );
  3255. };
  3256. THREE.Triangle.containsPoint = function ( point, a, b, c ) {
  3257. // NOTE: need to use __v3 here because __v0, __v1 and __v2 are used in barycoordFromPoint.
  3258. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, THREE.Triangle.__v3 );
  3259. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3260. };
  3261. THREE.Triangle.prototype = {
  3262. constructor: THREE.Triangle,
  3263. set: function ( a, b, c ) {
  3264. this.a.copy( a );
  3265. this.b.copy( b );
  3266. this.c.copy( c );
  3267. return this;
  3268. },
  3269. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3270. this.a.copy( points[i0] );
  3271. this.b.copy( points[i1] );
  3272. this.c.copy( points[i2] );
  3273. return this;
  3274. },
  3275. copy: function ( triangle ) {
  3276. this.a.copy( triangle.a );
  3277. this.b.copy( triangle.b );
  3278. this.c.copy( triangle.c );
  3279. return this;
  3280. },
  3281. area: function () {
  3282. THREE.Triangle.__v0.subVectors( this.c, this.b );
  3283. THREE.Triangle.__v1.subVectors( this.a, this.b );
  3284. return THREE.Triangle.__v0.cross( THREE.Triangle.__v1 ).length() * 0.5;
  3285. },
  3286. midpoint: function ( optionalTarget ) {
  3287. var result = optionalTarget || new THREE.Vector3();
  3288. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  3289. },
  3290. normal: function ( optionalTarget ) {
  3291. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3292. },
  3293. plane: function ( optionalTarget ) {
  3294. var result = optionalTarget || new THREE.Plane();
  3295. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  3296. },
  3297. barycoordFromPoint: function ( point, optionalTarget ) {
  3298. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  3299. },
  3300. containsPoint: function ( point ) {
  3301. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  3302. },
  3303. equals: function ( triangle ) {
  3304. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  3305. },
  3306. clone: function () {
  3307. return new THREE.Triangle().copy( this );
  3308. }
  3309. };
  3310. THREE.Triangle.__v0 = new THREE.Vector3();
  3311. THREE.Triangle.__v1 = new THREE.Vector3();
  3312. THREE.Triangle.__v2 = new THREE.Vector3();
  3313. THREE.Triangle.__v3 = new THREE.Vector3();
  3314. /**
  3315. * @author mrdoob / http://mrdoob.com/
  3316. */
  3317. THREE.Vertex = function ( v ) {
  3318. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  3319. return v;
  3320. };
  3321. /**
  3322. * @author mrdoob / http://mrdoob.com/
  3323. */
  3324. THREE.UV = function ( u, v ) {
  3325. console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
  3326. return new THREE.Vector2( u, v );
  3327. };
  3328. /**
  3329. * @author alteredq / http://alteredqualia.com/
  3330. */
  3331. THREE.Clock = function ( autoStart ) {
  3332. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  3333. this.startTime = 0;
  3334. this.oldTime = 0;
  3335. this.elapsedTime = 0;
  3336. this.running = false;
  3337. };
  3338. THREE.Clock.prototype.start = function () {
  3339. this.startTime = Date.now();
  3340. this.oldTime = this.startTime;
  3341. this.running = true;
  3342. };
  3343. THREE.Clock.prototype.stop = function () {
  3344. this.getElapsedTime();
  3345. this.running = false;
  3346. };
  3347. THREE.Clock.prototype.getElapsedTime = function () {
  3348. this.getDelta();
  3349. return this.elapsedTime;
  3350. };
  3351. THREE.Clock.prototype.getDelta = function () {
  3352. var diff = 0;
  3353. if ( this.autoStart && ! this.running ) {
  3354. this.start();
  3355. }
  3356. if ( this.running ) {
  3357. var newTime = Date.now();
  3358. diff = 0.001 * ( newTime - this.oldTime );
  3359. this.oldTime = newTime;
  3360. this.elapsedTime += diff;
  3361. }
  3362. return diff;
  3363. };/**
  3364. * https://github.com/mrdoob/eventdispatcher.js/
  3365. */
  3366. THREE.EventDispatcher = function () {
  3367. var listeners = {};
  3368. this.addEventListener = function ( type, listener ) {
  3369. if ( listeners[ type ] === undefined ) {
  3370. listeners[ type ] = [];
  3371. }
  3372. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  3373. listeners[ type ].push( listener );
  3374. }
  3375. };
  3376. this.removeEventListener = function ( type, listener ) {
  3377. var index = listeners[ type ].indexOf( listener );
  3378. if ( index !== - 1 ) {
  3379. listeners[ type ].splice( index, 1 );
  3380. }
  3381. };
  3382. this.dispatchEvent = function ( event ) {
  3383. var listenerArray = listeners[ event.type ];
  3384. if ( listenerArray !== undefined ) {
  3385. event.target = this;
  3386. for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
  3387. listenerArray[ i ].call( this, event );
  3388. }
  3389. }
  3390. };
  3391. };
  3392. /**
  3393. * @author mrdoob / http://mrdoob.com/
  3394. * @author bhouston / http://exocortex.com/
  3395. */
  3396. ( function ( THREE ) {
  3397. THREE.Raycaster = function ( origin, direction, near, far ) {
  3398. this.ray = new THREE.Ray( origin, direction );
  3399. // normalized ray.direction required for accurate distance calculations
  3400. if( this.ray.direction.length() > 0 ) {
  3401. this.ray.direction.normalize();
  3402. }
  3403. this.near = near || 0;
  3404. this.far = far || Infinity;
  3405. };
  3406. var sphere = new THREE.Sphere();
  3407. var localRay = new THREE.Ray();
  3408. var facePlane = new THREE.Plane();
  3409. var intersectPoint = new THREE.Vector3();
  3410. var inverseMatrix = new THREE.Matrix4();
  3411. var descSort = function ( a, b ) {
  3412. return a.distance - b.distance;
  3413. };
  3414. var intersectObject = function ( object, raycaster, intersects ) {
  3415. if ( object instanceof THREE.Particle ) {
  3416. var distance = raycaster.ray.distanceToPoint( object.matrixWorld.getPosition() );
  3417. if ( distance > object.scale.x ) {
  3418. return intersects;
  3419. }
  3420. intersects.push( {
  3421. distance: distance,
  3422. point: object.position,
  3423. face: null,
  3424. object: object
  3425. } );
  3426. } else if ( object instanceof THREE.Mesh ) {
  3427. // Checking boundingSphere distance to ray
  3428. sphere.set(
  3429. object.matrixWorld.getPosition(),
  3430. object.geometry.boundingSphere.radius* object.matrixWorld.getMaxScaleOnAxis() );
  3431. if ( ! raycaster.ray.isIntersectionSphere( sphere ) ) {
  3432. return intersects;
  3433. }
  3434. // Checking faces
  3435. var geometry = object.geometry;
  3436. var vertices = geometry.vertices;
  3437. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3438. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  3439. var side = object.material.side;
  3440. var a, b, c, d;
  3441. var precision = raycaster.precision;
  3442. object.matrixRotationWorld.extractRotation( object.matrixWorld );
  3443. inverseMatrix.getInverse( object.matrixWorld );
  3444. localRay.copy( raycaster.ray ).transform( inverseMatrix );
  3445. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  3446. var face = geometry.faces[ f ];
  3447. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  3448. if ( material === undefined ) continue;
  3449. facePlane.setFromNormalAndCoplanarPoint( face.normal, vertices[face.a] );
  3450. var planeDistance = localRay.distanceToPlane( facePlane );
  3451. // bail if raycaster and plane are parallel
  3452. if ( Math.abs( planeDistance ) < precision ) continue;
  3453. // if negative distance, then plane is behind raycaster
  3454. if ( planeDistance < 0 ) continue;
  3455. // check if we hit the wrong side of a single sided face
  3456. side = material.side;
  3457. if( side !== THREE.DoubleSide ) {
  3458. var planeSign = localRay.direction.dot( facePlane.normal );
  3459. if( ! ( side === THREE.FrontSide ? planeSign < 0 : planeSign > 0 ) ) continue;
  3460. }
  3461. // this can be done using the planeDistance from localRay because localRay wasn't normalized, but ray was
  3462. if ( planeDistance < raycaster.near || planeDistance > raycaster.far ) continue;
  3463. intersectPoint = localRay.at( planeDistance, intersectPoint ); // passing in intersectPoint avoids a copy
  3464. if ( face instanceof THREE.Face3 ) {
  3465. a = vertices[ face.a ];
  3466. b = vertices[ face.b ];
  3467. c = vertices[ face.c ];
  3468. if ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, c ) ) continue;
  3469. } else if ( face instanceof THREE.Face4 ) {
  3470. a = vertices[ face.a ];
  3471. b = vertices[ face.b ];
  3472. c = vertices[ face.c ];
  3473. d = vertices[ face.d ];
  3474. if ( ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, d ) ) &&
  3475. ( ! THREE.Triangle.containsPoint( intersectPoint, b, c, d ) ) ) continue;
  3476. } else {
  3477. // This is added because if we call out of this if/else group when none of the cases
  3478. // match it will add a point to the intersection list erroneously.
  3479. throw Error( "face type not supported" );
  3480. }
  3481. intersects.push( {
  3482. distance: planeDistance, // this works because the original ray was normalized, and the transformed localRay wasn't
  3483. point: raycaster.ray.at( planeDistance ),
  3484. face: face,
  3485. faceIndex: f,
  3486. object: object
  3487. } );
  3488. }
  3489. }
  3490. };
  3491. var intersectDescendants = function ( object, raycaster, intersects ) {
  3492. var descendants = object.getDescendants();
  3493. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  3494. intersectObject( descendants[ i ], raycaster, intersects );
  3495. }
  3496. };
  3497. //
  3498. THREE.Raycaster.prototype.precision = 0.0001;
  3499. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  3500. this.ray.set( origin, direction );
  3501. // normalized ray.direction required for accurate distance calculations
  3502. if( this.ray.direction.length() > 0 ) {
  3503. this.ray.direction.normalize();
  3504. }
  3505. };
  3506. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  3507. var intersects = [];
  3508. if ( recursive === true ) {
  3509. intersectDescendants( object, this, intersects );
  3510. }
  3511. intersectObject( object, this, intersects );
  3512. intersects.sort( descSort );
  3513. return intersects;
  3514. };
  3515. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  3516. var intersects = [];
  3517. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  3518. intersectObject( objects[ i ], this, intersects );
  3519. if ( recursive === true ) {
  3520. intersectDescendants( objects[ i ], this, intersects );
  3521. }
  3522. }
  3523. intersects.sort( descSort );
  3524. return intersects;
  3525. };
  3526. }( THREE ) );
  3527. /**
  3528. * @author mrdoob / http://mrdoob.com/
  3529. * @author mikael emtinger / http://gomo.se/
  3530. * @author alteredq / http://alteredqualia.com/
  3531. */
  3532. THREE.Object3D = function () {
  3533. this.id = THREE.Object3DIdCount ++;
  3534. this.name = '';
  3535. this.properties = {};
  3536. this.parent = undefined;
  3537. this.children = [];
  3538. this.up = new THREE.Vector3( 0, 1, 0 );
  3539. this.position = new THREE.Vector3();
  3540. this.rotation = new THREE.Vector3();
  3541. this.eulerOrder = THREE.Object3D.defaultEulerOrder;
  3542. this.scale = new THREE.Vector3( 1, 1, 1 );
  3543. this.renderDepth = null;
  3544. this.rotationAutoUpdate = true;
  3545. this.matrix = new THREE.Matrix4();
  3546. this.matrixWorld = new THREE.Matrix4();
  3547. this.matrixRotationWorld = new THREE.Matrix4();
  3548. this.matrixAutoUpdate = true;
  3549. this.matrixWorldNeedsUpdate = true;
  3550. this.quaternion = new THREE.Quaternion();
  3551. this.useQuaternion = false;
  3552. this.visible = true;
  3553. this.castShadow = false;
  3554. this.receiveShadow = false;
  3555. this.frustumCulled = true;
  3556. this._vector = new THREE.Vector3();
  3557. };
  3558. THREE.Object3D.prototype = {
  3559. constructor: THREE.Object3D,
  3560. applyMatrix: function ( matrix ) {
  3561. this.matrix.multiplyMatrices( matrix, this.matrix );
  3562. this.scale.getScaleFromMatrix( this.matrix );
  3563. var mat = new THREE.Matrix4().extractRotation( this.matrix );
  3564. this.rotation.setEulerFromRotationMatrix( mat, this.eulerOrder );
  3565. this.position.getPositionFromMatrix( this.matrix );
  3566. },
  3567. translate: function ( distance, axis ) {
  3568. this.matrix.rotateAxis( axis );
  3569. this.position.add( axis.multiplyScalar( distance ) );
  3570. },
  3571. translateX: function ( distance ) {
  3572. this.translate( distance, this._vector.set( 1, 0, 0 ) );
  3573. },
  3574. translateY: function ( distance ) {
  3575. this.translate( distance, this._vector.set( 0, 1, 0 ) );
  3576. },
  3577. translateZ: function ( distance ) {
  3578. this.translate( distance, this._vector.set( 0, 0, 1 ) );
  3579. },
  3580. localToWorld: function ( vector ) {
  3581. return vector.applyMatrix4( this.matrixWorld );
  3582. },
  3583. worldToLocal: function ( vector ) {
  3584. return vector.applyMatrix4( THREE.Object3D.__m1.getInverse( this.matrixWorld ) );
  3585. },
  3586. lookAt: function ( vector ) {
  3587. // TODO: Add hierarchy support.
  3588. this.matrix.lookAt( vector, this.position, this.up );
  3589. if ( this.rotationAutoUpdate ) {
  3590. if ( this.useQuaternion === false ) {
  3591. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  3592. } else {
  3593. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  3594. }
  3595. }
  3596. },
  3597. add: function ( object ) {
  3598. if ( object === this ) {
  3599. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  3600. return;
  3601. }
  3602. if ( object instanceof THREE.Object3D ) {
  3603. if ( object.parent !== undefined ) {
  3604. object.parent.remove( object );
  3605. }
  3606. object.parent = this;
  3607. this.children.push( object );
  3608. // add to scene
  3609. var scene = this;
  3610. while ( scene.parent !== undefined ) {
  3611. scene = scene.parent;
  3612. }
  3613. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  3614. scene.__addObject( object );
  3615. }
  3616. }
  3617. },
  3618. remove: function ( object ) {
  3619. var index = this.children.indexOf( object );
  3620. if ( index !== - 1 ) {
  3621. object.parent = undefined;
  3622. this.children.splice( index, 1 );
  3623. // remove from scene
  3624. var scene = this;
  3625. while ( scene.parent !== undefined ) {
  3626. scene = scene.parent;
  3627. }
  3628. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  3629. scene.__removeObject( object );
  3630. }
  3631. }
  3632. },
  3633. traverse: function ( callback ) {
  3634. callback( this );
  3635. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3636. this.children[ i ].traverse( callback );
  3637. }
  3638. },
  3639. getChildByName: function ( name, recursive ) {
  3640. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3641. var child = this.children[ i ];
  3642. if ( child.name === name ) {
  3643. return child;
  3644. }
  3645. if ( recursive === true ) {
  3646. child = child.getChildByName( name, recursive );
  3647. if ( child !== undefined ) {
  3648. return child;
  3649. }
  3650. }
  3651. }
  3652. return undefined;
  3653. },
  3654. getDescendants: function ( array ) {
  3655. if ( array === undefined ) array = [];
  3656. Array.prototype.push.apply( array, this.children );
  3657. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3658. this.children[ i ].getDescendants( array );
  3659. }
  3660. return array;
  3661. },
  3662. updateMatrix: function () {
  3663. this.matrix.setPosition( this.position );
  3664. if ( this.useQuaternion === false ) {
  3665. this.matrix.setRotationFromEuler( this.rotation, this.eulerOrder );
  3666. } else {
  3667. this.matrix.setRotationFromQuaternion( this.quaternion );
  3668. }
  3669. if ( this.scale.x !== 1 || this.scale.y !== 1 || this.scale.z !== 1 ) {
  3670. this.matrix.scale( this.scale );
  3671. }
  3672. this.matrixWorldNeedsUpdate = true;
  3673. },
  3674. updateMatrixWorld: function ( force ) {
  3675. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  3676. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  3677. if ( this.parent === undefined ) {
  3678. this.matrixWorld.copy( this.matrix );
  3679. } else {
  3680. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  3681. }
  3682. this.matrixWorldNeedsUpdate = false;
  3683. force = true;
  3684. }
  3685. // update children
  3686. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3687. this.children[ i ].updateMatrixWorld( force );
  3688. }
  3689. },
  3690. clone: function ( object ) {
  3691. if ( object === undefined ) object = new THREE.Object3D();
  3692. object.name = this.name;
  3693. object.up.copy( this.up );
  3694. object.position.copy( this.position );
  3695. if ( object.rotation instanceof THREE.Vector3 ) object.rotation.copy( this.rotation ); // because of Sprite madness
  3696. object.eulerOrder = this.eulerOrder;
  3697. object.scale.copy( this.scale );
  3698. object.renderDepth = this.renderDepth;
  3699. object.rotationAutoUpdate = this.rotationAutoUpdate;
  3700. object.matrix.copy( this.matrix );
  3701. object.matrixWorld.copy( this.matrixWorld );
  3702. object.matrixRotationWorld.copy( this.matrixRotationWorld );
  3703. object.matrixAutoUpdate = this.matrixAutoUpdate;
  3704. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  3705. object.quaternion.copy( this.quaternion );
  3706. object.useQuaternion = this.useQuaternion;
  3707. object.visible = this.visible;
  3708. object.castShadow = this.castShadow;
  3709. object.receiveShadow = this.receiveShadow;
  3710. object.frustumCulled = this.frustumCulled;
  3711. for ( var i = 0; i < this.children.length; i ++ ) {
  3712. var child = this.children[ i ];
  3713. object.add( child.clone() );
  3714. }
  3715. return object;
  3716. }
  3717. };
  3718. THREE.Object3D.__m1 = new THREE.Matrix4();
  3719. THREE.Object3D.defaultEulerOrder = 'XYZ',
  3720. THREE.Object3DIdCount = 0;
  3721. /**
  3722. * @author mrdoob / http://mrdoob.com/
  3723. * @author supereggbert / http://www.paulbrunt.co.uk/
  3724. * @author julianwa / https://github.com/julianwa
  3725. */
  3726. THREE.Projector = function() {
  3727. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  3728. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  3729. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  3730. _face4Count, _face4Pool = [], _face4PoolLength = 0,
  3731. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  3732. _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
  3733. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  3734. _vector3 = new THREE.Vector3(),
  3735. _vector4 = new THREE.Vector4(),
  3736. _viewMatrix = new THREE.Matrix4(),
  3737. _viewProjectionMatrix = new THREE.Matrix4(),
  3738. _modelMatrix,
  3739. _modelViewProjectionMatrix = new THREE.Matrix4(),
  3740. _normalMatrix = new THREE.Matrix3(),
  3741. _normalViewMatrix = new THREE.Matrix3(),
  3742. _centroid = new THREE.Vector3(),
  3743. _frustum = new THREE.Frustum(),
  3744. _clippedVertex1PositionScreen = new THREE.Vector4(),
  3745. _clippedVertex2PositionScreen = new THREE.Vector4(),
  3746. _face3VertexNormals;
  3747. this.projectVector = function ( vector, camera ) {
  3748. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  3749. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  3750. return vector.applyMatrix4( _viewProjectionMatrix );
  3751. };
  3752. this.unprojectVector = function ( vector, camera ) {
  3753. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  3754. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, camera.projectionMatrixInverse );
  3755. return vector.applyMatrix4( _viewProjectionMatrix );
  3756. };
  3757. this.pickingRay = function ( vector, camera ) {
  3758. // set two vectors with opposing z values
  3759. vector.z = -1.0;
  3760. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  3761. this.unprojectVector( vector, camera );
  3762. this.unprojectVector( end, camera );
  3763. // find direction from vector to end
  3764. end.sub( vector ).normalize();
  3765. return new THREE.Raycaster( vector, end );
  3766. };
  3767. var projectGraph = function ( root, sortObjects ) {
  3768. _objectCount = 0;
  3769. _renderData.objects.length = 0;
  3770. _renderData.sprites.length = 0;
  3771. _renderData.lights.length = 0;
  3772. var projectObject = function ( parent ) {
  3773. for ( var c = 0, cl = parent.children.length; c < cl; c ++ ) {
  3774. var object = parent.children[ c ];
  3775. if ( object.visible === false ) continue;
  3776. if ( object instanceof THREE.Light ) {
  3777. _renderData.lights.push( object );
  3778. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  3779. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  3780. _object = getNextObjectInPool();
  3781. _object.object = object;
  3782. if ( object.renderDepth !== null ) {
  3783. _object.z = object.renderDepth;
  3784. } else {
  3785. _vector3.copy( object.matrixWorld.getPosition() );
  3786. _vector3.applyMatrix4( _viewProjectionMatrix );
  3787. _object.z = _vector3.z;
  3788. }
  3789. _renderData.objects.push( _object );
  3790. }
  3791. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  3792. _object = getNextObjectInPool();
  3793. _object.object = object;
  3794. // TODO: Find an elegant and performant solution and remove this dupe code.
  3795. if ( object.renderDepth !== null ) {
  3796. _object.z = object.renderDepth;
  3797. } else {
  3798. _vector3.copy( object.matrixWorld.getPosition() );
  3799. _vector3.applyMatrix4( _viewProjectionMatrix );
  3800. _object.z = _vector3.z;
  3801. }
  3802. _renderData.sprites.push( _object );
  3803. } else {
  3804. _object = getNextObjectInPool();
  3805. _object.object = object;
  3806. if ( object.renderDepth !== null ) {
  3807. _object.z = object.renderDepth;
  3808. } else {
  3809. _vector3.copy( object.matrixWorld.getPosition() );
  3810. _vector3.applyMatrix4( _viewProjectionMatrix );
  3811. _object.z = _vector3.z;
  3812. }
  3813. _renderData.objects.push( _object );
  3814. }
  3815. projectObject( object );
  3816. }
  3817. };
  3818. projectObject( root );
  3819. if ( sortObjects === true ) _renderData.objects.sort( painterSort );
  3820. return _renderData;
  3821. };
  3822. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  3823. var near = camera.near, far = camera.far, visible = false,
  3824. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  3825. geometry, vertices, vertex, vertexPositionScreen,
  3826. faces, face, faceVertexNormals, faceVertexUvs, uvs,
  3827. v1, v2, v3, v4, isFaceMaterial, objectMaterials;
  3828. _face3Count = 0;
  3829. _face4Count = 0;
  3830. _lineCount = 0;
  3831. _particleCount = 0;
  3832. _renderData.elements.length = 0;
  3833. scene.updateMatrixWorld();
  3834. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  3835. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  3836. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  3837. _normalViewMatrix.getInverse( _viewMatrix );
  3838. _normalViewMatrix.transpose();
  3839. _frustum.setFromMatrix( _viewProjectionMatrix );
  3840. _renderData = projectGraph( scene, sortObjects );
  3841. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  3842. object = _renderData.objects[ o ].object;
  3843. _modelMatrix = object.matrixWorld;
  3844. _vertexCount = 0;
  3845. if ( object instanceof THREE.Mesh ) {
  3846. geometry = object.geometry;
  3847. vertices = geometry.vertices;
  3848. faces = geometry.faces;
  3849. faceVertexUvs = geometry.faceVertexUvs;
  3850. _normalMatrix.getInverse( _modelMatrix );
  3851. _normalMatrix.transpose();
  3852. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3853. objectMaterials = isFaceMaterial === true ? object.material : null;
  3854. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  3855. _vertex = getNextVertexInPool();
  3856. _vertex.positionWorld.copy( vertices[ v ] );
  3857. _vertex.positionWorld.applyMatrix4( _modelMatrix );
  3858. _vertex.positionScreen.copy( _vertex.positionWorld );
  3859. _vertex.positionScreen.applyMatrix4( _viewProjectionMatrix );
  3860. _vertex.positionScreen.multiplyScalar( 1 / _vertex.positionScreen.w );
  3861. _vertex.visible = _vertex.positionScreen.z > -1 && _vertex.positionScreen.z < 1;
  3862. }
  3863. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  3864. face = faces[ f ];
  3865. var material = isFaceMaterial === true
  3866. ? objectMaterials.materials[ face.materialIndex ]
  3867. : object.material;
  3868. if ( material === undefined ) continue;
  3869. var side = material.side;
  3870. if ( face instanceof THREE.Face3 ) {
  3871. v1 = _vertexPool[ face.a ];
  3872. v2 = _vertexPool[ face.b ];
  3873. v3 = _vertexPool[ face.c ];
  3874. if ( v1.visible === true && v2.visible === true && v3.visible === true ) {
  3875. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  3876. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  3877. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  3878. _face = getNextFace3InPool();
  3879. _face.v1.copy( v1 );
  3880. _face.v2.copy( v2 );
  3881. _face.v3.copy( v3 );
  3882. } else {
  3883. continue;
  3884. }
  3885. } else {
  3886. continue;
  3887. }
  3888. } else if ( face instanceof THREE.Face4 ) {
  3889. v1 = _vertexPool[ face.a ];
  3890. v2 = _vertexPool[ face.b ];
  3891. v3 = _vertexPool[ face.c ];
  3892. v4 = _vertexPool[ face.d ];
  3893. if ( v1.visible === true && v2.visible === true && v3.visible === true && v4.visible === true ) {
  3894. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  3895. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  3896. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  3897. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  3898. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  3899. _face = getNextFace4InPool();
  3900. _face.v1.copy( v1 );
  3901. _face.v2.copy( v2 );
  3902. _face.v3.copy( v3 );
  3903. _face.v4.copy( v4 );
  3904. } else {
  3905. continue;
  3906. }
  3907. } else {
  3908. continue;
  3909. }
  3910. }
  3911. _face.normalModel.copy( face.normal );
  3912. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  3913. _face.normalModel.negate();
  3914. }
  3915. _face.normalModel.applyMatrix3( _normalMatrix );
  3916. _face.normalModel.normalize();
  3917. _face.normalModelView.copy( _face.normalModel );
  3918. _face.normalModelView.applyMatrix3( _normalViewMatrix );
  3919. _face.centroidModel.copy( face.centroid );
  3920. _face.centroidModel.applyMatrix4( _modelMatrix );
  3921. faceVertexNormals = face.vertexNormals;
  3922. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  3923. var normalModel = _face.vertexNormalsModel[ n ];
  3924. normalModel.copy( faceVertexNormals[ n ] );
  3925. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  3926. normalModel.negate();
  3927. }
  3928. normalModel.applyMatrix3( _normalMatrix );
  3929. normalModel.normalize();
  3930. var normalModelView = _face.vertexNormalsModelView[ n ];
  3931. normalModelView.copy( normalModel );
  3932. normalModelView.applyMatrix3( _normalViewMatrix );
  3933. }
  3934. _face.vertexNormalsLength = faceVertexNormals.length;
  3935. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  3936. uvs = faceVertexUvs[ c ][ f ];
  3937. if ( uvs === undefined ) continue;
  3938. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  3939. _face.uvs[ c ][ u ] = uvs[ u ];
  3940. }
  3941. }
  3942. _face.color = face.color;
  3943. _face.material = material;
  3944. _centroid.copy( _face.centroidModel )
  3945. _centroid.applyMatrix4( _viewProjectionMatrix );
  3946. _face.z = _centroid.z;
  3947. _renderData.elements.push( _face );
  3948. }
  3949. } else if ( object instanceof THREE.Line ) {
  3950. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  3951. vertices = object.geometry.vertices;
  3952. v1 = getNextVertexInPool();
  3953. v1.positionScreen.copy( vertices[ 0 ] );
  3954. v1.positionScreen.applyMatrix4( _modelViewProjectionMatrix );
  3955. // Handle LineStrip and LinePieces
  3956. var step = object.type === THREE.LinePieces ? 2 : 1;
  3957. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  3958. v1 = getNextVertexInPool();
  3959. v1.positionScreen.copy( vertices[ v ] );
  3960. v1.positionScreen.applyMatrix4( _modelViewProjectionMatrix );
  3961. if ( ( v + 1 ) % step > 0 ) continue;
  3962. v2 = _vertexPool[ _vertexCount - 2 ];
  3963. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  3964. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  3965. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  3966. // Perform the perspective divide
  3967. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  3968. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  3969. _line = getNextLineInPool();
  3970. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  3971. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  3972. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  3973. _line.material = object.material;
  3974. _renderData.elements.push( _line );
  3975. }
  3976. }
  3977. }
  3978. }
  3979. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  3980. object = _renderData.sprites[ o ].object;
  3981. _modelMatrix = object.matrixWorld;
  3982. if ( object instanceof THREE.Particle ) {
  3983. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  3984. _vector4.applyMatrix4( _viewProjectionMatrix );
  3985. _vector4.z /= _vector4.w;
  3986. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  3987. _particle = getNextParticleInPool();
  3988. _particle.object = object;
  3989. _particle.x = _vector4.x / _vector4.w;
  3990. _particle.y = _vector4.y / _vector4.w;
  3991. _particle.z = _vector4.z;
  3992. _particle.rotation = object.rotation.z;
  3993. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  3994. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  3995. _particle.material = object.material;
  3996. _renderData.elements.push( _particle );
  3997. }
  3998. }
  3999. }
  4000. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  4001. return _renderData;
  4002. };
  4003. // Pools
  4004. function getNextObjectInPool() {
  4005. if ( _objectCount === _objectPoolLength ) {
  4006. var object = new THREE.RenderableObject();
  4007. _objectPool.push( object );
  4008. _objectPoolLength ++;
  4009. _objectCount ++;
  4010. return object;
  4011. }
  4012. return _objectPool[ _objectCount ++ ];
  4013. }
  4014. function getNextVertexInPool() {
  4015. if ( _vertexCount === _vertexPoolLength ) {
  4016. var vertex = new THREE.RenderableVertex();
  4017. _vertexPool.push( vertex );
  4018. _vertexPoolLength ++;
  4019. _vertexCount ++;
  4020. return vertex;
  4021. }
  4022. return _vertexPool[ _vertexCount ++ ];
  4023. }
  4024. function getNextFace3InPool() {
  4025. if ( _face3Count === _face3PoolLength ) {
  4026. var face = new THREE.RenderableFace3();
  4027. _face3Pool.push( face );
  4028. _face3PoolLength ++;
  4029. _face3Count ++;
  4030. return face;
  4031. }
  4032. return _face3Pool[ _face3Count ++ ];
  4033. }
  4034. function getNextFace4InPool() {
  4035. if ( _face4Count === _face4PoolLength ) {
  4036. var face = new THREE.RenderableFace4();
  4037. _face4Pool.push( face );
  4038. _face4PoolLength ++;
  4039. _face4Count ++;
  4040. return face;
  4041. }
  4042. return _face4Pool[ _face4Count ++ ];
  4043. }
  4044. function getNextLineInPool() {
  4045. if ( _lineCount === _linePoolLength ) {
  4046. var line = new THREE.RenderableLine();
  4047. _linePool.push( line );
  4048. _linePoolLength ++;
  4049. _lineCount ++
  4050. return line;
  4051. }
  4052. return _linePool[ _lineCount ++ ];
  4053. }
  4054. function getNextParticleInPool() {
  4055. if ( _particleCount === _particlePoolLength ) {
  4056. var particle = new THREE.RenderableParticle();
  4057. _particlePool.push( particle );
  4058. _particlePoolLength ++;
  4059. _particleCount ++
  4060. return particle;
  4061. }
  4062. return _particlePool[ _particleCount ++ ];
  4063. }
  4064. //
  4065. function painterSort( a, b ) {
  4066. return b.z - a.z;
  4067. }
  4068. function clipLine( s1, s2 ) {
  4069. var alpha1 = 0, alpha2 = 1,
  4070. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  4071. // Z = -1 and Z = +1, respectively.
  4072. bc1near = s1.z + s1.w,
  4073. bc2near = s2.z + s2.w,
  4074. bc1far = - s1.z + s1.w,
  4075. bc2far = - s2.z + s2.w;
  4076. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  4077. // Both vertices lie entirely within all clip planes.
  4078. return true;
  4079. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  4080. // Both vertices lie entirely outside one of the clip planes.
  4081. return false;
  4082. } else {
  4083. // The line segment spans at least one clip plane.
  4084. if ( bc1near < 0 ) {
  4085. // v1 lies outside the near plane, v2 inside
  4086. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  4087. } else if ( bc2near < 0 ) {
  4088. // v2 lies outside the near plane, v1 inside
  4089. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  4090. }
  4091. if ( bc1far < 0 ) {
  4092. // v1 lies outside the far plane, v2 inside
  4093. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  4094. } else if ( bc2far < 0 ) {
  4095. // v2 lies outside the far plane, v2 inside
  4096. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  4097. }
  4098. if ( alpha2 < alpha1 ) {
  4099. // The line segment spans two boundaries, but is outside both of them.
  4100. // (This can't happen when we're only clipping against just near/far but good
  4101. // to leave the check here for future usage if other clip planes are added.)
  4102. return false;
  4103. } else {
  4104. // Update the s1 and s2 vertices to match the clipped line segment.
  4105. s1.lerp( s2, alpha1 );
  4106. s2.lerp( s1, 1 - alpha2 );
  4107. return true;
  4108. }
  4109. }
  4110. }
  4111. };
  4112. /**
  4113. * @author mrdoob / http://mrdoob.com/
  4114. * @author alteredq / http://alteredqualia.com/
  4115. */
  4116. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  4117. this.a = a;
  4118. this.b = b;
  4119. this.c = c;
  4120. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4121. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4122. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4123. this.vertexColors = color instanceof Array ? color : [];
  4124. this.vertexTangents = [];
  4125. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4126. this.centroid = new THREE.Vector3();
  4127. };
  4128. THREE.Face3.prototype = {
  4129. constructor: THREE.Face3,
  4130. clone: function () {
  4131. var face = new THREE.Face3( this.a, this.b, this.c );
  4132. face.normal.copy( this.normal );
  4133. face.color.copy( this.color );
  4134. face.centroid.copy( this.centroid );
  4135. face.materialIndex = this.materialIndex;
  4136. var i, il;
  4137. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4138. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4139. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4140. return face;
  4141. }
  4142. };
  4143. /**
  4144. * @author mrdoob / http://mrdoob.com/
  4145. * @author alteredq / http://alteredqualia.com/
  4146. */
  4147. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  4148. this.a = a;
  4149. this.b = b;
  4150. this.c = c;
  4151. this.d = d;
  4152. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4153. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4154. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4155. this.vertexColors = color instanceof Array ? color : [];
  4156. this.vertexTangents = [];
  4157. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4158. this.centroid = new THREE.Vector3();
  4159. };
  4160. THREE.Face4.prototype = {
  4161. constructor: THREE.Face4,
  4162. clone: function () {
  4163. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  4164. face.normal.copy( this.normal );
  4165. face.color.copy( this.color );
  4166. face.centroid.copy( this.centroid );
  4167. face.materialIndex = this.materialIndex;
  4168. var i, il;
  4169. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4170. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4171. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4172. return face;
  4173. }
  4174. };
  4175. /**
  4176. * @author mrdoob / http://mrdoob.com/
  4177. * @author kile / http://kile.stravaganza.org/
  4178. * @author alteredq / http://alteredqualia.com/
  4179. * @author mikael emtinger / http://gomo.se/
  4180. * @author zz85 / http://www.lab4games.net/zz85/blog
  4181. * @author bhouston / http://exocortex.com
  4182. */
  4183. THREE.Geometry = function () {
  4184. THREE.EventDispatcher.call( this );
  4185. this.id = THREE.GeometryIdCount ++;
  4186. this.name = '';
  4187. this.vertices = [];
  4188. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  4189. this.normals = []; // one-to-one vertex normals, used in Ribbon
  4190. this.faces = [];
  4191. this.faceUvs = [[]];
  4192. this.faceVertexUvs = [[]];
  4193. this.morphTargets = [];
  4194. this.morphColors = [];
  4195. this.morphNormals = [];
  4196. this.skinWeights = [];
  4197. this.skinIndices = [];
  4198. this.lineDistances = [];
  4199. this.boundingBox = null;
  4200. this.boundingSphere = null;
  4201. this.hasTangents = false;
  4202. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  4203. // update flags
  4204. this.verticesNeedUpdate = false;
  4205. this.elementsNeedUpdate = false;
  4206. this.uvsNeedUpdate = false;
  4207. this.normalsNeedUpdate = false;
  4208. this.tangentsNeedUpdate = false;
  4209. this.colorsNeedUpdate = false;
  4210. this.lineDistancesNeedUpdate = false;
  4211. this.buffersNeedUpdate = false;
  4212. };
  4213. THREE.Geometry.prototype = {
  4214. constructor: THREE.Geometry,
  4215. applyMatrix: function ( matrix ) {
  4216. var normalMatrix = new THREE.Matrix3().getInverse( matrix ).transpose();
  4217. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  4218. var vertex = this.vertices[ i ];
  4219. vertex.applyMatrix4( matrix );
  4220. }
  4221. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  4222. var face = this.faces[ i ];
  4223. face.normal.applyMatrix3( normalMatrix ).normalize();
  4224. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  4225. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  4226. }
  4227. face.centroid.applyMatrix4( matrix );
  4228. }
  4229. },
  4230. computeCentroids: function () {
  4231. var f, fl, face;
  4232. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4233. face = this.faces[ f ];
  4234. face.centroid.set( 0, 0, 0 );
  4235. if ( face instanceof THREE.Face3 ) {
  4236. face.centroid.add( this.vertices[ face.a ] );
  4237. face.centroid.add( this.vertices[ face.b ] );
  4238. face.centroid.add( this.vertices[ face.c ] );
  4239. face.centroid.divideScalar( 3 );
  4240. } else if ( face instanceof THREE.Face4 ) {
  4241. face.centroid.add( this.vertices[ face.a ] );
  4242. face.centroid.add( this.vertices[ face.b ] );
  4243. face.centroid.add( this.vertices[ face.c ] );
  4244. face.centroid.add( this.vertices[ face.d ] );
  4245. face.centroid.divideScalar( 4 );
  4246. }
  4247. }
  4248. },
  4249. computeFaceNormals: function () {
  4250. var n, nl, v, vl, vertex, f, fl, face, vA, vB, vC,
  4251. cb = new THREE.Vector3(), ab = new THREE.Vector3();
  4252. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4253. face = this.faces[ f ];
  4254. vA = this.vertices[ face.a ];
  4255. vB = this.vertices[ face.b ];
  4256. vC = this.vertices[ face.c ];
  4257. cb.subVectors( vC, vB );
  4258. ab.subVectors( vA, vB );
  4259. cb.cross( ab );
  4260. cb.normalize();
  4261. face.normal.copy( cb );
  4262. }
  4263. },
  4264. computeVertexNormals: function ( areaWeighted ) {
  4265. var v, vl, f, fl, face, vertices;
  4266. // create internal buffers for reuse when calling this method repeatedly
  4267. // (otherwise memory allocation / deallocation every frame is big resource hog)
  4268. if ( this.__tmpVertices === undefined ) {
  4269. this.__tmpVertices = new Array( this.vertices.length );
  4270. vertices = this.__tmpVertices;
  4271. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4272. vertices[ v ] = new THREE.Vector3();
  4273. }
  4274. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4275. face = this.faces[ f ];
  4276. if ( face instanceof THREE.Face3 ) {
  4277. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4278. } else if ( face instanceof THREE.Face4 ) {
  4279. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4280. }
  4281. }
  4282. } else {
  4283. vertices = this.__tmpVertices;
  4284. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4285. vertices[ v ].set( 0, 0, 0 );
  4286. }
  4287. }
  4288. if ( areaWeighted ) {
  4289. // vertex normals weighted by triangle areas
  4290. // http://www.iquilezles.org/www/articles/normals/normals.htm
  4291. var vA, vB, vC, vD;
  4292. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  4293. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  4294. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4295. face = this.faces[ f ];
  4296. if ( face instanceof THREE.Face3 ) {
  4297. vA = this.vertices[ face.a ];
  4298. vB = this.vertices[ face.b ];
  4299. vC = this.vertices[ face.c ];
  4300. cb.subVectors( vC, vB );
  4301. ab.subVectors( vA, vB );
  4302. cb.cross( ab );
  4303. vertices[ face.a ].add( cb );
  4304. vertices[ face.b ].add( cb );
  4305. vertices[ face.c ].add( cb );
  4306. } else if ( face instanceof THREE.Face4 ) {
  4307. vA = this.vertices[ face.a ];
  4308. vB = this.vertices[ face.b ];
  4309. vC = this.vertices[ face.c ];
  4310. vD = this.vertices[ face.d ];
  4311. // abd
  4312. db.subVectors( vD, vB );
  4313. ab.subVectors( vA, vB );
  4314. db.cross( ab );
  4315. vertices[ face.a ].add( db );
  4316. vertices[ face.b ].add( db );
  4317. vertices[ face.d ].add( db );
  4318. // bcd
  4319. dc.subVectors( vD, vC );
  4320. bc.subVectors( vB, vC );
  4321. dc.cross( bc );
  4322. vertices[ face.b ].add( dc );
  4323. vertices[ face.c ].add( dc );
  4324. vertices[ face.d ].add( dc );
  4325. }
  4326. }
  4327. } else {
  4328. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4329. face = this.faces[ f ];
  4330. if ( face instanceof THREE.Face3 ) {
  4331. vertices[ face.a ].add( face.normal );
  4332. vertices[ face.b ].add( face.normal );
  4333. vertices[ face.c ].add( face.normal );
  4334. } else if ( face instanceof THREE.Face4 ) {
  4335. vertices[ face.a ].add( face.normal );
  4336. vertices[ face.b ].add( face.normal );
  4337. vertices[ face.c ].add( face.normal );
  4338. vertices[ face.d ].add( face.normal );
  4339. }
  4340. }
  4341. }
  4342. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4343. vertices[ v ].normalize();
  4344. }
  4345. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4346. face = this.faces[ f ];
  4347. if ( face instanceof THREE.Face3 ) {
  4348. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4349. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4350. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4351. } else if ( face instanceof THREE.Face4 ) {
  4352. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4353. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4354. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4355. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  4356. }
  4357. }
  4358. },
  4359. computeMorphNormals: function () {
  4360. var i, il, f, fl, face;
  4361. // save original normals
  4362. // - create temp variables on first access
  4363. // otherwise just copy (for faster repeated calls)
  4364. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4365. face = this.faces[ f ];
  4366. if ( ! face.__originalFaceNormal ) {
  4367. face.__originalFaceNormal = face.normal.clone();
  4368. } else {
  4369. face.__originalFaceNormal.copy( face.normal );
  4370. }
  4371. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  4372. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  4373. if ( ! face.__originalVertexNormals[ i ] ) {
  4374. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  4375. } else {
  4376. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  4377. }
  4378. }
  4379. }
  4380. // use temp geometry to compute face and vertex normals for each morph
  4381. var tmpGeo = new THREE.Geometry();
  4382. tmpGeo.faces = this.faces;
  4383. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  4384. // create on first access
  4385. if ( ! this.morphNormals[ i ] ) {
  4386. this.morphNormals[ i ] = {};
  4387. this.morphNormals[ i ].faceNormals = [];
  4388. this.morphNormals[ i ].vertexNormals = [];
  4389. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  4390. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  4391. var faceNormal, vertexNormals;
  4392. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4393. face = this.faces[ f ];
  4394. faceNormal = new THREE.Vector3();
  4395. if ( face instanceof THREE.Face3 ) {
  4396. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  4397. } else {
  4398. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  4399. }
  4400. dstNormalsFace.push( faceNormal );
  4401. dstNormalsVertex.push( vertexNormals );
  4402. }
  4403. }
  4404. var morphNormals = this.morphNormals[ i ];
  4405. // set vertices to morph target
  4406. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  4407. // compute morph normals
  4408. tmpGeo.computeFaceNormals();
  4409. tmpGeo.computeVertexNormals();
  4410. // store morph normals
  4411. var faceNormal, vertexNormals;
  4412. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4413. face = this.faces[ f ];
  4414. faceNormal = morphNormals.faceNormals[ f ];
  4415. vertexNormals = morphNormals.vertexNormals[ f ];
  4416. faceNormal.copy( face.normal );
  4417. if ( face instanceof THREE.Face3 ) {
  4418. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4419. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4420. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4421. } else {
  4422. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4423. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4424. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4425. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  4426. }
  4427. }
  4428. }
  4429. // restore original normals
  4430. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4431. face = this.faces[ f ];
  4432. face.normal = face.__originalFaceNormal;
  4433. face.vertexNormals = face.__originalVertexNormals;
  4434. }
  4435. },
  4436. computeTangents: function () {
  4437. // based on http://www.terathon.com/code/tangent.html
  4438. // tangents go to vertices
  4439. var f, fl, v, vl, i, il, vertexIndex,
  4440. face, uv, vA, vB, vC, uvA, uvB, uvC,
  4441. x1, x2, y1, y2, z1, z2,
  4442. s1, s2, t1, t2, r, t, test,
  4443. tan1 = [], tan2 = [],
  4444. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  4445. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  4446. n = new THREE.Vector3(), w;
  4447. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4448. tan1[ v ] = new THREE.Vector3();
  4449. tan2[ v ] = new THREE.Vector3();
  4450. }
  4451. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  4452. vA = context.vertices[ a ];
  4453. vB = context.vertices[ b ];
  4454. vC = context.vertices[ c ];
  4455. uvA = uv[ ua ];
  4456. uvB = uv[ ub ];
  4457. uvC = uv[ uc ];
  4458. x1 = vB.x - vA.x;
  4459. x2 = vC.x - vA.x;
  4460. y1 = vB.y - vA.y;
  4461. y2 = vC.y - vA.y;
  4462. z1 = vB.z - vA.z;
  4463. z2 = vC.z - vA.z;
  4464. s1 = uvB.x - uvA.x;
  4465. s2 = uvC.x - uvA.x;
  4466. t1 = uvB.y - uvA.y;
  4467. t2 = uvC.y - uvA.y;
  4468. r = 1.0 / ( s1 * t2 - s2 * t1 );
  4469. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  4470. ( t2 * y1 - t1 * y2 ) * r,
  4471. ( t2 * z1 - t1 * z2 ) * r );
  4472. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  4473. ( s1 * y2 - s2 * y1 ) * r,
  4474. ( s1 * z2 - s2 * z1 ) * r );
  4475. tan1[ a ].add( sdir );
  4476. tan1[ b ].add( sdir );
  4477. tan1[ c ].add( sdir );
  4478. tan2[ a ].add( tdir );
  4479. tan2[ b ].add( tdir );
  4480. tan2[ c ].add( tdir );
  4481. }
  4482. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4483. face = this.faces[ f ];
  4484. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  4485. if ( face instanceof THREE.Face3 ) {
  4486. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  4487. } else if ( face instanceof THREE.Face4 ) {
  4488. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  4489. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  4490. }
  4491. }
  4492. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  4493. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4494. face = this.faces[ f ];
  4495. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  4496. n.copy( face.vertexNormals[ i ] );
  4497. vertexIndex = face[ faceIndex[ i ] ];
  4498. t = tan1[ vertexIndex ];
  4499. // Gram-Schmidt orthogonalize
  4500. tmp.copy( t );
  4501. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  4502. // Calculate handedness
  4503. tmp2.crossVectors( face.vertexNormals[ i ], t );
  4504. test = tmp2.dot( tan2[ vertexIndex ] );
  4505. w = (test < 0.0) ? -1.0 : 1.0;
  4506. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  4507. }
  4508. }
  4509. this.hasTangents = true;
  4510. },
  4511. computeLineDistances: function ( ) {
  4512. var d = 0;
  4513. var vertices = this.vertices;
  4514. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4515. if ( i > 0 ) {
  4516. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  4517. }
  4518. this.lineDistances[ i ] = d;
  4519. }
  4520. },
  4521. computeBoundingBox: function () {
  4522. if ( this.boundingBox === null ) {
  4523. this.boundingBox = new THREE.Box3();
  4524. }
  4525. this.boundingBox.setFromPoints( this.vertices );
  4526. },
  4527. computeBoundingSphere: function () {
  4528. if ( this.boundingSphere === null ) {
  4529. this.boundingSphere = new THREE.Sphere();
  4530. }
  4531. this.boundingSphere.setFromCenterAndPoints( this.boundingSphere.center, this.vertices );
  4532. },
  4533. /*
  4534. * Checks for duplicate vertices with hashmap.
  4535. * Duplicated vertices are removed
  4536. * and faces' vertices are updated.
  4537. */
  4538. mergeVertices: function () {
  4539. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  4540. var unique = [], changes = [];
  4541. var v, key;
  4542. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  4543. var precision = Math.pow( 10, precisionPoints );
  4544. var i,il, face;
  4545. var indices, k, j, jl, u;
  4546. // reset cache of vertices as it now will be changing.
  4547. this.__tmpVertices = undefined;
  4548. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  4549. v = this.vertices[ i ];
  4550. key = [ Math.round( v.x * precision ), Math.round( v.y * precision ), Math.round( v.z * precision ) ].join( '_' );
  4551. if ( verticesMap[ key ] === undefined ) {
  4552. verticesMap[ key ] = i;
  4553. unique.push( this.vertices[ i ] );
  4554. changes[ i ] = unique.length - 1;
  4555. } else {
  4556. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  4557. changes[ i ] = changes[ verticesMap[ key ] ];
  4558. }
  4559. };
  4560. // if faces are completely degenerate after merging vertices, we
  4561. // have to remove them from the geometry.
  4562. var faceIndicesToRemove = [];
  4563. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  4564. face = this.faces[ i ];
  4565. if ( face instanceof THREE.Face3 ) {
  4566. face.a = changes[ face.a ];
  4567. face.b = changes[ face.b ];
  4568. face.c = changes[ face.c ];
  4569. indices = [ face.a, face.b, face.c ];
  4570. var dupIndex = -1;
  4571. // if any duplicate vertices are found in a Face3
  4572. // we have to remove the face as nothing can be saved
  4573. for ( var n = 0; n < 3; n ++ ) {
  4574. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  4575. dupIndex = n;
  4576. faceIndicesToRemove.push( i );
  4577. break;
  4578. }
  4579. }
  4580. } else if ( face instanceof THREE.Face4 ) {
  4581. face.a = changes[ face.a ];
  4582. face.b = changes[ face.b ];
  4583. face.c = changes[ face.c ];
  4584. face.d = changes[ face.d ];
  4585. // check dups in (a, b, c, d) and convert to -> face3
  4586. indices = [ face.a, face.b, face.c, face.d ];
  4587. var dupIndex = -1;
  4588. for ( var n = 0; n < 4; n ++ ) {
  4589. if ( indices[ n ] == indices[ ( n + 1 ) % 4 ] ) {
  4590. // if more than one duplicated vertex is found
  4591. // we can't generate any valid Face3's, thus
  4592. // we need to remove this face complete.
  4593. if ( dupIndex >= 0 ) {
  4594. faceIndicesToRemove.push( i );
  4595. }
  4596. dupIndex = n;
  4597. }
  4598. }
  4599. if ( dupIndex >= 0 ) {
  4600. indices.splice( dupIndex, 1 );
  4601. var newFace = new THREE.Face3( indices[0], indices[1], indices[2], face.normal, face.color, face.materialIndex );
  4602. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  4603. u = this.faceVertexUvs[ j ][ i ];
  4604. if ( u ) {
  4605. u.splice( dupIndex, 1 );
  4606. }
  4607. }
  4608. if( face.vertexNormals && face.vertexNormals.length > 0) {
  4609. newFace.vertexNormals = face.vertexNormals;
  4610. newFace.vertexNormals.splice( dupIndex, 1 );
  4611. }
  4612. if( face.vertexColors && face.vertexColors.length > 0 ) {
  4613. newFace.vertexColors = face.vertexColors;
  4614. newFace.vertexColors.splice( dupIndex, 1 );
  4615. }
  4616. this.faces[ i ] = newFace;
  4617. }
  4618. }
  4619. }
  4620. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  4621. this.faces.splice( i, 1 );
  4622. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  4623. this.faceVertexUvs[ j ].splice( i, 1 );
  4624. }
  4625. }
  4626. // Use unique set of vertices
  4627. var diff = this.vertices.length - unique.length;
  4628. this.vertices = unique;
  4629. return diff;
  4630. },
  4631. clone: function () {
  4632. var geometry = new THREE.Geometry();
  4633. var vertices = this.vertices;
  4634. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4635. geometry.vertices.push( vertices[ i ].clone() );
  4636. }
  4637. var faces = this.faces;
  4638. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  4639. geometry.faces.push( faces[ i ].clone() );
  4640. }
  4641. var uvs = this.faceVertexUvs[ 0 ];
  4642. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  4643. var uv = uvs[ i ], uvCopy = [];
  4644. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  4645. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  4646. }
  4647. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  4648. }
  4649. return geometry;
  4650. },
  4651. dispose: function () {
  4652. this.dispatchEvent( { type: 'dispose' } );
  4653. }
  4654. };
  4655. THREE.GeometryIdCount = 0;
  4656. /**
  4657. * @author alteredq / http://alteredqualia.com/
  4658. */
  4659. THREE.BufferGeometry = function () {
  4660. THREE.EventDispatcher.call( this );
  4661. this.id = THREE.GeometryIdCount ++;
  4662. // attributes
  4663. this.attributes = {};
  4664. // attributes typed arrays are kept only if dynamic flag is set
  4665. this.dynamic = false;
  4666. // offsets for chunks when using indexed elements
  4667. this.offsets = [];
  4668. // boundings
  4669. this.boundingBox = null;
  4670. this.boundingSphere = null;
  4671. this.hasTangents = false;
  4672. // for compatibility
  4673. this.morphTargets = [];
  4674. };
  4675. THREE.BufferGeometry.prototype = {
  4676. constructor : THREE.BufferGeometry,
  4677. applyMatrix: function ( matrix ) {
  4678. var positionArray;
  4679. var normalArray;
  4680. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  4681. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  4682. if ( positionArray !== undefined ) {
  4683. matrix.multiplyVector3Array( positionArray );
  4684. this.verticesNeedUpdate = true;
  4685. }
  4686. if ( normalArray !== undefined ) {
  4687. var normalMatrix = new THREE.Matrix3();
  4688. normalMatrix.getInverse( matrix ).transpose();
  4689. normalMatrix.multiplyVector3Array( normalArray );
  4690. this.normalizeNormals();
  4691. this.normalsNeedUpdate = true;
  4692. }
  4693. },
  4694. computeBoundingBox: function () {
  4695. if ( this.boundingBox === null ) {
  4696. this.boundingBox = new THREE.Box3();
  4697. }
  4698. var positions = this.attributes[ "position" ].array;
  4699. if ( positions ) {
  4700. var bb = this.boundingBox;
  4701. var x, y, z;
  4702. if( positions.length >= 3 ) {
  4703. bb.min.x = bb.max.x = positions[ 0 ];
  4704. bb.min.y = bb.max.y = positions[ 1 ];
  4705. bb.min.z = bb.max.z = positions[ 2 ];
  4706. }
  4707. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  4708. x = positions[ i ];
  4709. y = positions[ i + 1 ];
  4710. z = positions[ i + 2 ];
  4711. // bounding box
  4712. if ( x < bb.min.x ) {
  4713. bb.min.x = x;
  4714. } else if ( x > bb.max.x ) {
  4715. bb.max.x = x;
  4716. }
  4717. if ( y < bb.min.y ) {
  4718. bb.min.y = y;
  4719. } else if ( y > bb.max.y ) {
  4720. bb.max.y = y;
  4721. }
  4722. if ( z < bb.min.z ) {
  4723. bb.min.z = z;
  4724. } else if ( z > bb.max.z ) {
  4725. bb.max.z = z;
  4726. }
  4727. }
  4728. }
  4729. if ( positions === undefined || positions.length === 0 ) {
  4730. this.boundingBox.min.set( 0, 0, 0 );
  4731. this.boundingBox.max.set( 0, 0, 0 );
  4732. }
  4733. },
  4734. computeBoundingSphere: function () {
  4735. if ( this.boundingSphere === null ) {
  4736. this.boundingSphere = new THREE.Sphere();
  4737. }
  4738. var positions = this.attributes[ "position" ].array;
  4739. if ( positions ) {
  4740. var radiusSq, maxRadiusSq = 0;
  4741. var x, y, z;
  4742. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  4743. x = positions[ i ];
  4744. y = positions[ i + 1 ];
  4745. z = positions[ i + 2 ];
  4746. radiusSq = x * x + y * y + z * z;
  4747. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  4748. }
  4749. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  4750. }
  4751. },
  4752. computeVertexNormals: function () {
  4753. if ( this.attributes[ "position" ] ) {
  4754. var i, il;
  4755. var j, jl;
  4756. var nVertexElements = this.attributes[ "position" ].array.length;
  4757. if ( this.attributes[ "normal" ] === undefined ) {
  4758. this.attributes[ "normal" ] = {
  4759. itemSize: 3,
  4760. array: new Float32Array( nVertexElements ),
  4761. numItems: nVertexElements
  4762. };
  4763. } else {
  4764. // reset existing normals to zero
  4765. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  4766. this.attributes[ "normal" ].array[ i ] = 0;
  4767. }
  4768. }
  4769. var positions = this.attributes[ "position" ].array;
  4770. var normals = this.attributes[ "normal" ].array;
  4771. var vA, vB, vC, x, y, z,
  4772. pA = new THREE.Vector3(),
  4773. pB = new THREE.Vector3(),
  4774. pC = new THREE.Vector3(),
  4775. cb = new THREE.Vector3(),
  4776. ab = new THREE.Vector3();
  4777. // indexed elements
  4778. if ( this.attributes[ "index" ] ) {
  4779. var indices = this.attributes[ "index" ].array;
  4780. var offsets = this.offsets;
  4781. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  4782. var start = offsets[ j ].start;
  4783. var count = offsets[ j ].count;
  4784. var index = offsets[ j ].index;
  4785. for ( i = start, il = start + count; i < il; i += 3 ) {
  4786. vA = index + indices[ i ];
  4787. vB = index + indices[ i + 1 ];
  4788. vC = index + indices[ i + 2 ];
  4789. x = positions[ vA * 3 ];
  4790. y = positions[ vA * 3 + 1 ];
  4791. z = positions[ vA * 3 + 2 ];
  4792. pA.set( x, y, z );
  4793. x = positions[ vB * 3 ];
  4794. y = positions[ vB * 3 + 1 ];
  4795. z = positions[ vB * 3 + 2 ];
  4796. pB.set( x, y, z );
  4797. x = positions[ vC * 3 ];
  4798. y = positions[ vC * 3 + 1 ];
  4799. z = positions[ vC * 3 + 2 ];
  4800. pC.set( x, y, z );
  4801. cb.subVectors( pC, pB );
  4802. ab.subVectors( pA, pB );
  4803. cb.cross( ab );
  4804. normals[ vA * 3 ] += cb.x;
  4805. normals[ vA * 3 + 1 ] += cb.y;
  4806. normals[ vA * 3 + 2 ] += cb.z;
  4807. normals[ vB * 3 ] += cb.x;
  4808. normals[ vB * 3 + 1 ] += cb.y;
  4809. normals[ vB * 3 + 2 ] += cb.z;
  4810. normals[ vC * 3 ] += cb.x;
  4811. normals[ vC * 3 + 1 ] += cb.y;
  4812. normals[ vC * 3 + 2 ] += cb.z;
  4813. }
  4814. }
  4815. // non-indexed elements (unconnected triangle soup)
  4816. } else {
  4817. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  4818. x = positions[ i ];
  4819. y = positions[ i + 1 ];
  4820. z = positions[ i + 2 ];
  4821. pA.set( x, y, z );
  4822. x = positions[ i + 3 ];
  4823. y = positions[ i + 4 ];
  4824. z = positions[ i + 5 ];
  4825. pB.set( x, y, z );
  4826. x = positions[ i + 6 ];
  4827. y = positions[ i + 7 ];
  4828. z = positions[ i + 8 ];
  4829. pC.set( x, y, z );
  4830. cb.subVectors( pC, pB );
  4831. ab.subVectors( pA, pB );
  4832. cb.cross( ab );
  4833. normals[ i ] = cb.x;
  4834. normals[ i + 1 ] = cb.y;
  4835. normals[ i + 2 ] = cb.z;
  4836. normals[ i + 3 ] = cb.x;
  4837. normals[ i + 4 ] = cb.y;
  4838. normals[ i + 5 ] = cb.z;
  4839. normals[ i + 6 ] = cb.x;
  4840. normals[ i + 7 ] = cb.y;
  4841. normals[ i + 8 ] = cb.z;
  4842. }
  4843. }
  4844. this.normalizeNormals();
  4845. this.normalsNeedUpdate = true;
  4846. }
  4847. },
  4848. normalizeNormals: function () {
  4849. var normals = this.attributes[ "normal" ].array;
  4850. var x, y, z, n;
  4851. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  4852. x = normals[ i ];
  4853. y = normals[ i + 1 ];
  4854. z = normals[ i + 2 ];
  4855. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  4856. normals[ i ] *= n;
  4857. normals[ i + 1 ] *= n;
  4858. normals[ i + 2 ] *= n;
  4859. }
  4860. },
  4861. computeTangents: function () {
  4862. // based on http://www.terathon.com/code/tangent.html
  4863. // (per vertex tangents)
  4864. if ( this.attributes[ "index" ] === undefined ||
  4865. this.attributes[ "position" ] === undefined ||
  4866. this.attributes[ "normal" ] === undefined ||
  4867. this.attributes[ "uv" ] === undefined ) {
  4868. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  4869. return;
  4870. }
  4871. var indices = this.attributes[ "index" ].array;
  4872. var positions = this.attributes[ "position" ].array;
  4873. var normals = this.attributes[ "normal" ].array;
  4874. var uvs = this.attributes[ "uv" ].array;
  4875. var nVertices = positions.length / 3;
  4876. if ( this.attributes[ "tangent" ] === undefined ) {
  4877. var nTangentElements = 4 * nVertices;
  4878. this.attributes[ "tangent" ] = {
  4879. itemSize: 4,
  4880. array: new Float32Array( nTangentElements ),
  4881. numItems: nTangentElements
  4882. };
  4883. }
  4884. var tangents = this.attributes[ "tangent" ].array;
  4885. var tan1 = [], tan2 = [];
  4886. for ( var k = 0; k < nVertices; k ++ ) {
  4887. tan1[ k ] = new THREE.Vector3();
  4888. tan2[ k ] = new THREE.Vector3();
  4889. }
  4890. var xA, yA, zA,
  4891. xB, yB, zB,
  4892. xC, yC, zC,
  4893. uA, vA,
  4894. uB, vB,
  4895. uC, vC,
  4896. x1, x2, y1, y2, z1, z2,
  4897. s1, s2, t1, t2, r;
  4898. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  4899. function handleTriangle( a, b, c ) {
  4900. xA = positions[ a * 3 ];
  4901. yA = positions[ a * 3 + 1 ];
  4902. zA = positions[ a * 3 + 2 ];
  4903. xB = positions[ b * 3 ];
  4904. yB = positions[ b * 3 + 1 ];
  4905. zB = positions[ b * 3 + 2 ];
  4906. xC = positions[ c * 3 ];
  4907. yC = positions[ c * 3 + 1 ];
  4908. zC = positions[ c * 3 + 2 ];
  4909. uA = uvs[ a * 2 ];
  4910. vA = uvs[ a * 2 + 1 ];
  4911. uB = uvs[ b * 2 ];
  4912. vB = uvs[ b * 2 + 1 ];
  4913. uC = uvs[ c * 2 ];
  4914. vC = uvs[ c * 2 + 1 ];
  4915. x1 = xB - xA;
  4916. x2 = xC - xA;
  4917. y1 = yB - yA;
  4918. y2 = yC - yA;
  4919. z1 = zB - zA;
  4920. z2 = zC - zA;
  4921. s1 = uB - uA;
  4922. s2 = uC - uA;
  4923. t1 = vB - vA;
  4924. t2 = vC - vA;
  4925. r = 1.0 / ( s1 * t2 - s2 * t1 );
  4926. sdir.set(
  4927. ( t2 * x1 - t1 * x2 ) * r,
  4928. ( t2 * y1 - t1 * y2 ) * r,
  4929. ( t2 * z1 - t1 * z2 ) * r
  4930. );
  4931. tdir.set(
  4932. ( s1 * x2 - s2 * x1 ) * r,
  4933. ( s1 * y2 - s2 * y1 ) * r,
  4934. ( s1 * z2 - s2 * z1 ) * r
  4935. );
  4936. tan1[ a ].add( sdir );
  4937. tan1[ b ].add( sdir );
  4938. tan1[ c ].add( sdir );
  4939. tan2[ a ].add( tdir );
  4940. tan2[ b ].add( tdir );
  4941. tan2[ c ].add( tdir );
  4942. }
  4943. var i, il;
  4944. var j, jl;
  4945. var iA, iB, iC;
  4946. var offsets = this.offsets;
  4947. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  4948. var start = offsets[ j ].start;
  4949. var count = offsets[ j ].count;
  4950. var index = offsets[ j ].index;
  4951. for ( i = start, il = start + count; i < il; i += 3 ) {
  4952. iA = index + indices[ i ];
  4953. iB = index + indices[ i + 1 ];
  4954. iC = index + indices[ i + 2 ];
  4955. handleTriangle( iA, iB, iC );
  4956. }
  4957. }
  4958. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  4959. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  4960. var w, t, test;
  4961. var nx, ny, nz;
  4962. function handleVertex( v ) {
  4963. n.x = normals[ v * 3 ];
  4964. n.y = normals[ v * 3 + 1 ];
  4965. n.z = normals[ v * 3 + 2 ];
  4966. n2.copy( n );
  4967. t = tan1[ v ];
  4968. // Gram-Schmidt orthogonalize
  4969. tmp.copy( t );
  4970. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  4971. // Calculate handedness
  4972. tmp2.crossVectors( n2, t );
  4973. test = tmp2.dot( tan2[ v ] );
  4974. w = ( test < 0.0 ) ? -1.0 : 1.0;
  4975. tangents[ v * 4 ] = tmp.x;
  4976. tangents[ v * 4 + 1 ] = tmp.y;
  4977. tangents[ v * 4 + 2 ] = tmp.z;
  4978. tangents[ v * 4 + 3 ] = w;
  4979. }
  4980. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  4981. var start = offsets[ j ].start;
  4982. var count = offsets[ j ].count;
  4983. var index = offsets[ j ].index;
  4984. for ( i = start, il = start + count; i < il; i += 3 ) {
  4985. iA = index + indices[ i ];
  4986. iB = index + indices[ i + 1 ];
  4987. iC = index + indices[ i + 2 ];
  4988. handleVertex( iA );
  4989. handleVertex( iB );
  4990. handleVertex( iC );
  4991. }
  4992. }
  4993. this.hasTangents = true;
  4994. this.tangentsNeedUpdate = true;
  4995. },
  4996. dispose: function () {
  4997. this.dispatchEvent( { type: 'dispose' } );
  4998. }
  4999. };
  5000. /**
  5001. * @author mrdoob / http://mrdoob.com/
  5002. * @author mikael emtinger / http://gomo.se/
  5003. */
  5004. THREE.Camera = function () {
  5005. THREE.Object3D.call( this );
  5006. this.matrixWorldInverse = new THREE.Matrix4();
  5007. this.projectionMatrix = new THREE.Matrix4();
  5008. this.projectionMatrixInverse = new THREE.Matrix4();
  5009. };
  5010. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  5011. THREE.Camera.prototype.lookAt = function ( vector ) {
  5012. // TODO: Add hierarchy support.
  5013. this.matrix.lookAt( this.position, vector, this.up );
  5014. if ( this.rotationAutoUpdate === true ) {
  5015. if ( this.useQuaternion === false ) {
  5016. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  5017. } else {
  5018. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  5019. }
  5020. }
  5021. };
  5022. /**
  5023. * @author alteredq / http://alteredqualia.com/
  5024. */
  5025. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  5026. THREE.Camera.call( this );
  5027. this.left = left;
  5028. this.right = right;
  5029. this.top = top;
  5030. this.bottom = bottom;
  5031. this.near = ( near !== undefined ) ? near : 0.1;
  5032. this.far = ( far !== undefined ) ? far : 2000;
  5033. this.updateProjectionMatrix();
  5034. };
  5035. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  5036. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  5037. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  5038. };
  5039. /**
  5040. * @author mrdoob / http://mrdoob.com/
  5041. * @author greggman / http://games.greggman.com/
  5042. * @author zz85 / http://www.lab4games.net/zz85/blog
  5043. */
  5044. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  5045. THREE.Camera.call( this );
  5046. this.fov = fov !== undefined ? fov : 50;
  5047. this.aspect = aspect !== undefined ? aspect : 1;
  5048. this.near = near !== undefined ? near : 0.1;
  5049. this.far = far !== undefined ? far : 2000;
  5050. this.updateProjectionMatrix();
  5051. };
  5052. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  5053. /**
  5054. * Uses Focal Length (in mm) to estimate and set FOV
  5055. * 35mm (fullframe) camera is used if frame size is not specified;
  5056. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  5057. */
  5058. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  5059. if ( frameHeight === undefined ) frameHeight = 24;
  5060. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  5061. this.updateProjectionMatrix();
  5062. }
  5063. /**
  5064. * Sets an offset in a larger frustum. This is useful for multi-window or
  5065. * multi-monitor/multi-machine setups.
  5066. *
  5067. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  5068. * the monitors are in grid like this
  5069. *
  5070. * +---+---+---+
  5071. * | A | B | C |
  5072. * +---+---+---+
  5073. * | D | E | F |
  5074. * +---+---+---+
  5075. *
  5076. * then for each monitor you would call it like this
  5077. *
  5078. * var w = 1920;
  5079. * var h = 1080;
  5080. * var fullWidth = w * 3;
  5081. * var fullHeight = h * 2;
  5082. *
  5083. * --A--
  5084. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  5085. * --B--
  5086. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  5087. * --C--
  5088. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  5089. * --D--
  5090. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  5091. * --E--
  5092. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  5093. * --F--
  5094. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  5095. *
  5096. * Note there is no reason monitors have to be the same size or in a grid.
  5097. */
  5098. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  5099. this.fullWidth = fullWidth;
  5100. this.fullHeight = fullHeight;
  5101. this.x = x;
  5102. this.y = y;
  5103. this.width = width;
  5104. this.height = height;
  5105. this.updateProjectionMatrix();
  5106. };
  5107. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  5108. if ( this.fullWidth ) {
  5109. var aspect = this.fullWidth / this.fullHeight;
  5110. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  5111. var bottom = -top;
  5112. var left = aspect * bottom;
  5113. var right = aspect * top;
  5114. var width = Math.abs( right - left );
  5115. var height = Math.abs( top - bottom );
  5116. this.projectionMatrix.makeFrustum(
  5117. left + this.x * width / this.fullWidth,
  5118. left + ( this.x + this.width ) * width / this.fullWidth,
  5119. top - ( this.y + this.height ) * height / this.fullHeight,
  5120. top - this.y * height / this.fullHeight,
  5121. this.near,
  5122. this.far
  5123. );
  5124. } else {
  5125. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  5126. }
  5127. };
  5128. /**
  5129. * @author mrdoob / http://mrdoob.com/
  5130. * @author alteredq / http://alteredqualia.com/
  5131. */
  5132. THREE.Light = function ( hex ) {
  5133. THREE.Object3D.call( this );
  5134. this.color = new THREE.Color( hex );
  5135. };
  5136. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  5137. /**
  5138. * @author mrdoob / http://mrdoob.com/
  5139. */
  5140. THREE.AmbientLight = function ( hex ) {
  5141. THREE.Light.call( this, hex );
  5142. };
  5143. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  5144. /**
  5145. * @author MPanknin / http://www.redplant.de/
  5146. * @author alteredq / http://alteredqualia.com/
  5147. */
  5148. THREE.AreaLight = function ( hex, intensity ) {
  5149. THREE.Light.call( this, hex );
  5150. this.normal = new THREE.Vector3( 0, -1, 0 );
  5151. this.right = new THREE.Vector3( 1, 0, 0 );
  5152. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5153. this.width = 1.0;
  5154. this.height = 1.0;
  5155. this.constantAttenuation = 1.5;
  5156. this.linearAttenuation = 0.5;
  5157. this.quadraticAttenuation = 0.1;
  5158. };
  5159. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  5160. /**
  5161. * @author mrdoob / http://mrdoob.com/
  5162. * @author alteredq / http://alteredqualia.com/
  5163. */
  5164. THREE.DirectionalLight = function ( hex, intensity ) {
  5165. THREE.Light.call( this, hex );
  5166. this.position = new THREE.Vector3( 0, 1, 0 );
  5167. this.target = new THREE.Object3D();
  5168. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5169. this.castShadow = false;
  5170. this.onlyShadow = false;
  5171. //
  5172. this.shadowCameraNear = 50;
  5173. this.shadowCameraFar = 5000;
  5174. this.shadowCameraLeft = -500;
  5175. this.shadowCameraRight = 500;
  5176. this.shadowCameraTop = 500;
  5177. this.shadowCameraBottom = -500;
  5178. this.shadowCameraVisible = false;
  5179. this.shadowBias = 0;
  5180. this.shadowDarkness = 0.5;
  5181. this.shadowMapWidth = 512;
  5182. this.shadowMapHeight = 512;
  5183. //
  5184. this.shadowCascade = false;
  5185. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  5186. this.shadowCascadeCount = 2;
  5187. this.shadowCascadeBias = [ 0, 0, 0 ];
  5188. this.shadowCascadeWidth = [ 512, 512, 512 ];
  5189. this.shadowCascadeHeight = [ 512, 512, 512 ];
  5190. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  5191. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  5192. this.shadowCascadeArray = [];
  5193. //
  5194. this.shadowMap = null;
  5195. this.shadowMapSize = null;
  5196. this.shadowCamera = null;
  5197. this.shadowMatrix = null;
  5198. };
  5199. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  5200. /**
  5201. * @author alteredq / http://alteredqualia.com/
  5202. */
  5203. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  5204. THREE.Light.call( this, skyColorHex );
  5205. this.groundColor = new THREE.Color( groundColorHex );
  5206. this.position = new THREE.Vector3( 0, 100, 0 );
  5207. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5208. };
  5209. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  5210. /**
  5211. * @author mrdoob / http://mrdoob.com/
  5212. */
  5213. THREE.PointLight = function ( hex, intensity, distance ) {
  5214. THREE.Light.call( this, hex );
  5215. this.position = new THREE.Vector3( 0, 0, 0 );
  5216. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5217. this.distance = ( distance !== undefined ) ? distance : 0;
  5218. };
  5219. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  5220. /**
  5221. * @author alteredq / http://alteredqualia.com/
  5222. */
  5223. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  5224. THREE.Light.call( this, hex );
  5225. this.position = new THREE.Vector3( 0, 1, 0 );
  5226. this.target = new THREE.Object3D();
  5227. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5228. this.distance = ( distance !== undefined ) ? distance : 0;
  5229. this.angle = ( angle !== undefined ) ? angle : Math.PI / 2;
  5230. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  5231. this.castShadow = false;
  5232. this.onlyShadow = false;
  5233. //
  5234. this.shadowCameraNear = 50;
  5235. this.shadowCameraFar = 5000;
  5236. this.shadowCameraFov = 50;
  5237. this.shadowCameraVisible = false;
  5238. this.shadowBias = 0;
  5239. this.shadowDarkness = 0.5;
  5240. this.shadowMapWidth = 512;
  5241. this.shadowMapHeight = 512;
  5242. //
  5243. this.shadowMap = null;
  5244. this.shadowMapSize = null;
  5245. this.shadowCamera = null;
  5246. this.shadowMatrix = null;
  5247. };
  5248. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  5249. /**
  5250. * @author alteredq / http://alteredqualia.com/
  5251. */
  5252. THREE.Loader = function ( showStatus ) {
  5253. this.showStatus = showStatus;
  5254. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  5255. this.onLoadStart = function () {};
  5256. this.onLoadProgress = function () {};
  5257. this.onLoadComplete = function () {};
  5258. };
  5259. THREE.Loader.prototype = {
  5260. constructor: THREE.Loader,
  5261. crossOrigin: 'anonymous',
  5262. addStatusElement: function () {
  5263. var e = document.createElement( "div" );
  5264. e.style.position = "absolute";
  5265. e.style.right = "0px";
  5266. e.style.top = "0px";
  5267. e.style.fontSize = "0.8em";
  5268. e.style.textAlign = "left";
  5269. e.style.background = "rgba(0,0,0,0.25)";
  5270. e.style.color = "#fff";
  5271. e.style.width = "120px";
  5272. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  5273. e.style.zIndex = 1000;
  5274. e.innerHTML = "Loading ...";
  5275. return e;
  5276. },
  5277. updateProgress: function ( progress ) {
  5278. var message = "Loaded ";
  5279. if ( progress.total ) {
  5280. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  5281. } else {
  5282. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  5283. }
  5284. this.statusDomElement.innerHTML = message;
  5285. },
  5286. extractUrlBase: function ( url ) {
  5287. var parts = url.split( '/' );
  5288. parts.pop();
  5289. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  5290. },
  5291. initMaterials: function ( materials, texturePath ) {
  5292. var array = [];
  5293. for ( var i = 0; i < materials.length; ++ i ) {
  5294. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  5295. }
  5296. return array;
  5297. },
  5298. needsTangents: function ( materials ) {
  5299. for( var i = 0, il = materials.length; i < il; i ++ ) {
  5300. var m = materials[ i ];
  5301. if ( m instanceof THREE.ShaderMaterial ) return true;
  5302. }
  5303. return false;
  5304. },
  5305. createMaterial: function ( m, texturePath ) {
  5306. var _this = this;
  5307. function is_pow2( n ) {
  5308. var l = Math.log( n ) / Math.LN2;
  5309. return Math.floor( l ) == l;
  5310. }
  5311. function nearest_pow2( n ) {
  5312. var l = Math.log( n ) / Math.LN2;
  5313. return Math.pow( 2, Math.round( l ) );
  5314. }
  5315. function load_image( where, url ) {
  5316. var image = new Image();
  5317. image.onload = function () {
  5318. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  5319. var width = nearest_pow2( this.width );
  5320. var height = nearest_pow2( this.height );
  5321. where.image.width = width;
  5322. where.image.height = height;
  5323. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  5324. } else {
  5325. where.image = this;
  5326. }
  5327. where.needsUpdate = true;
  5328. };
  5329. image.crossOrigin = _this.crossOrigin;
  5330. image.src = url;
  5331. }
  5332. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  5333. var isCompressed = sourceFile.toLowerCase().endsWith( ".dds" );
  5334. var fullPath = texturePath + "/" + sourceFile;
  5335. if ( isCompressed ) {
  5336. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  5337. where[ name ] = texture;
  5338. } else {
  5339. var texture = document.createElement( 'canvas' );
  5340. where[ name ] = new THREE.Texture( texture );
  5341. }
  5342. where[ name ].sourceFile = sourceFile;
  5343. if( repeat ) {
  5344. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  5345. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  5346. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  5347. }
  5348. if ( offset ) {
  5349. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  5350. }
  5351. if ( wrap ) {
  5352. var wrapMap = {
  5353. "repeat": THREE.RepeatWrapping,
  5354. "mirror": THREE.MirroredRepeatWrapping
  5355. }
  5356. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  5357. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  5358. }
  5359. if ( anisotropy ) {
  5360. where[ name ].anisotropy = anisotropy;
  5361. }
  5362. if ( ! isCompressed ) {
  5363. load_image( where[ name ], fullPath );
  5364. }
  5365. }
  5366. function rgb2hex( rgb ) {
  5367. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  5368. }
  5369. // defaults
  5370. var mtype = "MeshLambertMaterial";
  5371. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  5372. // parameters from model file
  5373. if ( m.shading ) {
  5374. var shading = m.shading.toLowerCase();
  5375. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  5376. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  5377. }
  5378. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  5379. mpars.blending = THREE[ m.blending ];
  5380. }
  5381. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  5382. mpars.transparent = m.transparent;
  5383. }
  5384. if ( m.depthTest !== undefined ) {
  5385. mpars.depthTest = m.depthTest;
  5386. }
  5387. if ( m.depthWrite !== undefined ) {
  5388. mpars.depthWrite = m.depthWrite;
  5389. }
  5390. if ( m.visible !== undefined ) {
  5391. mpars.visible = m.visible;
  5392. }
  5393. if ( m.flipSided !== undefined ) {
  5394. mpars.side = THREE.BackSide;
  5395. }
  5396. if ( m.doubleSided !== undefined ) {
  5397. mpars.side = THREE.DoubleSide;
  5398. }
  5399. if ( m.wireframe !== undefined ) {
  5400. mpars.wireframe = m.wireframe;
  5401. }
  5402. if ( m.vertexColors !== undefined ) {
  5403. if ( m.vertexColors === "face" ) {
  5404. mpars.vertexColors = THREE.FaceColors;
  5405. } else if ( m.vertexColors ) {
  5406. mpars.vertexColors = THREE.VertexColors;
  5407. }
  5408. }
  5409. // colors
  5410. if ( m.colorDiffuse ) {
  5411. mpars.color = rgb2hex( m.colorDiffuse );
  5412. } else if ( m.DbgColor ) {
  5413. mpars.color = m.DbgColor;
  5414. }
  5415. if ( m.colorSpecular ) {
  5416. mpars.specular = rgb2hex( m.colorSpecular );
  5417. }
  5418. if ( m.colorAmbient ) {
  5419. mpars.ambient = rgb2hex( m.colorAmbient );
  5420. }
  5421. // modifiers
  5422. if ( m.transparency ) {
  5423. mpars.opacity = m.transparency;
  5424. }
  5425. if ( m.specularCoef ) {
  5426. mpars.shininess = m.specularCoef;
  5427. }
  5428. // textures
  5429. if ( m.mapDiffuse && texturePath ) {
  5430. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  5431. }
  5432. if ( m.mapLight && texturePath ) {
  5433. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  5434. }
  5435. if ( m.mapBump && texturePath ) {
  5436. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  5437. }
  5438. if ( m.mapNormal && texturePath ) {
  5439. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  5440. }
  5441. if ( m.mapSpecular && texturePath ) {
  5442. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  5443. }
  5444. //
  5445. if ( m.mapBumpScale ) {
  5446. mpars.bumpScale = m.mapBumpScale;
  5447. }
  5448. // special case for normal mapped material
  5449. if ( m.mapNormal ) {
  5450. var shader = THREE.ShaderUtils.lib[ "normal" ];
  5451. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5452. uniforms[ "tNormal" ].value = mpars.normalMap;
  5453. if ( m.mapNormalFactor ) {
  5454. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  5455. }
  5456. if ( mpars.map ) {
  5457. uniforms[ "tDiffuse" ].value = mpars.map;
  5458. uniforms[ "enableDiffuse" ].value = true;
  5459. }
  5460. if ( mpars.specularMap ) {
  5461. uniforms[ "tSpecular" ].value = mpars.specularMap;
  5462. uniforms[ "enableSpecular" ].value = true;
  5463. }
  5464. if ( mpars.lightMap ) {
  5465. uniforms[ "tAO" ].value = mpars.lightMap;
  5466. uniforms[ "enableAO" ].value = true;
  5467. }
  5468. // for the moment don't handle displacement texture
  5469. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  5470. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  5471. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  5472. uniforms[ "uShininess" ].value = mpars.shininess;
  5473. if ( mpars.opacity !== undefined ) {
  5474. uniforms[ "uOpacity" ].value = mpars.opacity;
  5475. }
  5476. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5477. var material = new THREE.ShaderMaterial( parameters );
  5478. if ( mpars.transparent ) {
  5479. material.transparent = true;
  5480. }
  5481. } else {
  5482. var material = new THREE[ mtype ]( mpars );
  5483. }
  5484. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  5485. return material;
  5486. }
  5487. };
  5488. /**
  5489. * @author mrdoob / http://mrdoob.com/
  5490. */
  5491. THREE.ImageLoader = function () {
  5492. THREE.EventDispatcher.call( this );
  5493. this.crossOrigin = null;
  5494. };
  5495. THREE.ImageLoader.prototype = {
  5496. constructor: THREE.ImageLoader,
  5497. load: function ( url, image ) {
  5498. var scope = this;
  5499. if ( image === undefined ) image = new Image();
  5500. image.addEventListener( 'load', function () {
  5501. scope.dispatchEvent( { type: 'load', content: image } );
  5502. }, false );
  5503. image.addEventListener( 'error', function () {
  5504. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  5505. }, false );
  5506. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  5507. image.src = url;
  5508. }
  5509. }
  5510. /**
  5511. * @author mrdoob / http://mrdoob.com/
  5512. * @author alteredq / http://alteredqualia.com/
  5513. */
  5514. THREE.JSONLoader = function ( showStatus ) {
  5515. THREE.Loader.call( this, showStatus );
  5516. this.withCredentials = false;
  5517. };
  5518. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  5519. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  5520. var scope = this;
  5521. // todo: unify load API to for easier SceneLoader use
  5522. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  5523. this.onLoadStart();
  5524. this.loadAjaxJSON( this, url, callback, texturePath );
  5525. };
  5526. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  5527. var xhr = new XMLHttpRequest();
  5528. var length = 0;
  5529. xhr.withCredentials = this.withCredentials;
  5530. xhr.onreadystatechange = function () {
  5531. if ( xhr.readyState === xhr.DONE ) {
  5532. if ( xhr.status === 200 || xhr.status === 0 ) {
  5533. if ( xhr.responseText ) {
  5534. var json = JSON.parse( xhr.responseText );
  5535. context.createModel( json, callback, texturePath );
  5536. } else {
  5537. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  5538. }
  5539. // in context of more complex asset initialization
  5540. // do not block on single failed file
  5541. // maybe should go even one more level up
  5542. context.onLoadComplete();
  5543. } else {
  5544. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5545. }
  5546. } else if ( xhr.readyState === xhr.LOADING ) {
  5547. if ( callbackProgress ) {
  5548. if ( length === 0 ) {
  5549. length = xhr.getResponseHeader( "Content-Length" );
  5550. }
  5551. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  5552. }
  5553. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  5554. length = xhr.getResponseHeader( "Content-Length" );
  5555. }
  5556. };
  5557. xhr.open( "GET", url, true );
  5558. xhr.send( null );
  5559. };
  5560. THREE.JSONLoader.prototype.createModel = function ( json, callback, texturePath ) {
  5561. var scope = this,
  5562. geometry = new THREE.Geometry(),
  5563. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  5564. parseModel( scale );
  5565. parseSkin();
  5566. parseMorphing( scale );
  5567. geometry.computeCentroids();
  5568. geometry.computeFaceNormals();
  5569. function parseModel( scale ) {
  5570. function isBitSet( value, position ) {
  5571. return value & ( 1 << position );
  5572. }
  5573. var i, j, fi,
  5574. offset, zLength, nVertices,
  5575. colorIndex, normalIndex, uvIndex, materialIndex,
  5576. type,
  5577. isQuad,
  5578. hasMaterial,
  5579. hasFaceUv, hasFaceVertexUv,
  5580. hasFaceNormal, hasFaceVertexNormal,
  5581. hasFaceColor, hasFaceVertexColor,
  5582. vertex, face, color, normal,
  5583. uvLayer, uvs, u, v,
  5584. faces = json.faces,
  5585. vertices = json.vertices,
  5586. normals = json.normals,
  5587. colors = json.colors,
  5588. nUvLayers = 0;
  5589. // disregard empty arrays
  5590. for ( i = 0; i < json.uvs.length; i++ ) {
  5591. if ( json.uvs[ i ].length ) nUvLayers ++;
  5592. }
  5593. for ( i = 0; i < nUvLayers; i++ ) {
  5594. geometry.faceUvs[ i ] = [];
  5595. geometry.faceVertexUvs[ i ] = [];
  5596. }
  5597. offset = 0;
  5598. zLength = vertices.length;
  5599. while ( offset < zLength ) {
  5600. vertex = new THREE.Vector3();
  5601. vertex.x = vertices[ offset ++ ] * scale;
  5602. vertex.y = vertices[ offset ++ ] * scale;
  5603. vertex.z = vertices[ offset ++ ] * scale;
  5604. geometry.vertices.push( vertex );
  5605. }
  5606. offset = 0;
  5607. zLength = faces.length;
  5608. while ( offset < zLength ) {
  5609. type = faces[ offset ++ ];
  5610. isQuad = isBitSet( type, 0 );
  5611. hasMaterial = isBitSet( type, 1 );
  5612. hasFaceUv = isBitSet( type, 2 );
  5613. hasFaceVertexUv = isBitSet( type, 3 );
  5614. hasFaceNormal = isBitSet( type, 4 );
  5615. hasFaceVertexNormal = isBitSet( type, 5 );
  5616. hasFaceColor = isBitSet( type, 6 );
  5617. hasFaceVertexColor = isBitSet( type, 7 );
  5618. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  5619. if ( isQuad ) {
  5620. face = new THREE.Face4();
  5621. face.a = faces[ offset ++ ];
  5622. face.b = faces[ offset ++ ];
  5623. face.c = faces[ offset ++ ];
  5624. face.d = faces[ offset ++ ];
  5625. nVertices = 4;
  5626. } else {
  5627. face = new THREE.Face3();
  5628. face.a = faces[ offset ++ ];
  5629. face.b = faces[ offset ++ ];
  5630. face.c = faces[ offset ++ ];
  5631. nVertices = 3;
  5632. }
  5633. if ( hasMaterial ) {
  5634. materialIndex = faces[ offset ++ ];
  5635. face.materialIndex = materialIndex;
  5636. }
  5637. // to get face <=> uv index correspondence
  5638. fi = geometry.faces.length;
  5639. if ( hasFaceUv ) {
  5640. for ( i = 0; i < nUvLayers; i++ ) {
  5641. uvLayer = json.uvs[ i ];
  5642. uvIndex = faces[ offset ++ ];
  5643. u = uvLayer[ uvIndex * 2 ];
  5644. v = uvLayer[ uvIndex * 2 + 1 ];
  5645. geometry.faceUvs[ i ][ fi ] = new THREE.Vector2( u, v );
  5646. }
  5647. }
  5648. if ( hasFaceVertexUv ) {
  5649. for ( i = 0; i < nUvLayers; i++ ) {
  5650. uvLayer = json.uvs[ i ];
  5651. uvs = [];
  5652. for ( j = 0; j < nVertices; j ++ ) {
  5653. uvIndex = faces[ offset ++ ];
  5654. u = uvLayer[ uvIndex * 2 ];
  5655. v = uvLayer[ uvIndex * 2 + 1 ];
  5656. uvs[ j ] = new THREE.Vector2( u, v );
  5657. }
  5658. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  5659. }
  5660. }
  5661. if ( hasFaceNormal ) {
  5662. normalIndex = faces[ offset ++ ] * 3;
  5663. normal = new THREE.Vector3();
  5664. normal.x = normals[ normalIndex ++ ];
  5665. normal.y = normals[ normalIndex ++ ];
  5666. normal.z = normals[ normalIndex ];
  5667. face.normal = normal;
  5668. }
  5669. if ( hasFaceVertexNormal ) {
  5670. for ( i = 0; i < nVertices; i++ ) {
  5671. normalIndex = faces[ offset ++ ] * 3;
  5672. normal = new THREE.Vector3();
  5673. normal.x = normals[ normalIndex ++ ];
  5674. normal.y = normals[ normalIndex ++ ];
  5675. normal.z = normals[ normalIndex ];
  5676. face.vertexNormals.push( normal );
  5677. }
  5678. }
  5679. if ( hasFaceColor ) {
  5680. colorIndex = faces[ offset ++ ];
  5681. color = new THREE.Color( colors[ colorIndex ] );
  5682. face.color = color;
  5683. }
  5684. if ( hasFaceVertexColor ) {
  5685. for ( i = 0; i < nVertices; i++ ) {
  5686. colorIndex = faces[ offset ++ ];
  5687. color = new THREE.Color( colors[ colorIndex ] );
  5688. face.vertexColors.push( color );
  5689. }
  5690. }
  5691. geometry.faces.push( face );
  5692. }
  5693. };
  5694. function parseSkin() {
  5695. var i, l, x, y, z, w, a, b, c, d;
  5696. if ( json.skinWeights ) {
  5697. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  5698. x = json.skinWeights[ i ];
  5699. y = json.skinWeights[ i + 1 ];
  5700. z = 0;
  5701. w = 0;
  5702. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  5703. }
  5704. }
  5705. if ( json.skinIndices ) {
  5706. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  5707. a = json.skinIndices[ i ];
  5708. b = json.skinIndices[ i + 1 ];
  5709. c = 0;
  5710. d = 0;
  5711. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  5712. }
  5713. }
  5714. geometry.bones = json.bones;
  5715. geometry.animation = json.animation;
  5716. };
  5717. function parseMorphing( scale ) {
  5718. if ( json.morphTargets !== undefined ) {
  5719. var i, l, v, vl, dstVertices, srcVertices;
  5720. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  5721. geometry.morphTargets[ i ] = {};
  5722. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  5723. geometry.morphTargets[ i ].vertices = [];
  5724. dstVertices = geometry.morphTargets[ i ].vertices;
  5725. srcVertices = json.morphTargets [ i ].vertices;
  5726. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  5727. var vertex = new THREE.Vector3();
  5728. vertex.x = srcVertices[ v ] * scale;
  5729. vertex.y = srcVertices[ v + 1 ] * scale;
  5730. vertex.z = srcVertices[ v + 2 ] * scale;
  5731. dstVertices.push( vertex );
  5732. }
  5733. }
  5734. }
  5735. if ( json.morphColors !== undefined ) {
  5736. var i, l, c, cl, dstColors, srcColors, color;
  5737. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  5738. geometry.morphColors[ i ] = {};
  5739. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  5740. geometry.morphColors[ i ].colors = [];
  5741. dstColors = geometry.morphColors[ i ].colors;
  5742. srcColors = json.morphColors [ i ].colors;
  5743. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  5744. color = new THREE.Color( 0xffaa00 );
  5745. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  5746. dstColors.push( color );
  5747. }
  5748. }
  5749. }
  5750. };
  5751. var materials = this.initMaterials( json.materials, texturePath );
  5752. if ( this.needsTangents( materials ) ) geometry.computeTangents();
  5753. callback( geometry, materials );
  5754. };
  5755. /**
  5756. * @author mrdoob / http://mrdoob.com/
  5757. */
  5758. THREE.LoadingMonitor = function () {
  5759. THREE.EventDispatcher.call( this );
  5760. var scope = this;
  5761. var loaded = 0;
  5762. var total = 0;
  5763. var onLoad = function ( event ) {
  5764. loaded ++;
  5765. scope.dispatchEvent( { type: 'progress', loaded: loaded, total: total } );
  5766. if ( loaded === total ) {
  5767. scope.dispatchEvent( { type: 'load' } );
  5768. }
  5769. };
  5770. this.add = function ( loader ) {
  5771. total ++;
  5772. loader.addEventListener( 'load', onLoad, false );
  5773. };
  5774. };
  5775. /**
  5776. * @author alteredq / http://alteredqualia.com/
  5777. */
  5778. THREE.SceneLoader = function () {
  5779. this.onLoadStart = function () {};
  5780. this.onLoadProgress = function() {};
  5781. this.onLoadComplete = function () {};
  5782. this.callbackSync = function () {};
  5783. this.callbackProgress = function () {};
  5784. this.geometryHandlerMap = {};
  5785. this.hierarchyHandlerMap = {};
  5786. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  5787. };
  5788. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  5789. THREE.SceneLoader.prototype.load = function ( url, callbackFinished ) {
  5790. var scope = this;
  5791. var xhr = new XMLHttpRequest();
  5792. xhr.onreadystatechange = function () {
  5793. if ( xhr.readyState === 4 ) {
  5794. if ( xhr.status === 200 || xhr.status === 0 ) {
  5795. var json = JSON.parse( xhr.responseText );
  5796. scope.parse( json, callbackFinished, url );
  5797. } else {
  5798. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5799. }
  5800. }
  5801. };
  5802. xhr.open( "GET", url, true );
  5803. xhr.send( null );
  5804. };
  5805. THREE.SceneLoader.prototype.addGeometryHandler = function ( typeID, loaderClass ) {
  5806. this.geometryHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5807. };
  5808. THREE.SceneLoader.prototype.addHierarchyHandler = function ( typeID, loaderClass ) {
  5809. this.hierarchyHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5810. };
  5811. THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
  5812. var scope = this;
  5813. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  5814. var geometry, material, camera, fog,
  5815. texture, images, color,
  5816. light, hex, intensity,
  5817. counter_models, counter_textures,
  5818. total_models, total_textures,
  5819. result;
  5820. var target_array = [];
  5821. var data = json;
  5822. // async geometry loaders
  5823. for ( var typeID in this.geometryHandlerMap ) {
  5824. var loaderClass = this.geometryHandlerMap[ typeID ][ "loaderClass" ];
  5825. this.geometryHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5826. }
  5827. // async hierachy loaders
  5828. for ( var typeID in this.hierarchyHandlerMap ) {
  5829. var loaderClass = this.hierarchyHandlerMap[ typeID ][ "loaderClass" ];
  5830. this.hierarchyHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5831. }
  5832. counter_models = 0;
  5833. counter_textures = 0;
  5834. result = {
  5835. scene: new THREE.Scene(),
  5836. geometries: {},
  5837. face_materials: {},
  5838. materials: {},
  5839. textures: {},
  5840. objects: {},
  5841. cameras: {},
  5842. lights: {},
  5843. fogs: {},
  5844. empties: {}
  5845. };
  5846. if ( data.transform ) {
  5847. var position = data.transform.position,
  5848. rotation = data.transform.rotation,
  5849. scale = data.transform.scale;
  5850. if ( position )
  5851. result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
  5852. if ( rotation )
  5853. result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
  5854. if ( scale )
  5855. result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
  5856. if ( position || rotation || scale ) {
  5857. result.scene.updateMatrix();
  5858. result.scene.updateMatrixWorld();
  5859. }
  5860. }
  5861. function get_url( source_url, url_type ) {
  5862. if ( url_type == "relativeToHTML" ) {
  5863. return source_url;
  5864. } else {
  5865. return urlBase + "/" + source_url;
  5866. }
  5867. };
  5868. // toplevel loader function, delegates to handle_children
  5869. function handle_objects() {
  5870. handle_children( result.scene, data.objects );
  5871. }
  5872. // handle all the children from the loaded json and attach them to given parent
  5873. function handle_children( parent, children ) {
  5874. var mat, dst, pos, rot, scl, quat;
  5875. for ( var objID in children ) {
  5876. // check by id if child has already been handled,
  5877. // if not, create new object
  5878. if ( result.objects[ objID ] === undefined ) {
  5879. var objJSON = children[ objID ];
  5880. var object = null;
  5881. // meshes
  5882. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlerMap ) ) {
  5883. if ( objJSON.loading === undefined ) {
  5884. var reservedTypes = { "type": 1, "url": 1, "material": 1,
  5885. "position": 1, "rotation": 1, "scale" : 1,
  5886. "visible": 1, "children": 1, "properties": 1,
  5887. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1 };
  5888. var loaderParameters = {};
  5889. for ( var parType in objJSON ) {
  5890. if ( ! ( parType in reservedTypes ) ) {
  5891. loaderParameters[ parType ] = objJSON[ parType ];
  5892. }
  5893. }
  5894. material = result.materials[ objJSON.material ];
  5895. objJSON.loading = true;
  5896. var loader = scope.hierarchyHandlerMap[ objJSON.type ][ "loaderObject" ];
  5897. // ColladaLoader
  5898. if ( loader.options ) {
  5899. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  5900. // UTF8Loader
  5901. // OBJLoader
  5902. } else {
  5903. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  5904. }
  5905. }
  5906. } else if ( objJSON.geometry !== undefined ) {
  5907. geometry = result.geometries[ objJSON.geometry ];
  5908. // geometry already loaded
  5909. if ( geometry ) {
  5910. var needsTangents = false;
  5911. material = result.materials[ objJSON.material ];
  5912. needsTangents = material instanceof THREE.ShaderMaterial;
  5913. pos = objJSON.position;
  5914. rot = objJSON.rotation;
  5915. scl = objJSON.scale;
  5916. mat = objJSON.matrix;
  5917. quat = objJSON.quaternion;
  5918. // use materials from the model file
  5919. // if there is no material specified in the object
  5920. if ( ! objJSON.material ) {
  5921. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  5922. }
  5923. // use materials from the model file
  5924. // if there is just empty face material
  5925. // (must create new material as each model has its own face material)
  5926. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  5927. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  5928. }
  5929. if ( material instanceof THREE.MeshFaceMaterial ) {
  5930. for ( var i = 0; i < material.materials.length; i ++ ) {
  5931. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  5932. }
  5933. }
  5934. if ( needsTangents ) {
  5935. geometry.computeTangents();
  5936. }
  5937. if ( objJSON.skin ) {
  5938. object = new THREE.SkinnedMesh( geometry, material );
  5939. } else if ( objJSON.morph ) {
  5940. object = new THREE.MorphAnimMesh( geometry, material );
  5941. if ( objJSON.duration !== undefined ) {
  5942. object.duration = objJSON.duration;
  5943. }
  5944. if ( objJSON.time !== undefined ) {
  5945. object.time = objJSON.time;
  5946. }
  5947. if ( objJSON.mirroredLoop !== undefined ) {
  5948. object.mirroredLoop = objJSON.mirroredLoop;
  5949. }
  5950. if ( material.morphNormals ) {
  5951. geometry.computeMorphNormals();
  5952. }
  5953. } else {
  5954. object = new THREE.Mesh( geometry, material );
  5955. }
  5956. object.name = objID;
  5957. if ( mat ) {
  5958. object.matrixAutoUpdate = false;
  5959. object.matrix.set(
  5960. mat[0], mat[1], mat[2], mat[3],
  5961. mat[4], mat[5], mat[6], mat[7],
  5962. mat[8], mat[9], mat[10], mat[11],
  5963. mat[12], mat[13], mat[14], mat[15]
  5964. );
  5965. } else {
  5966. object.position.set( pos[0], pos[1], pos[2] );
  5967. if ( quat ) {
  5968. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  5969. object.useQuaternion = true;
  5970. } else {
  5971. object.rotation.set( rot[0], rot[1], rot[2] );
  5972. }
  5973. object.scale.set( scl[0], scl[1], scl[2] );
  5974. }
  5975. object.visible = objJSON.visible;
  5976. object.castShadow = objJSON.castShadow;
  5977. object.receiveShadow = objJSON.receiveShadow;
  5978. parent.add( object );
  5979. result.objects[ objID ] = object;
  5980. }
  5981. // lights
  5982. } else if ( objJSON.type === "DirectionalLight" || objJSON.type === "PointLight" || objJSON.type === "AmbientLight" ) {
  5983. hex = ( objJSON.color !== undefined ) ? objJSON.color : 0xffffff;
  5984. intensity = ( objJSON.intensity !== undefined ) ? objJSON.intensity : 1;
  5985. if ( objJSON.type === "DirectionalLight" ) {
  5986. pos = objJSON.direction;
  5987. light = new THREE.DirectionalLight( hex, intensity );
  5988. light.position.set( pos[0], pos[1], pos[2] );
  5989. if ( objJSON.target ) {
  5990. target_array.push( { "object": light, "targetName" : objJSON.target } );
  5991. // kill existing default target
  5992. // otherwise it gets added to scene when parent gets added
  5993. light.target = null;
  5994. }
  5995. } else if ( objJSON.type === "PointLight" ) {
  5996. pos = objJSON.position;
  5997. dst = objJSON.distance;
  5998. light = new THREE.PointLight( hex, intensity, dst );
  5999. light.position.set( pos[0], pos[1], pos[2] );
  6000. } else if ( objJSON.type === "AmbientLight" ) {
  6001. light = new THREE.AmbientLight( hex );
  6002. }
  6003. parent.add( light );
  6004. light.name = objID;
  6005. result.lights[ objID ] = light;
  6006. result.objects[ objID ] = light;
  6007. // cameras
  6008. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  6009. if ( objJSON.type === "PerspectiveCamera" ) {
  6010. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  6011. } else if ( objJSON.type === "OrthographicCamera" ) {
  6012. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  6013. }
  6014. pos = objJSON.position;
  6015. camera.position.set( pos[0], pos[1], pos[2] );
  6016. parent.add( camera );
  6017. camera.name = objID;
  6018. result.cameras[ objID ] = camera;
  6019. result.objects[ objID ] = camera;
  6020. // pure Object3D
  6021. } else {
  6022. pos = objJSON.position;
  6023. rot = objJSON.rotation;
  6024. scl = objJSON.scale;
  6025. quat = objJSON.quaternion;
  6026. object = new THREE.Object3D();
  6027. object.name = objID;
  6028. object.position.set( pos[0], pos[1], pos[2] );
  6029. if ( quat ) {
  6030. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  6031. object.useQuaternion = true;
  6032. } else {
  6033. object.rotation.set( rot[0], rot[1], rot[2] );
  6034. }
  6035. object.scale.set( scl[0], scl[1], scl[2] );
  6036. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  6037. parent.add( object );
  6038. result.objects[ objID ] = object;
  6039. result.empties[ objID ] = object;
  6040. }
  6041. if ( object ) {
  6042. if ( objJSON.properties !== undefined ) {
  6043. for ( var key in objJSON.properties ) {
  6044. var value = objJSON.properties[ key ];
  6045. object.properties[ key ] = value;
  6046. }
  6047. }
  6048. if ( objJSON.children !== undefined ) {
  6049. handle_children( object, objJSON.children );
  6050. }
  6051. }
  6052. }
  6053. }
  6054. };
  6055. function handle_mesh( geo, mat, id ) {
  6056. result.geometries[ id ] = geo;
  6057. result.face_materials[ id ] = mat;
  6058. handle_objects();
  6059. };
  6060. function handle_hierarchy( node, id, parent, material, obj ) {
  6061. var p = obj.position;
  6062. var r = obj.rotation;
  6063. var q = obj.quaternion;
  6064. var s = obj.scale;
  6065. node.position.set( p[0], p[1], p[2] );
  6066. if ( q ) {
  6067. node.quaternion.set( q[0], q[1], q[2], q[3] );
  6068. node.useQuaternion = true;
  6069. } else {
  6070. node.rotation.set( r[0], r[1], r[2] );
  6071. }
  6072. node.scale.set( s[0], s[1], s[2] );
  6073. // override children materials
  6074. // if object material was specified in JSON explicitly
  6075. if ( material ) {
  6076. node.traverse( function ( child ) {
  6077. child.material = material;
  6078. } );
  6079. }
  6080. // override children visibility
  6081. // with root node visibility as specified in JSON
  6082. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  6083. node.traverse( function ( child ) {
  6084. child.visible = visible;
  6085. } );
  6086. parent.add( node );
  6087. node.name = id;
  6088. result.objects[ id ] = node;
  6089. handle_objects();
  6090. };
  6091. function create_callback_geometry( id ) {
  6092. return function( geo, mat ) {
  6093. handle_mesh( geo, mat, id );
  6094. counter_models -= 1;
  6095. scope.onLoadComplete();
  6096. async_callback_gate();
  6097. }
  6098. };
  6099. function create_callback_hierachy( id, parent, material, obj ) {
  6100. return function( event ) {
  6101. var result;
  6102. // loaders which use EventDispatcher
  6103. if ( event.content ) {
  6104. result = event.content;
  6105. // ColladaLoader
  6106. } else if ( event.dae ) {
  6107. result = event.scene;
  6108. // UTF8Loader
  6109. } else {
  6110. result = event;
  6111. }
  6112. handle_hierarchy( result, id, parent, material, obj );
  6113. counter_models -= 1;
  6114. scope.onLoadComplete();
  6115. async_callback_gate();
  6116. }
  6117. };
  6118. function create_callback_embed( id ) {
  6119. return function( geo, mat ) {
  6120. result.geometries[ id ] = geo;
  6121. result.face_materials[ id ] = mat;
  6122. }
  6123. };
  6124. function async_callback_gate() {
  6125. var progress = {
  6126. totalModels : total_models,
  6127. totalTextures : total_textures,
  6128. loadedModels : total_models - counter_models,
  6129. loadedTextures : total_textures - counter_textures
  6130. };
  6131. scope.callbackProgress( progress, result );
  6132. scope.onLoadProgress();
  6133. if ( counter_models === 0 && counter_textures === 0 ) {
  6134. finalize();
  6135. callbackFinished( result );
  6136. }
  6137. };
  6138. function finalize() {
  6139. // take care of targets which could be asynchronously loaded objects
  6140. for ( var i = 0; i < target_array.length; i ++ ) {
  6141. var ta = target_array[ i ];
  6142. var target = result.objects[ ta.targetName ];
  6143. if ( target ) {
  6144. ta.object.target = target;
  6145. } else {
  6146. // if there was error and target of specified name doesn't exist in the scene file
  6147. // create instead dummy target
  6148. // (target must be added to scene explicitly as parent is already added)
  6149. ta.object.target = new THREE.Object3D();
  6150. result.scene.add( ta.object.target );
  6151. }
  6152. ta.object.target.properties.targetInverse = ta.object;
  6153. }
  6154. };
  6155. var callbackTexture = function ( count ) {
  6156. counter_textures -= count;
  6157. async_callback_gate();
  6158. scope.onLoadComplete();
  6159. };
  6160. // must use this instead of just directly calling callbackTexture
  6161. // because of closure in the calling context loop
  6162. var generateTextureCallback = function ( count ) {
  6163. return function() {
  6164. callbackTexture( count );
  6165. };
  6166. };
  6167. // first go synchronous elements
  6168. // fogs
  6169. var fogID, fogJSON;
  6170. for ( fogID in data.fogs ) {
  6171. fogJSON = data.fogs[ fogID ];
  6172. if ( fogJSON.type === "linear" ) {
  6173. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  6174. } else if ( fogJSON.type === "exp2" ) {
  6175. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  6176. }
  6177. color = fogJSON.color;
  6178. fog.color.setRGB( color[0], color[1], color[2] );
  6179. result.fogs[ fogID ] = fog;
  6180. }
  6181. // now come potentially asynchronous elements
  6182. // geometries
  6183. // count how many geometries will be loaded asynchronously
  6184. var geoID, geoJSON;
  6185. for ( geoID in data.geometries ) {
  6186. geoJSON = data.geometries[ geoID ];
  6187. if ( geoJSON.type in this.geometryHandlerMap ) {
  6188. counter_models += 1;
  6189. scope.onLoadStart();
  6190. }
  6191. }
  6192. // count how many hierarchies will be loaded asynchronously
  6193. var objID, objJSON;
  6194. for ( objID in data.objects ) {
  6195. objJSON = data.objects[ objID ];
  6196. if ( objJSON.type && ( objJSON.type in this.hierarchyHandlerMap ) ) {
  6197. counter_models += 1;
  6198. scope.onLoadStart();
  6199. }
  6200. }
  6201. total_models = counter_models;
  6202. for ( geoID in data.geometries ) {
  6203. geoJSON = data.geometries[ geoID ];
  6204. if ( geoJSON.type === "cube" ) {
  6205. geometry = new THREE.CubeGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  6206. result.geometries[ geoID ] = geometry;
  6207. } else if ( geoJSON.type === "plane" ) {
  6208. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  6209. result.geometries[ geoID ] = geometry;
  6210. } else if ( geoJSON.type === "sphere" ) {
  6211. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  6212. result.geometries[ geoID ] = geometry;
  6213. } else if ( geoJSON.type === "cylinder" ) {
  6214. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  6215. result.geometries[ geoID ] = geometry;
  6216. } else if ( geoJSON.type === "torus" ) {
  6217. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  6218. result.geometries[ geoID ] = geometry;
  6219. } else if ( geoJSON.type === "icosahedron" ) {
  6220. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  6221. result.geometries[ geoID ] = geometry;
  6222. } else if ( geoJSON.type in this.geometryHandlerMap ) {
  6223. var loaderParameters = {};
  6224. for ( var parType in geoJSON ) {
  6225. if ( parType !== "type" && parType !== "url" ) {
  6226. loaderParameters[ parType ] = geoJSON[ parType ];
  6227. }
  6228. }
  6229. var loader = this.geometryHandlerMap[ geoJSON.type ][ "loaderObject" ];
  6230. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  6231. } else if ( geoJSON.type === "embedded" ) {
  6232. var modelJson = data.embeds[ geoJSON.id ],
  6233. texture_path = "";
  6234. // pass metadata along to jsonLoader so it knows the format version
  6235. modelJson.metadata = data.metadata;
  6236. if ( modelJson ) {
  6237. var jsonLoader = this.geometryHandlerMap[ "ascii" ][ "loaderObject" ];
  6238. jsonLoader.createModel( modelJson, create_callback_embed( geoID ), texture_path );
  6239. }
  6240. }
  6241. }
  6242. // textures
  6243. // count how many textures will be loaded asynchronously
  6244. var textureID, textureJSON;
  6245. for ( textureID in data.textures ) {
  6246. textureJSON = data.textures[ textureID ];
  6247. if ( textureJSON.url instanceof Array ) {
  6248. counter_textures += textureJSON.url.length;
  6249. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  6250. scope.onLoadStart();
  6251. }
  6252. } else {
  6253. counter_textures += 1;
  6254. scope.onLoadStart();
  6255. }
  6256. }
  6257. total_textures = counter_textures;
  6258. for ( textureID in data.textures ) {
  6259. textureJSON = data.textures[ textureID ];
  6260. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  6261. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  6262. }
  6263. if ( textureJSON.url instanceof Array ) {
  6264. var count = textureJSON.url.length;
  6265. var url_array = [];
  6266. for( var i = 0; i < count; i ++ ) {
  6267. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  6268. }
  6269. var isCompressed = url_array[ 0 ].endsWith( ".dds" );
  6270. if ( isCompressed ) {
  6271. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6272. } else {
  6273. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6274. }
  6275. } else {
  6276. var isCompressed = textureJSON.url.toLowerCase().endsWith( ".dds" );
  6277. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  6278. var textureCallback = generateTextureCallback( 1 );
  6279. if ( isCompressed ) {
  6280. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  6281. } else {
  6282. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  6283. }
  6284. if ( THREE[ textureJSON.minFilter ] !== undefined )
  6285. texture.minFilter = THREE[ textureJSON.minFilter ];
  6286. if ( THREE[ textureJSON.magFilter ] !== undefined )
  6287. texture.magFilter = THREE[ textureJSON.magFilter ];
  6288. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  6289. if ( textureJSON.repeat ) {
  6290. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  6291. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  6292. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  6293. }
  6294. if ( textureJSON.offset ) {
  6295. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  6296. }
  6297. // handle wrap after repeat so that default repeat can be overriden
  6298. if ( textureJSON.wrap ) {
  6299. var wrapMap = {
  6300. "repeat" : THREE.RepeatWrapping,
  6301. "mirror" : THREE.MirroredRepeatWrapping
  6302. }
  6303. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  6304. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  6305. }
  6306. }
  6307. result.textures[ textureID ] = texture;
  6308. }
  6309. // materials
  6310. var matID, matJSON;
  6311. var parID;
  6312. for ( matID in data.materials ) {
  6313. matJSON = data.materials[ matID ];
  6314. for ( parID in matJSON.parameters ) {
  6315. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  6316. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  6317. } else if ( parID === "shading" ) {
  6318. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  6319. } else if ( parID === "side" ) {
  6320. if ( matJSON.parameters[ parID ] == "double" ) {
  6321. matJSON.parameters[ parID ] = THREE.DoubleSide;
  6322. } else if ( matJSON.parameters[ parID ] == "back" ) {
  6323. matJSON.parameters[ parID ] = THREE.BackSide;
  6324. } else {
  6325. matJSON.parameters[ parID ] = THREE.FrontSide;
  6326. }
  6327. } else if ( parID === "blending" ) {
  6328. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  6329. } else if ( parID === "combine" ) {
  6330. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  6331. } else if ( parID === "vertexColors" ) {
  6332. if ( matJSON.parameters[ parID ] == "face" ) {
  6333. matJSON.parameters[ parID ] = THREE.FaceColors;
  6334. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  6335. } else if ( matJSON.parameters[ parID ] ) {
  6336. matJSON.parameters[ parID ] = THREE.VertexColors;
  6337. }
  6338. } else if ( parID === "wrapRGB" ) {
  6339. var v3 = matJSON.parameters[ parID ];
  6340. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  6341. }
  6342. }
  6343. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  6344. matJSON.parameters.transparent = true;
  6345. }
  6346. if ( matJSON.parameters.normalMap ) {
  6347. var shader = THREE.ShaderUtils.lib[ "normal" ];
  6348. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6349. var diffuse = matJSON.parameters.color;
  6350. var specular = matJSON.parameters.specular;
  6351. var ambient = matJSON.parameters.ambient;
  6352. var shininess = matJSON.parameters.shininess;
  6353. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  6354. if ( matJSON.parameters.normalScale ) {
  6355. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  6356. }
  6357. if ( matJSON.parameters.map ) {
  6358. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  6359. uniforms[ "enableDiffuse" ].value = true;
  6360. }
  6361. if ( matJSON.parameters.envMap ) {
  6362. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  6363. uniforms[ "enableReflection" ].value = true;
  6364. uniforms[ "uReflectivity" ].value = matJSON.parameters.reflectivity;
  6365. }
  6366. if ( matJSON.parameters.lightMap ) {
  6367. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  6368. uniforms[ "enableAO" ].value = true;
  6369. }
  6370. if ( matJSON.parameters.specularMap ) {
  6371. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  6372. uniforms[ "enableSpecular" ].value = true;
  6373. }
  6374. if ( matJSON.parameters.displacementMap ) {
  6375. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  6376. uniforms[ "enableDisplacement" ].value = true;
  6377. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  6378. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  6379. }
  6380. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  6381. uniforms[ "uSpecularColor" ].value.setHex( specular );
  6382. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  6383. uniforms[ "uShininess" ].value = shininess;
  6384. if ( matJSON.parameters.opacity ) {
  6385. uniforms[ "uOpacity" ].value = matJSON.parameters.opacity;
  6386. }
  6387. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6388. material = new THREE.ShaderMaterial( parameters );
  6389. } else {
  6390. material = new THREE[ matJSON.type ]( matJSON.parameters );
  6391. }
  6392. result.materials[ matID ] = material;
  6393. }
  6394. // second pass through all materials to initialize MeshFaceMaterials
  6395. // that could be referring to other materials out of order
  6396. for ( matID in data.materials ) {
  6397. matJSON = data.materials[ matID ];
  6398. if ( matJSON.parameters.materials ) {
  6399. var materialArray = [];
  6400. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  6401. var label = matJSON.parameters.materials[ i ];
  6402. materialArray.push( result.materials[ label ] );
  6403. }
  6404. result.materials[ matID ].materials = materialArray;
  6405. }
  6406. }
  6407. // objects ( synchronous init of procedural primitives )
  6408. handle_objects();
  6409. // defaults
  6410. if ( result.cameras && data.defaults.camera ) {
  6411. result.currentCamera = result.cameras[ data.defaults.camera ];
  6412. }
  6413. if ( result.fogs && data.defaults.fog ) {
  6414. result.scene.fog = result.fogs[ data.defaults.fog ];
  6415. }
  6416. color = data.defaults.bgcolor;
  6417. result.bgColor = new THREE.Color();
  6418. result.bgColor.setRGB( color[0], color[1], color[2] );
  6419. result.bgColorAlpha = data.defaults.bgalpha;
  6420. // synchronous callback
  6421. scope.callbackSync( result );
  6422. // just in case there are no async elements
  6423. async_callback_gate();
  6424. };
  6425. /**
  6426. * @author mrdoob / http://mrdoob.com/
  6427. */
  6428. THREE.TextureLoader = function () {
  6429. THREE.EventDispatcher.call( this );
  6430. this.crossOrigin = null;
  6431. };
  6432. THREE.TextureLoader.prototype = {
  6433. constructor: THREE.TextureLoader,
  6434. load: function ( url ) {
  6435. var scope = this;
  6436. var image = new Image();
  6437. image.addEventListener( 'load', function () {
  6438. var texture = new THREE.Texture( image );
  6439. texture.needsUpdate = true;
  6440. scope.dispatchEvent( { type: 'load', content: texture } );
  6441. }, false );
  6442. image.addEventListener( 'error', function () {
  6443. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  6444. }, false );
  6445. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  6446. image.src = url;
  6447. }
  6448. }
  6449. /**
  6450. * @author mrdoob / http://mrdoob.com/
  6451. * @author alteredq / http://alteredqualia.com/
  6452. */
  6453. THREE.Material = function () {
  6454. THREE.EventDispatcher.call( this );
  6455. this.id = THREE.MaterialIdCount ++;
  6456. this.name = '';
  6457. this.side = THREE.FrontSide;
  6458. this.opacity = 1;
  6459. this.transparent = false;
  6460. this.blending = THREE.NormalBlending;
  6461. this.blendSrc = THREE.SrcAlphaFactor;
  6462. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  6463. this.blendEquation = THREE.AddEquation;
  6464. this.depthTest = true;
  6465. this.depthWrite = true;
  6466. this.polygonOffset = false;
  6467. this.polygonOffsetFactor = 0;
  6468. this.polygonOffsetUnits = 0;
  6469. this.alphaTest = 0;
  6470. this.overdraw = false; // Boolean for fixing antialiasing gaps in CanvasRenderer
  6471. this.visible = true;
  6472. this.needsUpdate = true;
  6473. };
  6474. THREE.Material.prototype.setValues = function ( values ) {
  6475. if ( values === undefined ) return;
  6476. for ( var key in values ) {
  6477. var newValue = values[ key ];
  6478. if ( newValue === undefined ) {
  6479. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  6480. continue;
  6481. }
  6482. if ( key in this ) {
  6483. var currentValue = this[ key ];
  6484. if ( currentValue instanceof THREE.Color && newValue instanceof THREE.Color ) {
  6485. currentValue.copy( newValue );
  6486. } else if ( currentValue instanceof THREE.Color ) {
  6487. currentValue.set( newValue );
  6488. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  6489. currentValue.copy( newValue );
  6490. } else {
  6491. this[ key ] = newValue;
  6492. }
  6493. }
  6494. }
  6495. };
  6496. THREE.Material.prototype.clone = function ( material ) {
  6497. if ( material === undefined ) material = new THREE.Material();
  6498. material.name = this.name;
  6499. material.side = this.side;
  6500. material.opacity = this.opacity;
  6501. material.transparent = this.transparent;
  6502. material.blending = this.blending;
  6503. material.blendSrc = this.blendSrc;
  6504. material.blendDst = this.blendDst;
  6505. material.blendEquation = this.blendEquation;
  6506. material.depthTest = this.depthTest;
  6507. material.depthWrite = this.depthWrite;
  6508. material.polygonOffset = this.polygonOffset;
  6509. material.polygonOffsetFactor = this.polygonOffsetFactor;
  6510. material.polygonOffsetUnits = this.polygonOffsetUnits;
  6511. material.alphaTest = this.alphaTest;
  6512. material.overdraw = this.overdraw;
  6513. material.visible = this.visible;
  6514. return material;
  6515. };
  6516. THREE.Material.prototype.dispose = function () {
  6517. this.dispatchEvent( { type: 'dispose' } );
  6518. };
  6519. THREE.MaterialIdCount = 0;
  6520. /**
  6521. * @author mrdoob / http://mrdoob.com/
  6522. * @author alteredq / http://alteredqualia.com/
  6523. *
  6524. * parameters = {
  6525. * color: <hex>,
  6526. * opacity: <float>,
  6527. *
  6528. * blending: THREE.NormalBlending,
  6529. * depthTest: <bool>,
  6530. * depthWrite: <bool>,
  6531. *
  6532. * linewidth: <float>,
  6533. * linecap: "round",
  6534. * linejoin: "round",
  6535. *
  6536. * vertexColors: <bool>
  6537. *
  6538. * fog: <bool>
  6539. * }
  6540. */
  6541. THREE.LineBasicMaterial = function ( parameters ) {
  6542. THREE.Material.call( this );
  6543. this.color = new THREE.Color( 0xffffff );
  6544. this.linewidth = 1;
  6545. this.linecap = 'round';
  6546. this.linejoin = 'round';
  6547. this.vertexColors = false;
  6548. this.fog = true;
  6549. this.setValues( parameters );
  6550. };
  6551. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6552. THREE.LineBasicMaterial.prototype.clone = function () {
  6553. var material = new THREE.LineBasicMaterial();
  6554. THREE.Material.prototype.clone.call( this, material );
  6555. material.color.copy( this.color );
  6556. material.linewidth = this.linewidth;
  6557. material.linecap = this.linecap;
  6558. material.linejoin = this.linejoin;
  6559. material.vertexColors = this.vertexColors;
  6560. material.fog = this.fog;
  6561. return material;
  6562. };
  6563. /**
  6564. * @author alteredq / http://alteredqualia.com/
  6565. *
  6566. * parameters = {
  6567. * color: <hex>,
  6568. * opacity: <float>,
  6569. *
  6570. * blending: THREE.NormalBlending,
  6571. * depthTest: <bool>,
  6572. * depthWrite: <bool>,
  6573. *
  6574. * linewidth: <float>,
  6575. *
  6576. * scale: <float>,
  6577. * dashSize: <float>,
  6578. * gapSize: <float>,
  6579. *
  6580. * vertexColors: <bool>
  6581. *
  6582. * fog: <bool>
  6583. * }
  6584. */
  6585. THREE.LineDashedMaterial = function ( parameters ) {
  6586. THREE.Material.call( this );
  6587. this.color = new THREE.Color( 0xffffff );
  6588. this.linewidth = 1;
  6589. this.scale = 1;
  6590. this.dashSize = 3;
  6591. this.gapSize = 1;
  6592. this.vertexColors = false;
  6593. this.fog = true;
  6594. this.setValues( parameters );
  6595. };
  6596. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  6597. THREE.LineDashedMaterial.prototype.clone = function () {
  6598. var material = new THREE.LineDashedMaterial();
  6599. THREE.Material.prototype.clone.call( this, material );
  6600. material.color.copy( this.color );
  6601. material.linewidth = this.linewidth;
  6602. material.scale = this.scale;
  6603. material.dashSize = this.dashSize;
  6604. material.gapSize = this.gapSize;
  6605. material.vertexColors = this.vertexColors;
  6606. material.fog = this.fog;
  6607. return material;
  6608. };
  6609. /**
  6610. * @author mrdoob / http://mrdoob.com/
  6611. * @author alteredq / http://alteredqualia.com/
  6612. *
  6613. * parameters = {
  6614. * color: <hex>,
  6615. * opacity: <float>,
  6616. * map: new THREE.Texture( <Image> ),
  6617. *
  6618. * lightMap: new THREE.Texture( <Image> ),
  6619. *
  6620. * specularMap: new THREE.Texture( <Image> ),
  6621. *
  6622. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6623. * combine: THREE.Multiply,
  6624. * reflectivity: <float>,
  6625. * refractionRatio: <float>,
  6626. *
  6627. * shading: THREE.SmoothShading,
  6628. * blending: THREE.NormalBlending,
  6629. * depthTest: <bool>,
  6630. * depthWrite: <bool>,
  6631. *
  6632. * wireframe: <boolean>,
  6633. * wireframeLinewidth: <float>,
  6634. *
  6635. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6636. *
  6637. * skinning: <bool>,
  6638. * morphTargets: <bool>,
  6639. *
  6640. * fog: <bool>
  6641. * }
  6642. */
  6643. THREE.MeshBasicMaterial = function ( parameters ) {
  6644. THREE.Material.call( this );
  6645. this.color = new THREE.Color( 0xffffff ); // emissive
  6646. this.map = null;
  6647. this.lightMap = null;
  6648. this.specularMap = null;
  6649. this.envMap = null;
  6650. this.combine = THREE.MultiplyOperation;
  6651. this.reflectivity = 1;
  6652. this.refractionRatio = 0.98;
  6653. this.fog = true;
  6654. this.shading = THREE.SmoothShading;
  6655. this.wireframe = false;
  6656. this.wireframeLinewidth = 1;
  6657. this.wireframeLinecap = 'round';
  6658. this.wireframeLinejoin = 'round';
  6659. this.vertexColors = THREE.NoColors;
  6660. this.skinning = false;
  6661. this.morphTargets = false;
  6662. this.setValues( parameters );
  6663. };
  6664. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6665. THREE.MeshBasicMaterial.prototype.clone = function () {
  6666. var material = new THREE.MeshBasicMaterial();
  6667. THREE.Material.prototype.clone.call( this, material );
  6668. material.color.copy( this.color );
  6669. material.map = this.map;
  6670. material.lightMap = this.lightMap;
  6671. material.specularMap = this.specularMap;
  6672. material.envMap = this.envMap;
  6673. material.combine = this.combine;
  6674. material.reflectivity = this.reflectivity;
  6675. material.refractionRatio = this.refractionRatio;
  6676. material.fog = this.fog;
  6677. material.shading = this.shading;
  6678. material.wireframe = this.wireframe;
  6679. material.wireframeLinewidth = this.wireframeLinewidth;
  6680. material.wireframeLinecap = this.wireframeLinecap;
  6681. material.wireframeLinejoin = this.wireframeLinejoin;
  6682. material.vertexColors = this.vertexColors;
  6683. material.skinning = this.skinning;
  6684. material.morphTargets = this.morphTargets;
  6685. return material;
  6686. };
  6687. /**
  6688. * @author mrdoob / http://mrdoob.com/
  6689. * @author alteredq / http://alteredqualia.com/
  6690. *
  6691. * parameters = {
  6692. * color: <hex>,
  6693. * ambient: <hex>,
  6694. * emissive: <hex>,
  6695. * opacity: <float>,
  6696. *
  6697. * map: new THREE.Texture( <Image> ),
  6698. *
  6699. * lightMap: new THREE.Texture( <Image> ),
  6700. *
  6701. * specularMap: new THREE.Texture( <Image> ),
  6702. *
  6703. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6704. * combine: THREE.Multiply,
  6705. * reflectivity: <float>,
  6706. * refractionRatio: <float>,
  6707. *
  6708. * shading: THREE.SmoothShading,
  6709. * blending: THREE.NormalBlending,
  6710. * depthTest: <bool>,
  6711. * depthWrite: <bool>,
  6712. *
  6713. * wireframe: <boolean>,
  6714. * wireframeLinewidth: <float>,
  6715. *
  6716. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6717. *
  6718. * skinning: <bool>,
  6719. * morphTargets: <bool>,
  6720. * morphNormals: <bool>,
  6721. *
  6722. * fog: <bool>
  6723. * }
  6724. */
  6725. THREE.MeshLambertMaterial = function ( parameters ) {
  6726. THREE.Material.call( this );
  6727. this.color = new THREE.Color( 0xffffff ); // diffuse
  6728. this.ambient = new THREE.Color( 0xffffff );
  6729. this.emissive = new THREE.Color( 0x000000 );
  6730. this.wrapAround = false;
  6731. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6732. this.map = null;
  6733. this.lightMap = null;
  6734. this.specularMap = null;
  6735. this.envMap = null;
  6736. this.combine = THREE.MultiplyOperation;
  6737. this.reflectivity = 1;
  6738. this.refractionRatio = 0.98;
  6739. this.fog = true;
  6740. this.shading = THREE.SmoothShading;
  6741. this.wireframe = false;
  6742. this.wireframeLinewidth = 1;
  6743. this.wireframeLinecap = 'round';
  6744. this.wireframeLinejoin = 'round';
  6745. this.vertexColors = THREE.NoColors;
  6746. this.skinning = false;
  6747. this.morphTargets = false;
  6748. this.morphNormals = false;
  6749. this.setValues( parameters );
  6750. };
  6751. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  6752. THREE.MeshLambertMaterial.prototype.clone = function () {
  6753. var material = new THREE.MeshLambertMaterial();
  6754. THREE.Material.prototype.clone.call( this, material );
  6755. material.color.copy( this.color );
  6756. material.ambient.copy( this.ambient );
  6757. material.emissive.copy( this.emissive );
  6758. material.wrapAround = this.wrapAround;
  6759. material.wrapRGB.copy( this.wrapRGB );
  6760. material.map = this.map;
  6761. material.lightMap = this.lightMap;
  6762. material.specularMap = this.specularMap;
  6763. material.envMap = this.envMap;
  6764. material.combine = this.combine;
  6765. material.reflectivity = this.reflectivity;
  6766. material.refractionRatio = this.refractionRatio;
  6767. material.fog = this.fog;
  6768. material.shading = this.shading;
  6769. material.wireframe = this.wireframe;
  6770. material.wireframeLinewidth = this.wireframeLinewidth;
  6771. material.wireframeLinecap = this.wireframeLinecap;
  6772. material.wireframeLinejoin = this.wireframeLinejoin;
  6773. material.vertexColors = this.vertexColors;
  6774. material.skinning = this.skinning;
  6775. material.morphTargets = this.morphTargets;
  6776. material.morphNormals = this.morphNormals;
  6777. return material;
  6778. };
  6779. /**
  6780. * @author mrdoob / http://mrdoob.com/
  6781. * @author alteredq / http://alteredqualia.com/
  6782. *
  6783. * parameters = {
  6784. * color: <hex>,
  6785. * ambient: <hex>,
  6786. * emissive: <hex>,
  6787. * specular: <hex>,
  6788. * shininess: <float>,
  6789. * opacity: <float>,
  6790. *
  6791. * map: new THREE.Texture( <Image> ),
  6792. *
  6793. * lightMap: new THREE.Texture( <Image> ),
  6794. *
  6795. * bumpMap: new THREE.Texture( <Image> ),
  6796. * bumpScale: <float>,
  6797. *
  6798. * normalMap: new THREE.Texture( <Image> ),
  6799. * normalScale: <Vector2>,
  6800. *
  6801. * specularMap: new THREE.Texture( <Image> ),
  6802. *
  6803. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6804. * combine: THREE.Multiply,
  6805. * reflectivity: <float>,
  6806. * refractionRatio: <float>,
  6807. *
  6808. * shading: THREE.SmoothShading,
  6809. * blending: THREE.NormalBlending,
  6810. * depthTest: <bool>,
  6811. * depthWrite: <bool>,
  6812. *
  6813. * wireframe: <boolean>,
  6814. * wireframeLinewidth: <float>,
  6815. *
  6816. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6817. *
  6818. * skinning: <bool>,
  6819. * morphTargets: <bool>,
  6820. * morphNormals: <bool>,
  6821. *
  6822. * fog: <bool>
  6823. * }
  6824. */
  6825. THREE.MeshPhongMaterial = function ( parameters ) {
  6826. THREE.Material.call( this );
  6827. this.color = new THREE.Color( 0xffffff ); // diffuse
  6828. this.ambient = new THREE.Color( 0xffffff );
  6829. this.emissive = new THREE.Color( 0x000000 );
  6830. this.specular = new THREE.Color( 0x111111 );
  6831. this.shininess = 30;
  6832. this.metal = false;
  6833. this.perPixel = true;
  6834. this.wrapAround = false;
  6835. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6836. this.map = null;
  6837. this.lightMap = null;
  6838. this.bumpMap = null;
  6839. this.bumpScale = 1;
  6840. this.normalMap = null;
  6841. this.normalScale = new THREE.Vector2( 1, 1 );
  6842. this.specularMap = null;
  6843. this.envMap = null;
  6844. this.combine = THREE.MultiplyOperation;
  6845. this.reflectivity = 1;
  6846. this.refractionRatio = 0.98;
  6847. this.fog = true;
  6848. this.shading = THREE.SmoothShading;
  6849. this.wireframe = false;
  6850. this.wireframeLinewidth = 1;
  6851. this.wireframeLinecap = 'round';
  6852. this.wireframeLinejoin = 'round';
  6853. this.vertexColors = THREE.NoColors;
  6854. this.skinning = false;
  6855. this.morphTargets = false;
  6856. this.morphNormals = false;
  6857. this.setValues( parameters );
  6858. };
  6859. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  6860. THREE.MeshPhongMaterial.prototype.clone = function () {
  6861. var material = new THREE.MeshPhongMaterial();
  6862. THREE.Material.prototype.clone.call( this, material );
  6863. material.color.copy( this.color );
  6864. material.ambient.copy( this.ambient );
  6865. material.emissive.copy( this.emissive );
  6866. material.specular.copy( this.specular );
  6867. material.shininess = this.shininess;
  6868. material.metal = this.metal;
  6869. material.perPixel = this.perPixel;
  6870. material.wrapAround = this.wrapAround;
  6871. material.wrapRGB.copy( this.wrapRGB );
  6872. material.map = this.map;
  6873. material.lightMap = this.lightMap;
  6874. material.bumpMap = this.bumpMap;
  6875. material.bumpScale = this.bumpScale;
  6876. material.normalMap = this.normalMap;
  6877. material.normalScale.copy( this.normalScale );
  6878. material.specularMap = this.specularMap;
  6879. material.envMap = this.envMap;
  6880. material.combine = this.combine;
  6881. material.reflectivity = this.reflectivity;
  6882. material.refractionRatio = this.refractionRatio;
  6883. material.fog = this.fog;
  6884. material.shading = this.shading;
  6885. material.wireframe = this.wireframe;
  6886. material.wireframeLinewidth = this.wireframeLinewidth;
  6887. material.wireframeLinecap = this.wireframeLinecap;
  6888. material.wireframeLinejoin = this.wireframeLinejoin;
  6889. material.vertexColors = this.vertexColors;
  6890. material.skinning = this.skinning;
  6891. material.morphTargets = this.morphTargets;
  6892. material.morphNormals = this.morphNormals;
  6893. return material;
  6894. };
  6895. /**
  6896. * @author mrdoob / http://mrdoob.com/
  6897. * @author alteredq / http://alteredqualia.com/
  6898. *
  6899. * parameters = {
  6900. * opacity: <float>,
  6901. *
  6902. * blending: THREE.NormalBlending,
  6903. * depthTest: <bool>,
  6904. * depthWrite: <bool>,
  6905. *
  6906. * wireframe: <boolean>,
  6907. * wireframeLinewidth: <float>
  6908. * }
  6909. */
  6910. THREE.MeshDepthMaterial = function ( parameters ) {
  6911. THREE.Material.call( this );
  6912. this.wireframe = false;
  6913. this.wireframeLinewidth = 1;
  6914. this.setValues( parameters );
  6915. };
  6916. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  6917. THREE.MeshDepthMaterial.prototype.clone = function () {
  6918. var material = new THREE.LineBasicMaterial();
  6919. THREE.Material.prototype.clone.call( this, material );
  6920. material.wireframe = this.wireframe;
  6921. material.wireframeLinewidth = this.wireframeLinewidth;
  6922. return material;
  6923. };
  6924. /**
  6925. * @author mrdoob / http://mrdoob.com/
  6926. *
  6927. * parameters = {
  6928. * opacity: <float>,
  6929. *
  6930. * shading: THREE.FlatShading,
  6931. * blending: THREE.NormalBlending,
  6932. * depthTest: <bool>,
  6933. * depthWrite: <bool>,
  6934. *
  6935. * wireframe: <boolean>,
  6936. * wireframeLinewidth: <float>
  6937. * }
  6938. */
  6939. THREE.MeshNormalMaterial = function ( parameters ) {
  6940. THREE.Material.call( this, parameters );
  6941. this.shading = THREE.FlatShading;
  6942. this.wireframe = false;
  6943. this.wireframeLinewidth = 1;
  6944. this.setValues( parameters );
  6945. };
  6946. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  6947. THREE.MeshNormalMaterial.prototype.clone = function () {
  6948. var material = new THREE.MeshNormalMaterial();
  6949. THREE.Material.prototype.clone.call( this, material );
  6950. material.shading = this.shading;
  6951. material.wireframe = this.wireframe;
  6952. material.wireframeLinewidth = this.wireframeLinewidth;
  6953. return material;
  6954. };
  6955. /**
  6956. * @author mrdoob / http://mrdoob.com/
  6957. */
  6958. THREE.MeshFaceMaterial = function ( materials ) {
  6959. this.materials = materials instanceof Array ? materials : [];
  6960. };
  6961. THREE.MeshFaceMaterial.prototype.clone = function () {
  6962. return new THREE.MeshFaceMaterial( this.materials.slice( 0 ) );
  6963. };
  6964. /**
  6965. * @author mrdoob / http://mrdoob.com/
  6966. * @author alteredq / http://alteredqualia.com/
  6967. *
  6968. * parameters = {
  6969. * color: <hex>,
  6970. * opacity: <float>,
  6971. * map: new THREE.Texture( <Image> ),
  6972. *
  6973. * size: <float>,
  6974. *
  6975. * blending: THREE.NormalBlending,
  6976. * depthTest: <bool>,
  6977. * depthWrite: <bool>,
  6978. *
  6979. * vertexColors: <bool>,
  6980. *
  6981. * fog: <bool>
  6982. * }
  6983. */
  6984. THREE.ParticleBasicMaterial = function ( parameters ) {
  6985. THREE.Material.call( this );
  6986. this.color = new THREE.Color( 0xffffff );
  6987. this.map = null;
  6988. this.size = 1;
  6989. this.sizeAttenuation = true;
  6990. this.vertexColors = false;
  6991. this.fog = true;
  6992. this.setValues( parameters );
  6993. };
  6994. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6995. THREE.ParticleBasicMaterial.prototype.clone = function () {
  6996. var material = new THREE.ParticleBasicMaterial();
  6997. THREE.Material.prototype.clone.call( this, material );
  6998. material.color.copy( this.color );
  6999. material.map = this.map;
  7000. material.size = this.size;
  7001. material.sizeAttenuation = this.sizeAttenuation;
  7002. material.vertexColors = this.vertexColors;
  7003. material.fog = this.fog;
  7004. return material;
  7005. };
  7006. /**
  7007. * @author mrdoob / http://mrdoob.com/
  7008. *
  7009. * parameters = {
  7010. * color: <hex>,
  7011. * program: <function>,
  7012. * opacity: <float>,
  7013. * blending: THREE.NormalBlending
  7014. * }
  7015. */
  7016. THREE.ParticleCanvasMaterial = function ( parameters ) {
  7017. THREE.Material.call( this );
  7018. this.color = new THREE.Color( 0xffffff );
  7019. this.program = function ( context, color ) {};
  7020. this.setValues( parameters );
  7021. };
  7022. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  7023. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  7024. var material = new THREE.ParticleCanvasMaterial();
  7025. THREE.Material.prototype.clone.call( this, material );
  7026. material.color.copy( this.color );
  7027. material.program = this.program;
  7028. return material;
  7029. };
  7030. /**
  7031. * @author alteredq / http://alteredqualia.com/
  7032. *
  7033. * parameters = {
  7034. * fragmentShader: <string>,
  7035. * vertexShader: <string>,
  7036. *
  7037. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  7038. *
  7039. * defines: { "label" : "value" },
  7040. *
  7041. * shading: THREE.SmoothShading,
  7042. * blending: THREE.NormalBlending,
  7043. * depthTest: <bool>,
  7044. * depthWrite: <bool>,
  7045. *
  7046. * wireframe: <boolean>,
  7047. * wireframeLinewidth: <float>,
  7048. *
  7049. * lights: <bool>,
  7050. *
  7051. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7052. *
  7053. * skinning: <bool>,
  7054. * morphTargets: <bool>,
  7055. * morphNormals: <bool>,
  7056. *
  7057. * fog: <bool>
  7058. * }
  7059. */
  7060. THREE.ShaderMaterial = function ( parameters ) {
  7061. THREE.Material.call( this );
  7062. this.fragmentShader = "void main() {}";
  7063. this.vertexShader = "void main() {}";
  7064. this.uniforms = {};
  7065. this.defines = {};
  7066. this.attributes = null;
  7067. this.shading = THREE.SmoothShading;
  7068. this.wireframe = false;
  7069. this.wireframeLinewidth = 1;
  7070. this.fog = false; // set to use scene fog
  7071. this.lights = false; // set to use scene lights
  7072. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  7073. this.skinning = false; // set to use skinning attribute streams
  7074. this.morphTargets = false; // set to use morph targets
  7075. this.morphNormals = false; // set to use morph normals
  7076. this.setValues( parameters );
  7077. };
  7078. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  7079. THREE.ShaderMaterial.prototype.clone = function () {
  7080. var material = new THREE.ShaderMaterial();
  7081. THREE.Material.prototype.clone.call( this, material );
  7082. material.fragmentShader = this.fragmentShader;
  7083. material.vertexShader = this.vertexShader;
  7084. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  7085. material.attributes = this.attributes;
  7086. material.defines = this.defines;
  7087. material.shading = this.shading;
  7088. material.wireframe = this.wireframe;
  7089. material.wireframeLinewidth = this.wireframeLinewidth;
  7090. material.fog = this.fog;
  7091. material.lights = this.lights;
  7092. material.vertexColors = this.vertexColors;
  7093. material.skinning = this.skinning;
  7094. material.morphTargets = this.morphTargets;
  7095. material.morphNormals = this.morphNormals;
  7096. return material;
  7097. };
  7098. /**
  7099. * @author alteredq / http://alteredqualia.com/
  7100. *
  7101. * parameters = {
  7102. * color: <hex>,
  7103. * opacity: <float>,
  7104. * map: new THREE.Texture( <Image> ),
  7105. *
  7106. * blending: THREE.NormalBlending,
  7107. * depthTest: <bool>,
  7108. * depthWrite: <bool>,
  7109. *
  7110. * useScreenCoordinates: <bool>,
  7111. * sizeAttenuation: <bool>,
  7112. * scaleByViewport: <bool>,
  7113. * alignment: THREE.SpriteAlignment.center,
  7114. *
  7115. * uvOffset: new THREE.Vector2(),
  7116. * uvScale: new THREE.Vector2(),
  7117. *
  7118. * fog: <bool>
  7119. * }
  7120. */
  7121. THREE.SpriteMaterial = function ( parameters ) {
  7122. THREE.Material.call( this );
  7123. // defaults
  7124. this.color = new THREE.Color( 0xffffff );
  7125. this.map = new THREE.Texture();
  7126. this.useScreenCoordinates = true;
  7127. this.depthTest = !this.useScreenCoordinates;
  7128. this.sizeAttenuation = !this.useScreenCoordinates;
  7129. this.scaleByViewport = !this.sizeAttenuation;
  7130. this.alignment = THREE.SpriteAlignment.center.clone();
  7131. this.fog = false;
  7132. this.uvOffset = new THREE.Vector2( 0, 0 );
  7133. this.uvScale = new THREE.Vector2( 1, 1 );
  7134. // set parameters
  7135. this.setValues( parameters );
  7136. // override coupled defaults if not specified explicitly by parameters
  7137. parameters = parameters || {};
  7138. if ( parameters.depthTest === undefined ) this.depthTest = !this.useScreenCoordinates;
  7139. if ( parameters.sizeAttenuation === undefined ) this.sizeAttenuation = !this.useScreenCoordinates;
  7140. if ( parameters.scaleByViewport === undefined ) this.scaleByViewport = !this.sizeAttenuation;
  7141. };
  7142. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  7143. THREE.SpriteMaterial.prototype.clone = function () {
  7144. var material = new THREE.SpriteMaterial();
  7145. THREE.Material.prototype.clone.call( this, material );
  7146. material.color.copy( this.color );
  7147. material.map = this.map;
  7148. material.useScreenCoordinates = this.useScreenCoordinates;
  7149. material.sizeAttenuation = this.sizeAttenuation;
  7150. material.scaleByViewport = this.scaleByViewport;
  7151. material.alignment.copy( this.alignment );
  7152. material.uvOffset.copy( this.uvOffset );
  7153. material.uvScale.copy( this.uvScale );
  7154. material.fog = this.fog;
  7155. return material;
  7156. };
  7157. // Alignment enums
  7158. THREE.SpriteAlignment = {};
  7159. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  7160. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  7161. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  7162. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  7163. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  7164. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  7165. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  7166. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  7167. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  7168. /**
  7169. * @author mrdoob / http://mrdoob.com/
  7170. * @author alteredq / http://alteredqualia.com/
  7171. * @author szimek / https://github.com/szimek/
  7172. */
  7173. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  7174. THREE.EventDispatcher.call( this );
  7175. this.id = THREE.TextureIdCount ++;
  7176. this.name = '';
  7177. this.image = image;
  7178. this.mipmaps = [];
  7179. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  7180. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  7181. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  7182. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  7183. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  7184. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  7185. this.format = format !== undefined ? format : THREE.RGBAFormat;
  7186. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  7187. this.offset = new THREE.Vector2( 0, 0 );
  7188. this.repeat = new THREE.Vector2( 1, 1 );
  7189. this.generateMipmaps = true;
  7190. this.premultiplyAlpha = false;
  7191. this.flipY = true;
  7192. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  7193. this.needsUpdate = false;
  7194. this.onUpdate = null;
  7195. };
  7196. THREE.Texture.prototype = {
  7197. constructor: THREE.Texture,
  7198. clone: function ( texture ) {
  7199. if ( texture === undefined ) texture = new THREE.Texture();
  7200. texture.image = this.image;
  7201. texture.mipmaps = this.mipmaps.slice(0);
  7202. texture.mapping = this.mapping;
  7203. texture.wrapS = this.wrapS;
  7204. texture.wrapT = this.wrapT;
  7205. texture.magFilter = this.magFilter;
  7206. texture.minFilter = this.minFilter;
  7207. texture.anisotropy = this.anisotropy;
  7208. texture.format = this.format;
  7209. texture.type = this.type;
  7210. texture.offset.copy( this.offset );
  7211. texture.repeat.copy( this.repeat );
  7212. texture.generateMipmaps = this.generateMipmaps;
  7213. texture.premultiplyAlpha = this.premultiplyAlpha;
  7214. texture.flipY = this.flipY;
  7215. texture.unpackAlignment = this.unpackAlignment;
  7216. return texture;
  7217. },
  7218. dispose: function () {
  7219. this.dispatchEvent( { type: 'dispose' } );
  7220. }
  7221. };
  7222. THREE.TextureIdCount = 0;
  7223. /**
  7224. * @author alteredq / http://alteredqualia.com/
  7225. */
  7226. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7227. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7228. this.image = { width: width, height: height };
  7229. this.mipmaps = mipmaps;
  7230. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  7231. };
  7232. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  7233. THREE.CompressedTexture.prototype.clone = function () {
  7234. var texture = new THREE.CompressedTexture();
  7235. THREE.Texture.prototype.clone.call( this, texture );
  7236. return texture;
  7237. };
  7238. /**
  7239. * @author alteredq / http://alteredqualia.com/
  7240. */
  7241. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7242. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7243. this.image = { data: data, width: width, height: height };
  7244. };
  7245. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  7246. THREE.DataTexture.prototype.clone = function () {
  7247. var texture = new THREE.DataTexture();
  7248. THREE.Texture.prototype.clone.call( this, texture );
  7249. return texture;
  7250. };
  7251. /**
  7252. * @author mrdoob / http://mrdoob.com/
  7253. */
  7254. THREE.Particle = function ( material ) {
  7255. THREE.Object3D.call( this );
  7256. this.material = material;
  7257. };
  7258. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  7259. THREE.Particle.prototype.clone = function ( object ) {
  7260. if ( object === undefined ) object = new THREE.Particle( this.material );
  7261. THREE.Object3D.prototype.clone.call( this, object );
  7262. return object;
  7263. };
  7264. /**
  7265. * @author alteredq / http://alteredqualia.com/
  7266. */
  7267. THREE.ParticleSystem = function ( geometry, material ) {
  7268. THREE.Object3D.call( this );
  7269. this.geometry = geometry;
  7270. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  7271. this.sortParticles = false;
  7272. if ( this.geometry ) {
  7273. // calc bound radius
  7274. if( this.geometry.boundingSphere === null ) {
  7275. this.geometry.computeBoundingSphere();
  7276. }
  7277. }
  7278. this.frustumCulled = false;
  7279. };
  7280. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  7281. THREE.ParticleSystem.prototype.clone = function ( object ) {
  7282. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  7283. object.sortParticles = this.sortParticles;
  7284. THREE.Object3D.prototype.clone.call( this, object );
  7285. return object;
  7286. };
  7287. /**
  7288. * @author mrdoob / http://mrdoob.com/
  7289. */
  7290. THREE.Line = function ( geometry, material, type ) {
  7291. THREE.Object3D.call( this );
  7292. this.geometry = geometry;
  7293. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  7294. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  7295. if ( this.geometry ) {
  7296. if ( ! this.geometry.boundingSphere ) {
  7297. this.geometry.computeBoundingSphere();
  7298. }
  7299. }
  7300. };
  7301. THREE.LineStrip = 0;
  7302. THREE.LinePieces = 1;
  7303. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  7304. THREE.Line.prototype.clone = function ( object ) {
  7305. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  7306. THREE.Object3D.prototype.clone.call( this, object );
  7307. return object;
  7308. };
  7309. /**
  7310. * @author mrdoob / http://mrdoob.com/
  7311. * @author alteredq / http://alteredqualia.com/
  7312. * @author mikael emtinger / http://gomo.se/
  7313. * @author jonobr1 / http://jonobr1.com/
  7314. */
  7315. THREE.Mesh = function ( geometry, material ) {
  7316. THREE.Object3D.call( this );
  7317. this.geometry = geometry;
  7318. this.material = ( material !== undefined ) ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  7319. if ( this.geometry !== undefined ) {
  7320. if ( this.geometry.boundingSphere === null ) {
  7321. this.geometry.computeBoundingSphere();
  7322. }
  7323. this.updateMorphTargets();
  7324. }
  7325. };
  7326. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  7327. THREE.Mesh.prototype.updateMorphTargets = function () {
  7328. if ( this.geometry.morphTargets.length > 0 ) {
  7329. this.morphTargetBase = -1;
  7330. this.morphTargetForcedOrder = [];
  7331. this.morphTargetInfluences = [];
  7332. this.morphTargetDictionary = {};
  7333. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  7334. this.morphTargetInfluences.push( 0 );
  7335. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  7336. }
  7337. }
  7338. };
  7339. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  7340. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  7341. return this.morphTargetDictionary[ name ];
  7342. }
  7343. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  7344. return 0;
  7345. };
  7346. THREE.Mesh.prototype.clone = function ( object ) {
  7347. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  7348. THREE.Object3D.prototype.clone.call( this, object );
  7349. return object;
  7350. };
  7351. /**
  7352. * @author mikael emtinger / http://gomo.se/
  7353. * @author alteredq / http://alteredqualia.com/
  7354. */
  7355. THREE.Bone = function( belongsToSkin ) {
  7356. THREE.Object3D.call( this );
  7357. this.skin = belongsToSkin;
  7358. this.skinMatrix = new THREE.Matrix4();
  7359. };
  7360. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  7361. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  7362. // update local
  7363. if ( this.matrixAutoUpdate ) {
  7364. forceUpdate |= this.updateMatrix();
  7365. }
  7366. // update skin matrix
  7367. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  7368. if( parentSkinMatrix ) {
  7369. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  7370. } else {
  7371. this.skinMatrix.copy( this.matrix );
  7372. }
  7373. this.matrixWorldNeedsUpdate = false;
  7374. forceUpdate = true;
  7375. }
  7376. // update children
  7377. var child, i, l = this.children.length;
  7378. for ( i = 0; i < l; i ++ ) {
  7379. this.children[ i ].update( this.skinMatrix, forceUpdate );
  7380. }
  7381. };
  7382. /**
  7383. * @author mikael emtinger / http://gomo.se/
  7384. * @author alteredq / http://alteredqualia.com/
  7385. */
  7386. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  7387. THREE.Mesh.call( this, geometry, material );
  7388. //
  7389. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  7390. // init bones
  7391. this.identityMatrix = new THREE.Matrix4();
  7392. this.bones = [];
  7393. this.boneMatrices = [];
  7394. var b, bone, gbone, p, q, s;
  7395. if ( this.geometry && this.geometry.bones !== undefined ) {
  7396. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  7397. gbone = this.geometry.bones[ b ];
  7398. p = gbone.pos;
  7399. q = gbone.rotq;
  7400. s = gbone.scl;
  7401. bone = this.addBone();
  7402. bone.name = gbone.name;
  7403. bone.position.set( p[0], p[1], p[2] );
  7404. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  7405. bone.useQuaternion = true;
  7406. if ( s !== undefined ) {
  7407. bone.scale.set( s[0], s[1], s[2] );
  7408. } else {
  7409. bone.scale.set( 1, 1, 1 );
  7410. }
  7411. }
  7412. for ( b = 0; b < this.bones.length; b ++ ) {
  7413. gbone = this.geometry.bones[ b ];
  7414. bone = this.bones[ b ];
  7415. if ( gbone.parent === -1 ) {
  7416. this.add( bone );
  7417. } else {
  7418. this.bones[ gbone.parent ].add( bone );
  7419. }
  7420. }
  7421. //
  7422. var nBones = this.bones.length;
  7423. if ( this.useVertexTexture ) {
  7424. // layout (1 matrix = 4 pixels)
  7425. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  7426. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  7427. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  7428. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  7429. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  7430. var size;
  7431. if ( nBones > 256 )
  7432. size = 64;
  7433. else if ( nBones > 64 )
  7434. size = 32;
  7435. else if ( nBones > 16 )
  7436. size = 16;
  7437. else
  7438. size = 8;
  7439. this.boneTextureWidth = size;
  7440. this.boneTextureHeight = size;
  7441. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  7442. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  7443. this.boneTexture.minFilter = THREE.NearestFilter;
  7444. this.boneTexture.magFilter = THREE.NearestFilter;
  7445. this.boneTexture.generateMipmaps = false;
  7446. this.boneTexture.flipY = false;
  7447. } else {
  7448. this.boneMatrices = new Float32Array( 16 * nBones );
  7449. }
  7450. this.pose();
  7451. }
  7452. };
  7453. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  7454. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  7455. if ( bone === undefined ) {
  7456. bone = new THREE.Bone( this );
  7457. }
  7458. this.bones.push( bone );
  7459. return bone;
  7460. };
  7461. THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
  7462. this.matrixAutoUpdate && this.updateMatrix();
  7463. // update matrixWorld
  7464. if ( this.matrixWorldNeedsUpdate || force ) {
  7465. if ( this.parent ) {
  7466. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  7467. } else {
  7468. this.matrixWorld.copy( this.matrix );
  7469. }
  7470. this.matrixWorldNeedsUpdate = false;
  7471. force = true;
  7472. }
  7473. // update children
  7474. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  7475. var child = this.children[ i ];
  7476. if ( child instanceof THREE.Bone ) {
  7477. child.update( this.identityMatrix, false );
  7478. } else {
  7479. child.updateMatrixWorld( true );
  7480. }
  7481. }
  7482. // make a snapshot of the bones' rest position
  7483. if ( this.boneInverses == undefined ) {
  7484. this.boneInverses = [];
  7485. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7486. var inverse = new THREE.Matrix4();
  7487. inverse.getInverse( this.bones[ b ].skinMatrix );
  7488. this.boneInverses.push( inverse );
  7489. }
  7490. }
  7491. // flatten bone matrices to array
  7492. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7493. // compute the offset between the current and the original transform;
  7494. //TODO: we could get rid of this multiplication step if the skinMatrix
  7495. // was already representing the offset; however, this requires some
  7496. // major changes to the animation system
  7497. THREE.SkinnedMesh.offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  7498. THREE.SkinnedMesh.offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  7499. }
  7500. if ( this.useVertexTexture ) {
  7501. this.boneTexture.needsUpdate = true;
  7502. }
  7503. };
  7504. THREE.SkinnedMesh.prototype.pose = function () {
  7505. this.updateMatrixWorld( true );
  7506. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  7507. // normalize weights
  7508. var sw = this.geometry.skinWeights[ i ];
  7509. var scale = 1.0 / sw.lengthManhattan();
  7510. if ( scale !== Infinity ) {
  7511. sw.multiplyScalar( scale );
  7512. } else {
  7513. sw.set( 1 ); // this will be normalized by the shader anyway
  7514. }
  7515. }
  7516. };
  7517. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  7518. if ( object === undefined ) object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  7519. THREE.Mesh.prototype.clone.call( this, object );
  7520. return object;
  7521. };
  7522. THREE.SkinnedMesh.offsetMatrix = new THREE.Matrix4();
  7523. /**
  7524. * @author alteredq / http://alteredqualia.com/
  7525. */
  7526. THREE.MorphAnimMesh = function ( geometry, material ) {
  7527. THREE.Mesh.call( this, geometry, material );
  7528. // API
  7529. this.duration = 1000; // milliseconds
  7530. this.mirroredLoop = false;
  7531. this.time = 0;
  7532. // internals
  7533. this.lastKeyframe = 0;
  7534. this.currentKeyframe = 0;
  7535. this.direction = 1;
  7536. this.directionBackwards = false;
  7537. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  7538. };
  7539. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  7540. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  7541. this.startKeyframe = start;
  7542. this.endKeyframe = end;
  7543. this.length = this.endKeyframe - this.startKeyframe + 1;
  7544. };
  7545. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  7546. this.direction = 1;
  7547. this.directionBackwards = false;
  7548. };
  7549. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  7550. this.direction = -1;
  7551. this.directionBackwards = true;
  7552. };
  7553. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  7554. var geometry = this.geometry;
  7555. if ( ! geometry.animations ) geometry.animations = {};
  7556. var firstAnimation, animations = geometry.animations;
  7557. var pattern = /([a-z]+)(\d+)/;
  7558. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  7559. var morph = geometry.morphTargets[ i ];
  7560. var parts = morph.name.match( pattern );
  7561. if ( parts && parts.length > 1 ) {
  7562. var label = parts[ 1 ];
  7563. var num = parts[ 2 ];
  7564. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  7565. var animation = animations[ label ];
  7566. if ( i < animation.start ) animation.start = i;
  7567. if ( i > animation.end ) animation.end = i;
  7568. if ( ! firstAnimation ) firstAnimation = label;
  7569. }
  7570. }
  7571. geometry.firstAnimation = firstAnimation;
  7572. };
  7573. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  7574. if ( ! this.geometry.animations ) this.geometry.animations = {};
  7575. this.geometry.animations[ label ] = { start: start, end: end };
  7576. };
  7577. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  7578. var animation = this.geometry.animations[ label ];
  7579. if ( animation ) {
  7580. this.setFrameRange( animation.start, animation.end );
  7581. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  7582. this.time = 0;
  7583. } else {
  7584. console.warn( "animation[" + label + "] undefined" );
  7585. }
  7586. };
  7587. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  7588. var frameTime = this.duration / this.length;
  7589. this.time += this.direction * delta;
  7590. if ( this.mirroredLoop ) {
  7591. if ( this.time > this.duration || this.time < 0 ) {
  7592. this.direction *= -1;
  7593. if ( this.time > this.duration ) {
  7594. this.time = this.duration;
  7595. this.directionBackwards = true;
  7596. }
  7597. if ( this.time < 0 ) {
  7598. this.time = 0;
  7599. this.directionBackwards = false;
  7600. }
  7601. }
  7602. } else {
  7603. this.time = this.time % this.duration;
  7604. if ( this.time < 0 ) this.time += this.duration;
  7605. }
  7606. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  7607. if ( keyframe !== this.currentKeyframe ) {
  7608. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  7609. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  7610. this.morphTargetInfluences[ keyframe ] = 0;
  7611. this.lastKeyframe = this.currentKeyframe;
  7612. this.currentKeyframe = keyframe;
  7613. }
  7614. var mix = ( this.time % frameTime ) / frameTime;
  7615. if ( this.directionBackwards ) {
  7616. mix = 1 - mix;
  7617. }
  7618. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  7619. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  7620. };
  7621. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  7622. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  7623. object.duration = this.duration;
  7624. object.mirroredLoop = this.mirroredLoop;
  7625. object.time = this.time;
  7626. object.lastKeyframe = this.lastKeyframe;
  7627. object.currentKeyframe = this.currentKeyframe;
  7628. object.direction = this.direction;
  7629. object.directionBackwards = this.directionBackwards;
  7630. THREE.Mesh.prototype.clone.call( this, object );
  7631. return object;
  7632. };
  7633. /**
  7634. * @author alteredq / http://alteredqualia.com/
  7635. */
  7636. THREE.Ribbon = function ( geometry, material ) {
  7637. THREE.Object3D.call( this );
  7638. this.geometry = geometry;
  7639. this.material = material;
  7640. };
  7641. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  7642. THREE.Ribbon.prototype.clone = function ( object ) {
  7643. if ( object === undefined ) object = new THREE.Ribbon( this.geometry, this.material );
  7644. THREE.Object3D.prototype.clone.call( this, object );
  7645. return object;
  7646. };
  7647. /**
  7648. * @author mikael emtinger / http://gomo.se/
  7649. * @author alteredq / http://alteredqualia.com/
  7650. * @author mrdoob / http://mrdoob.com/
  7651. */
  7652. THREE.LOD = function () {
  7653. THREE.Object3D.call( this );
  7654. this.LODs = [];
  7655. };
  7656. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  7657. THREE.LOD.prototype.addLevel = function ( object3D, visibleAtDistance ) {
  7658. if ( visibleAtDistance === undefined ) {
  7659. visibleAtDistance = 0;
  7660. }
  7661. visibleAtDistance = Math.abs( visibleAtDistance );
  7662. for ( var l = 0; l < this.LODs.length; l ++ ) {
  7663. if ( visibleAtDistance < this.LODs[ l ].visibleAtDistance ) {
  7664. break;
  7665. }
  7666. }
  7667. this.LODs.splice( l, 0, { visibleAtDistance: visibleAtDistance, object3D: object3D } );
  7668. this.add( object3D );
  7669. };
  7670. THREE.LOD.prototype.update = function ( camera ) {
  7671. if ( this.LODs.length > 1 ) {
  7672. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  7673. var inverse = camera.matrixWorldInverse;
  7674. var distance = -( inverse.elements[2] * this.matrixWorld.elements[12] + inverse.elements[6] * this.matrixWorld.elements[13] + inverse.elements[10] * this.matrixWorld.elements[14] + inverse.elements[14] );
  7675. this.LODs[ 0 ].object3D.visible = true;
  7676. for ( var l = 1; l < this.LODs.length; l ++ ) {
  7677. if( distance >= this.LODs[ l ].visibleAtDistance ) {
  7678. this.LODs[ l - 1 ].object3D.visible = false;
  7679. this.LODs[ l ].object3D.visible = true;
  7680. } else {
  7681. break;
  7682. }
  7683. }
  7684. for( ; l < this.LODs.length; l ++ ) {
  7685. this.LODs[ l ].object3D.visible = false;
  7686. }
  7687. }
  7688. };
  7689. THREE.LOD.prototype.clone = function () {
  7690. // TODO
  7691. };
  7692. /**
  7693. * @author mikael emtinger / http://gomo.se/
  7694. * @author alteredq / http://alteredqualia.com/
  7695. */
  7696. THREE.Sprite = function ( material ) {
  7697. THREE.Object3D.call( this );
  7698. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  7699. this.rotation3d = this.rotation;
  7700. this.rotation = 0;
  7701. };
  7702. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  7703. /*
  7704. * Custom update matrix
  7705. */
  7706. THREE.Sprite.prototype.updateMatrix = function () {
  7707. this.matrix.setPosition( this.position );
  7708. this.rotation3d.set( 0, 0, this.rotation );
  7709. this.matrix.setRotationFromEuler( this.rotation3d );
  7710. if ( this.scale.x !== 1 || this.scale.y !== 1 ) {
  7711. this.matrix.scale( this.scale );
  7712. }
  7713. this.matrixWorldNeedsUpdate = true;
  7714. };
  7715. THREE.Sprite.prototype.clone = function ( object ) {
  7716. if ( object === undefined ) object = new THREE.Sprite( this.material );
  7717. THREE.Object3D.prototype.clone.call( this, object );
  7718. return object;
  7719. };
  7720. /**
  7721. * @author mrdoob / http://mrdoob.com/
  7722. */
  7723. THREE.Scene = function () {
  7724. THREE.Object3D.call( this );
  7725. this.fog = null;
  7726. this.overrideMaterial = null;
  7727. this.matrixAutoUpdate = false;
  7728. this.__objects = [];
  7729. this.__lights = [];
  7730. this.__objectsAdded = [];
  7731. this.__objectsRemoved = [];
  7732. };
  7733. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  7734. THREE.Scene.prototype.__addObject = function ( object ) {
  7735. if ( object instanceof THREE.Light ) {
  7736. if ( this.__lights.indexOf( object ) === - 1 ) {
  7737. this.__lights.push( object );
  7738. }
  7739. if ( object.target && object.target.parent === undefined ) {
  7740. this.add( object.target );
  7741. }
  7742. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  7743. if ( this.__objects.indexOf( object ) === - 1 ) {
  7744. this.__objects.push( object );
  7745. this.__objectsAdded.push( object );
  7746. // check if previously removed
  7747. var i = this.__objectsRemoved.indexOf( object );
  7748. if ( i !== -1 ) {
  7749. this.__objectsRemoved.splice( i, 1 );
  7750. }
  7751. }
  7752. }
  7753. for ( var c = 0; c < object.children.length; c ++ ) {
  7754. this.__addObject( object.children[ c ] );
  7755. }
  7756. };
  7757. THREE.Scene.prototype.__removeObject = function ( object ) {
  7758. if ( object instanceof THREE.Light ) {
  7759. var i = this.__lights.indexOf( object );
  7760. if ( i !== -1 ) {
  7761. this.__lights.splice( i, 1 );
  7762. }
  7763. } else if ( !( object instanceof THREE.Camera ) ) {
  7764. var i = this.__objects.indexOf( object );
  7765. if( i !== -1 ) {
  7766. this.__objects.splice( i, 1 );
  7767. this.__objectsRemoved.push( object );
  7768. // check if previously added
  7769. var ai = this.__objectsAdded.indexOf( object );
  7770. if ( ai !== -1 ) {
  7771. this.__objectsAdded.splice( ai, 1 );
  7772. }
  7773. }
  7774. }
  7775. for ( var c = 0; c < object.children.length; c ++ ) {
  7776. this.__removeObject( object.children[ c ] );
  7777. }
  7778. };
  7779. /**
  7780. * @author mrdoob / http://mrdoob.com/
  7781. * @author alteredq / http://alteredqualia.com/
  7782. */
  7783. THREE.Fog = function ( hex, near, far ) {
  7784. this.name = '';
  7785. this.color = new THREE.Color( hex );
  7786. this.near = ( near !== undefined ) ? near : 1;
  7787. this.far = ( far !== undefined ) ? far : 1000;
  7788. };
  7789. THREE.Fog.prototype.clone = function () {
  7790. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  7791. };
  7792. /**
  7793. * @author mrdoob / http://mrdoob.com/
  7794. * @author alteredq / http://alteredqualia.com/
  7795. */
  7796. THREE.FogExp2 = function ( hex, density ) {
  7797. this.name = '';
  7798. this.color = new THREE.Color( hex );
  7799. this.density = ( density !== undefined ) ? density : 0.00025;
  7800. };
  7801. THREE.FogExp2.prototype.clone = function () {
  7802. return new THREE.FogExp2( this.color.getHex(), this.density );
  7803. };
  7804. /**
  7805. * @author mrdoob / http://mrdoob.com/
  7806. */
  7807. THREE.CanvasRenderer = function ( parameters ) {
  7808. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  7809. parameters = parameters || {};
  7810. var _this = this,
  7811. _renderData, _elements, _lights,
  7812. _projector = new THREE.Projector(),
  7813. _canvas = parameters.canvas !== undefined
  7814. ? parameters.canvas
  7815. : document.createElement( 'canvas' ),
  7816. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  7817. _context = _canvas.getContext( '2d' ),
  7818. _clearColor = new THREE.Color( 0x000000 ),
  7819. _clearOpacity = 0,
  7820. _contextGlobalAlpha = 1,
  7821. _contextGlobalCompositeOperation = 0,
  7822. _contextStrokeStyle = null,
  7823. _contextFillStyle = null,
  7824. _contextLineWidth = null,
  7825. _contextLineCap = null,
  7826. _contextLineJoin = null,
  7827. _v1, _v2, _v3, _v4,
  7828. _v5 = new THREE.RenderableVertex(),
  7829. _v6 = new THREE.RenderableVertex(),
  7830. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  7831. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  7832. _color = new THREE.Color(),
  7833. _color1 = new THREE.Color(),
  7834. _color2 = new THREE.Color(),
  7835. _color3 = new THREE.Color(),
  7836. _color4 = new THREE.Color(),
  7837. _diffuseColor = new THREE.Color(),
  7838. _emissiveColor = new THREE.Color(),
  7839. _lightColor = new THREE.Color(),
  7840. _patterns = {}, _imagedatas = {},
  7841. _near, _far,
  7842. _image, _uvs,
  7843. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  7844. _clipBox = new THREE.Box2(),
  7845. _clearBox = new THREE.Box2(),
  7846. _elemBox = new THREE.Box2(),
  7847. _enableLighting = false,
  7848. _ambientLight = new THREE.Color(),
  7849. _directionalLights = new THREE.Color(),
  7850. _pointLights = new THREE.Color(),
  7851. _pi2 = Math.PI * 2,
  7852. _vector3 = new THREE.Vector3(), // Needed for PointLight
  7853. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  7854. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  7855. _pixelMap = document.createElement( 'canvas' );
  7856. _pixelMap.width = _pixelMap.height = 2;
  7857. _pixelMapContext = _pixelMap.getContext( '2d' );
  7858. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  7859. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  7860. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  7861. _pixelMapData = _pixelMapImage.data;
  7862. _gradientMap = document.createElement( 'canvas' );
  7863. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  7864. _gradientMapContext = _gradientMap.getContext( '2d' );
  7865. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  7866. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  7867. _gradientMapQuality --; // Fix UVs
  7868. this.domElement = _canvas;
  7869. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  7870. ? parameters.devicePixelRatio
  7871. : window.devicePixelRatio !== undefined
  7872. ? window.devicePixelRatio
  7873. : 1;
  7874. this.autoClear = true;
  7875. this.sortObjects = true;
  7876. this.sortElements = true;
  7877. this.info = {
  7878. render: {
  7879. vertices: 0,
  7880. faces: 0
  7881. }
  7882. }
  7883. this.setSize = function ( width, height ) {
  7884. _canvasWidth = width * this.devicePixelRatio;
  7885. _canvasHeight = height * this.devicePixelRatio;
  7886. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  7887. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  7888. _canvas.width = _canvasWidth;
  7889. _canvas.height = _canvasHeight;
  7890. _canvas.style.width = width + 'px';
  7891. _canvas.style.height = height + 'px';
  7892. _clipBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  7893. _clipBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  7894. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  7895. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  7896. _contextGlobalAlpha = 1;
  7897. _contextGlobalCompositeOperation = 0;
  7898. _contextStrokeStyle = null;
  7899. _contextFillStyle = null;
  7900. _contextLineWidth = null;
  7901. _contextLineCap = null;
  7902. _contextLineJoin = null;
  7903. };
  7904. this.setClearColor = function ( color, opacity ) {
  7905. _clearColor.copy( color );
  7906. _clearOpacity = opacity !== undefined ? opacity : 1;
  7907. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  7908. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  7909. };
  7910. this.setClearColorHex = function ( hex, opacity ) {
  7911. _clearColor.setHex( hex );
  7912. _clearOpacity = opacity !== undefined ? opacity : 1;
  7913. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  7914. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  7915. };
  7916. this.getMaxAnisotropy = function () {
  7917. return 0;
  7918. };
  7919. this.clear = function () {
  7920. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  7921. if ( _clearBox.empty() === false ) {
  7922. _clearBox.intersect( _clipBox );
  7923. _clearBox.expandByScalar( 2 );
  7924. if ( _clearOpacity < 1 ) {
  7925. _context.clearRect( _clearBox.min.x | 0, _clearBox.min.y | 0, ( _clearBox.max.x - _clearBox.min.x ) | 0, ( _clearBox.max.y - _clearBox.min.y ) | 0 );
  7926. }
  7927. if ( _clearOpacity > 0 ) {
  7928. setBlending( THREE.NormalBlending );
  7929. setOpacity( 1 );
  7930. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearOpacity + ')' );
  7931. _context.fillRect( _clearBox.min.x | 0, _clearBox.min.y | 0, ( _clearBox.max.x - _clearBox.min.x ) | 0, ( _clearBox.max.y - _clearBox.min.y ) | 0 );
  7932. }
  7933. _clearBox.makeEmpty();
  7934. }
  7935. };
  7936. this.render = function ( scene, camera ) {
  7937. if ( camera instanceof THREE.Camera === false ) {
  7938. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  7939. return;
  7940. }
  7941. if ( this.autoClear === true ) {
  7942. this.clear();
  7943. }
  7944. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  7945. _this.info.render.vertices = 0;
  7946. _this.info.render.faces = 0;
  7947. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  7948. _elements = _renderData.elements;
  7949. _lights = _renderData.lights;
  7950. /* DEBUG
  7951. _context.fillStyle = 'rgba( 0, 255, 255, 0.5 )';
  7952. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  7953. */
  7954. _enableLighting = _lights.length > 0;
  7955. if ( _enableLighting === true ) {
  7956. calculateLights();
  7957. }
  7958. for ( var e = 0, el = _elements.length; e < el; e++ ) {
  7959. var element = _elements[ e ];
  7960. var material = element.material;
  7961. if ( material === undefined || material.visible === false ) continue;
  7962. _elemBox.makeEmpty();
  7963. if ( element instanceof THREE.RenderableParticle ) {
  7964. _v1 = element;
  7965. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  7966. renderParticle( _v1, element, material, scene );
  7967. } else if ( element instanceof THREE.RenderableLine ) {
  7968. _v1 = element.v1; _v2 = element.v2;
  7969. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7970. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7971. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen ] );
  7972. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  7973. renderLine( _v1, _v2, element, material, scene );
  7974. }
  7975. } else if ( element instanceof THREE.RenderableFace3 ) {
  7976. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  7977. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7978. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7979. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  7980. if ( material.overdraw === true ) {
  7981. expand( _v1.positionScreen, _v2.positionScreen );
  7982. expand( _v2.positionScreen, _v3.positionScreen );
  7983. expand( _v3.positionScreen, _v1.positionScreen );
  7984. }
  7985. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen, _v3.positionScreen ] );
  7986. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  7987. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material, scene );
  7988. }
  7989. } else if ( element instanceof THREE.RenderableFace4 ) {
  7990. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  7991. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7992. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7993. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  7994. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  7995. _v5.positionScreen.copy( _v2.positionScreen );
  7996. _v6.positionScreen.copy( _v4.positionScreen );
  7997. if ( material.overdraw === true ) {
  7998. expand( _v1.positionScreen, _v2.positionScreen );
  7999. expand( _v2.positionScreen, _v4.positionScreen );
  8000. expand( _v4.positionScreen, _v1.positionScreen );
  8001. expand( _v3.positionScreen, _v5.positionScreen );
  8002. expand( _v3.positionScreen, _v6.positionScreen );
  8003. }
  8004. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen, _v3.positionScreen, _v4.positionScreen ] );
  8005. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8006. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material, scene );
  8007. }
  8008. }
  8009. /* DEBUG
  8010. _context.lineWidth = 1;
  8011. _context.strokeStyle = 'rgba( 0, 255, 0, 0.5 )';
  8012. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  8013. */
  8014. _clearBox.union( _elemBox );
  8015. }
  8016. /* DEBUG
  8017. _context.lineWidth = 1;
  8018. _context.strokeStyle = 'rgba( 255, 0, 0, 0.5 )';
  8019. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  8020. */
  8021. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  8022. //
  8023. function calculateLights() {
  8024. _ambientLight.setRGB( 0, 0, 0 );
  8025. _directionalLights.setRGB( 0, 0, 0 );
  8026. _pointLights.setRGB( 0, 0, 0 );
  8027. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8028. var light = _lights[ l ];
  8029. var lightColor = light.color;
  8030. if ( light instanceof THREE.AmbientLight ) {
  8031. _ambientLight.add( lightColor );
  8032. } else if ( light instanceof THREE.DirectionalLight ) {
  8033. // for particles
  8034. _directionalLights.add( lightColor );
  8035. } else if ( light instanceof THREE.PointLight ) {
  8036. // for particles
  8037. _pointLights.add( lightColor );
  8038. }
  8039. }
  8040. }
  8041. function calculateLight( position, normal, color ) {
  8042. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8043. var light = _lights[ l ];
  8044. _lightColor.copy( light.color );
  8045. if ( light instanceof THREE.DirectionalLight ) {
  8046. var lightPosition = light.matrixWorld.getPosition().normalize();
  8047. var amount = normal.dot( lightPosition );
  8048. if ( amount <= 0 ) continue;
  8049. amount *= light.intensity;
  8050. color.add( _lightColor.multiplyScalar( amount ) );
  8051. } else if ( light instanceof THREE.PointLight ) {
  8052. var lightPosition = light.matrixWorld.getPosition();
  8053. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  8054. if ( amount <= 0 ) continue;
  8055. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  8056. if ( amount == 0 ) continue;
  8057. amount *= light.intensity;
  8058. color.add( _lightColor.multiplyScalar( amount ) );
  8059. }
  8060. }
  8061. }
  8062. function renderParticle( v1, element, material, scene ) {
  8063. setOpacity( material.opacity );
  8064. setBlending( material.blending );
  8065. var width, height, scaleX, scaleY,
  8066. bitmap, bitmapWidth, bitmapHeight;
  8067. if ( material instanceof THREE.ParticleBasicMaterial ) {
  8068. if ( material.map === null ) {
  8069. scaleX = element.object.scale.x;
  8070. scaleY = element.object.scale.y;
  8071. // TODO: Be able to disable this
  8072. scaleX *= element.scale.x * _canvasWidthHalf;
  8073. scaleY *= element.scale.y * _canvasHeightHalf;
  8074. _elemBox.min.set( v1.x - scaleX, v1.y - scaleY );
  8075. _elemBox.max.set( v1.x + scaleX, v1.y + scaleY );
  8076. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8077. return;
  8078. }
  8079. setFillStyle( material.color.getStyle() );
  8080. _context.save();
  8081. _context.translate( v1.x, v1.y );
  8082. _context.rotate( - element.rotation );
  8083. _context.scale( scaleX, scaleY );
  8084. _context.fillRect( -1, -1, 2, 2 );
  8085. _context.restore();
  8086. } else {
  8087. bitmap = material.map.image;
  8088. bitmapWidth = bitmap.width >> 1;
  8089. bitmapHeight = bitmap.height >> 1;
  8090. scaleX = element.scale.x * _canvasWidthHalf;
  8091. scaleY = element.scale.y * _canvasHeightHalf;
  8092. width = scaleX * bitmapWidth;
  8093. height = scaleY * bitmapHeight;
  8094. // TODO: Rotations break this...
  8095. _elemBox.min.set( v1.x - width, v1.y - height );
  8096. _elemBox.max.set( v1.x + width, v1.y + height );
  8097. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8098. return;
  8099. }
  8100. _context.save();
  8101. _context.translate( v1.x, v1.y );
  8102. _context.rotate( - element.rotation );
  8103. _context.scale( scaleX, - scaleY );
  8104. _context.translate( - bitmapWidth, - bitmapHeight );
  8105. _context.drawImage( bitmap, 0, 0 );
  8106. _context.restore();
  8107. }
  8108. /* DEBUG
  8109. setStrokeStyle( 'rgb(255,255,0)' );
  8110. _context.beginPath();
  8111. _context.moveTo( v1.x - 10, v1.y );
  8112. _context.lineTo( v1.x + 10, v1.y );
  8113. _context.moveTo( v1.x, v1.y - 10 );
  8114. _context.lineTo( v1.x, v1.y + 10 );
  8115. _context.stroke();
  8116. */
  8117. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  8118. width = element.scale.x * _canvasWidthHalf;
  8119. height = element.scale.y * _canvasHeightHalf;
  8120. _elemBox.min.set( v1.x - width, v1.y - height );
  8121. _elemBox.max.set( v1.x + width, v1.y + height );
  8122. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8123. return;
  8124. }
  8125. setStrokeStyle( material.color.getStyle() );
  8126. setFillStyle( material.color.getStyle() );
  8127. _context.save();
  8128. _context.translate( v1.x, v1.y );
  8129. _context.rotate( - element.rotation );
  8130. _context.scale( width, height );
  8131. material.program( _context );
  8132. _context.restore();
  8133. }
  8134. }
  8135. function renderLine( v1, v2, element, material, scene ) {
  8136. setOpacity( material.opacity );
  8137. setBlending( material.blending );
  8138. _context.beginPath();
  8139. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  8140. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  8141. if ( material instanceof THREE.LineBasicMaterial ) {
  8142. setLineWidth( material.linewidth );
  8143. setLineCap( material.linecap );
  8144. setLineJoin( material.linejoin );
  8145. setStrokeStyle( material.color.getStyle() );
  8146. _context.stroke();
  8147. _elemBox.expandByScalar( material.linewidth * 2 );
  8148. }
  8149. }
  8150. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material, scene ) {
  8151. _this.info.render.vertices += 3;
  8152. _this.info.render.faces ++;
  8153. setOpacity( material.opacity );
  8154. setBlending( material.blending );
  8155. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8156. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8157. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8158. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  8159. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null && material.map === null ) {
  8160. _diffuseColor.copy( material.color );
  8161. _emissiveColor.copy( material.emissive );
  8162. if ( material.vertexColors === THREE.FaceColors ) {
  8163. _diffuseColor.multiply( element.color );
  8164. }
  8165. if ( _enableLighting === true ) {
  8166. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  8167. _color1.copy( _ambientLight );
  8168. _color2.copy( _ambientLight );
  8169. _color3.copy( _ambientLight );
  8170. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  8171. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  8172. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color3 );
  8173. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  8174. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  8175. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  8176. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8177. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8178. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8179. } else {
  8180. _color.copy( _ambientLight );
  8181. calculateLight( element.centroidModel, element.normalModel, _color );
  8182. _color.multiply( _diffuseColor ).add( _emissiveColor );
  8183. material.wireframe === true
  8184. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8185. : fillPath( _color );
  8186. }
  8187. } else {
  8188. material.wireframe === true
  8189. ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8190. : fillPath( material.color );
  8191. }
  8192. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8193. if ( material.map !== null ) {
  8194. if ( material.map.mapping instanceof THREE.UVMapping ) {
  8195. _uvs = element.uvs[ 0 ];
  8196. 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 );
  8197. }
  8198. } else if ( material.envMap !== null ) {
  8199. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  8200. _vector3.copy( element.vertexNormalsModelView[ uv1 ] );
  8201. _uv1x = 0.5 * _vector3.x + 0.5;
  8202. _uv1y = 0.5 * _vector3.y + 0.5;
  8203. _vector3.copy( element.vertexNormalsModelView[ uv2 ] );
  8204. _uv2x = 0.5 * _vector3.x + 0.5;
  8205. _uv2y = 0.5 * _vector3.y + 0.5;
  8206. _vector3.copy( element.vertexNormalsModelView[ uv3 ] );
  8207. _uv3x = 0.5 * _vector3.x + 0.5;
  8208. _uv3y = 0.5 * _vector3.y + 0.5;
  8209. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  8210. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  8211. }*/
  8212. } else {
  8213. _color.copy( material.color );
  8214. if ( material.vertexColors === THREE.FaceColors ) {
  8215. _color.multiply( element.color );
  8216. }
  8217. material.wireframe === true
  8218. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8219. : fillPath( _color );
  8220. }
  8221. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8222. _near = camera.near;
  8223. _far = camera.far;
  8224. var depth;
  8225. depth = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  8226. _color1.setRGB( depth, depth, depth );
  8227. depth = 1 - smoothstep( v2.positionScreen.z, _near, _far )
  8228. _color2.setRGB( depth, depth, depth );
  8229. depth = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  8230. _color3.setRGB( depth, depth, depth );
  8231. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8232. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8233. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8234. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8235. var normal;
  8236. if ( material.shading == THREE.FlatShading ) {
  8237. normal = element.normalModelView;
  8238. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8239. material.wireframe === true
  8240. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8241. : fillPath( _color );
  8242. } else if ( material.shading == THREE.SmoothShading ) {
  8243. normal = element.vertexNormalsModelView[ uv1 ];
  8244. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8245. normal = element.vertexNormalsModelView[ uv2 ];
  8246. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8247. normal = element.vertexNormalsModelView[ uv3 ];
  8248. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8249. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8250. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8251. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8252. }
  8253. }
  8254. }
  8255. function renderFace4( v1, v2, v3, v4, v5, v6, element, material, scene ) {
  8256. _this.info.render.vertices += 4;
  8257. _this.info.render.faces ++;
  8258. setOpacity( material.opacity );
  8259. setBlending( material.blending );
  8260. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  8261. // Let renderFace3() handle this
  8262. renderFace3( v1, v2, v4, 0, 1, 3, element, material, scene );
  8263. renderFace3( v5, v3, v6, 1, 2, 3, element, material, scene );
  8264. return;
  8265. }
  8266. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8267. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8268. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8269. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  8270. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  8271. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  8272. if ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8273. _diffuseColor.copy( material.color );
  8274. _emissiveColor.copy( material.emissive );
  8275. if ( material.vertexColors === THREE.FaceColors ) {
  8276. _diffuseColor.multiply( element.color );
  8277. }
  8278. if ( _enableLighting === true ) {
  8279. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  8280. _color1.copy( _ambientLight );
  8281. _color2.copy( _ambientLight );
  8282. _color3.copy( _ambientLight );
  8283. _color4.copy( _ambientLight );
  8284. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  8285. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  8286. calculateLight( element.v4.positionWorld, element.vertexNormalsModel[ 3 ], _color3 );
  8287. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color4 );
  8288. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  8289. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  8290. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  8291. _color4.multiply( _diffuseColor ).add( _emissiveColor );
  8292. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8293. // TODO: UVs are incorrect, v4->v3?
  8294. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8295. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8296. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8297. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8298. } else {
  8299. _color.copy( _ambientLight );
  8300. calculateLight( element.centroidModel, element.normalModel, _color );
  8301. _color.multiply( _diffuseColor ).add( _emissiveColor );
  8302. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8303. material.wireframe === true
  8304. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8305. : fillPath( _color );
  8306. }
  8307. } else {
  8308. _color.addColors( _diffuseColor, _emissiveColor );
  8309. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8310. material.wireframe === true
  8311. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8312. : fillPath( _color );
  8313. }
  8314. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  8315. _color.copy( material.color );
  8316. if ( material.vertexColors === THREE.FaceColors ) {
  8317. _color.multiply( element.color );
  8318. }
  8319. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8320. material.wireframe === true
  8321. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8322. : fillPath( _color );
  8323. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8324. var normal;
  8325. if ( material.shading == THREE.FlatShading ) {
  8326. normal = element.normalModelView;
  8327. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8328. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8329. material.wireframe === true
  8330. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8331. : fillPath( _color );
  8332. } else if ( material.shading == THREE.SmoothShading ) {
  8333. normal = element.vertexNormalsModelView[ 0 ];
  8334. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8335. normal = element.vertexNormalsModelView[ 1 ];
  8336. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8337. normal = element.vertexNormalsModelView[ 3 ];
  8338. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8339. normal = element.vertexNormalsModelView[ 2 ];
  8340. _color4.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8341. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8342. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8343. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8344. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8345. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8346. }
  8347. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8348. _near = camera.near;
  8349. _far = camera.far;
  8350. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  8351. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  8352. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z, _near, _far );
  8353. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  8354. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8355. // TODO: UVs are incorrect, v4->v3?
  8356. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8357. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8358. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8359. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8360. }
  8361. }
  8362. //
  8363. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  8364. _context.beginPath();
  8365. _context.moveTo( x0, y0 );
  8366. _context.lineTo( x1, y1 );
  8367. _context.lineTo( x2, y2 );
  8368. _context.closePath();
  8369. }
  8370. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  8371. _context.beginPath();
  8372. _context.moveTo( x0, y0 );
  8373. _context.lineTo( x1, y1 );
  8374. _context.lineTo( x2, y2 );
  8375. _context.lineTo( x3, y3 );
  8376. _context.closePath();
  8377. }
  8378. function strokePath( color, linewidth, linecap, linejoin ) {
  8379. setLineWidth( linewidth );
  8380. setLineCap( linecap );
  8381. setLineJoin( linejoin );
  8382. setStrokeStyle( color.getStyle() );
  8383. _context.stroke();
  8384. _elemBox.expandByScalar( linewidth * 2 );
  8385. }
  8386. function fillPath( color ) {
  8387. setFillStyle( color.getStyle() );
  8388. _context.fill();
  8389. }
  8390. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  8391. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  8392. if ( texture.needsUpdate === true ) {
  8393. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  8394. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  8395. _patterns[ texture.id ] = _context.createPattern(
  8396. texture.image, repeatX === true && repeatY === true
  8397. ? 'repeat'
  8398. : repeatX === true && repeatY === false
  8399. ? 'repeat-x'
  8400. : repeatX === false && repeatY === true
  8401. ? 'repeat-y'
  8402. : 'no-repeat'
  8403. );
  8404. texture.needsUpdate = false;
  8405. }
  8406. _patterns[ texture.id ] === undefined
  8407. ? setFillStyle( 'rgba(0,0,0,1)' )
  8408. : setFillStyle( _patterns[ texture.id ] );
  8409. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8410. var a, b, c, d, e, f, det, idet,
  8411. offsetX = texture.offset.x / texture.repeat.x,
  8412. offsetY = texture.offset.y / texture.repeat.y,
  8413. width = texture.image.width * texture.repeat.x,
  8414. height = texture.image.height * texture.repeat.y;
  8415. u0 = ( u0 + offsetX ) * width;
  8416. v0 = ( 1.0 - v0 + offsetY ) * height;
  8417. u1 = ( u1 + offsetX ) * width;
  8418. v1 = ( 1.0 - v1 + offsetY ) * height;
  8419. u2 = ( u2 + offsetX ) * width;
  8420. v2 = ( 1.0 - v2 + offsetY ) * height;
  8421. x1 -= x0; y1 -= y0;
  8422. x2 -= x0; y2 -= y0;
  8423. u1 -= u0; v1 -= v0;
  8424. u2 -= u0; v2 -= v0;
  8425. det = u1 * v2 - u2 * v1;
  8426. if ( det === 0 ) {
  8427. if ( _imagedatas[ texture.id ] === undefined ) {
  8428. var canvas = document.createElement( 'canvas' )
  8429. canvas.width = texture.image.width;
  8430. canvas.height = texture.image.height;
  8431. var context = canvas.getContext( '2d' );
  8432. context.drawImage( texture.image, 0, 0 );
  8433. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  8434. }
  8435. var data = _imagedatas[ texture.id ];
  8436. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  8437. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  8438. fillPath( _color );
  8439. return;
  8440. }
  8441. idet = 1 / det;
  8442. a = ( v2 * x1 - v1 * x2 ) * idet;
  8443. b = ( v2 * y1 - v1 * y2 ) * idet;
  8444. c = ( u1 * x2 - u2 * x1 ) * idet;
  8445. d = ( u1 * y2 - u2 * y1 ) * idet;
  8446. e = x0 - a * u0 - c * v0;
  8447. f = y0 - b * u0 - d * v0;
  8448. _context.save();
  8449. _context.transform( a, b, c, d, e, f );
  8450. _context.fill();
  8451. _context.restore();
  8452. }
  8453. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  8454. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8455. var a, b, c, d, e, f, det, idet,
  8456. width = image.width - 1,
  8457. height = image.height - 1;
  8458. u0 *= width; v0 *= height;
  8459. u1 *= width; v1 *= height;
  8460. u2 *= width; v2 *= height;
  8461. x1 -= x0; y1 -= y0;
  8462. x2 -= x0; y2 -= y0;
  8463. u1 -= u0; v1 -= v0;
  8464. u2 -= u0; v2 -= v0;
  8465. det = u1 * v2 - u2 * v1;
  8466. idet = 1 / det;
  8467. a = ( v2 * x1 - v1 * x2 ) * idet;
  8468. b = ( v2 * y1 - v1 * y2 ) * idet;
  8469. c = ( u1 * x2 - u2 * x1 ) * idet;
  8470. d = ( u1 * y2 - u2 * y1 ) * idet;
  8471. e = x0 - a * u0 - c * v0;
  8472. f = y0 - b * u0 - d * v0;
  8473. _context.save();
  8474. _context.transform( a, b, c, d, e, f );
  8475. _context.clip();
  8476. _context.drawImage( image, 0, 0 );
  8477. _context.restore();
  8478. }
  8479. function getGradientTexture( color1, color2, color3, color4 ) {
  8480. // http://mrdoob.com/blog/post/710
  8481. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  8482. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  8483. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  8484. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  8485. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  8486. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  8487. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  8488. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  8489. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  8490. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  8491. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  8492. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  8493. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  8494. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  8495. return _gradientMap;
  8496. }
  8497. function smoothstep( value, min, max ) {
  8498. var x = ( value - min ) / ( max - min );
  8499. return x * x * ( 3 - 2 * x );
  8500. }
  8501. // Hide anti-alias gaps
  8502. function expand( v1, v2 ) {
  8503. var x = v2.x - v1.x, y = v2.y - v1.y,
  8504. det = x * x + y * y, idet;
  8505. if ( det === 0 ) return;
  8506. idet = 1 / Math.sqrt( det );
  8507. x *= idet; y *= idet;
  8508. v2.x += x; v2.y += y;
  8509. v1.x -= x; v1.y -= y;
  8510. }
  8511. };
  8512. // Context cached methods.
  8513. function setOpacity( value ) {
  8514. if ( _contextGlobalAlpha !== value ) {
  8515. _context.globalAlpha = value;
  8516. _contextGlobalAlpha = value;
  8517. }
  8518. }
  8519. function setBlending( value ) {
  8520. if ( _contextGlobalCompositeOperation !== value ) {
  8521. if ( value === THREE.NormalBlending ) {
  8522. _context.globalCompositeOperation = 'source-over';
  8523. } else if ( value === THREE.AdditiveBlending ) {
  8524. _context.globalCompositeOperation = 'lighter';
  8525. } else if ( value === THREE.SubtractiveBlending ) {
  8526. _context.globalCompositeOperation = 'darker';
  8527. }
  8528. _contextGlobalCompositeOperation = value;
  8529. }
  8530. }
  8531. function setLineWidth( value ) {
  8532. if ( _contextLineWidth !== value ) {
  8533. _context.lineWidth = value;
  8534. _contextLineWidth = value;
  8535. }
  8536. }
  8537. function setLineCap( value ) {
  8538. // "butt", "round", "square"
  8539. if ( _contextLineCap !== value ) {
  8540. _context.lineCap = value;
  8541. _contextLineCap = value;
  8542. }
  8543. }
  8544. function setLineJoin( value ) {
  8545. // "round", "bevel", "miter"
  8546. if ( _contextLineJoin !== value ) {
  8547. _context.lineJoin = value;
  8548. _contextLineJoin = value;
  8549. }
  8550. }
  8551. function setStrokeStyle( value ) {
  8552. if ( _contextStrokeStyle !== value ) {
  8553. _context.strokeStyle = value;
  8554. _contextStrokeStyle = value;
  8555. }
  8556. }
  8557. function setFillStyle( value ) {
  8558. if ( _contextFillStyle !== value ) {
  8559. _context.fillStyle = value;
  8560. _contextFillStyle = value;
  8561. }
  8562. }
  8563. };
  8564. /**
  8565. * @author alteredq / http://alteredqualia.com/
  8566. * @author mrdoob / http://mrdoob.com/
  8567. * @author mikael emtinger / http://gomo.se/
  8568. */
  8569. THREE.ShaderChunk = {
  8570. // FOG
  8571. fog_pars_fragment: [
  8572. "#ifdef USE_FOG",
  8573. "uniform vec3 fogColor;",
  8574. "#ifdef FOG_EXP2",
  8575. "uniform float fogDensity;",
  8576. "#else",
  8577. "uniform float fogNear;",
  8578. "uniform float fogFar;",
  8579. "#endif",
  8580. "#endif"
  8581. ].join("\n"),
  8582. fog_fragment: [
  8583. "#ifdef USE_FOG",
  8584. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  8585. "#ifdef FOG_EXP2",
  8586. "const float LOG2 = 1.442695;",
  8587. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  8588. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  8589. "#else",
  8590. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  8591. "#endif",
  8592. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  8593. "#endif"
  8594. ].join("\n"),
  8595. // ENVIRONMENT MAP
  8596. envmap_pars_fragment: [
  8597. "#ifdef USE_ENVMAP",
  8598. "uniform float reflectivity;",
  8599. "uniform samplerCube envMap;",
  8600. "uniform float flipEnvMap;",
  8601. "uniform int combine;",
  8602. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8603. "uniform bool useRefract;",
  8604. "uniform float refractionRatio;",
  8605. "#else",
  8606. "varying vec3 vReflect;",
  8607. "#endif",
  8608. "#endif"
  8609. ].join("\n"),
  8610. envmap_fragment: [
  8611. "#ifdef USE_ENVMAP",
  8612. "vec3 reflectVec;",
  8613. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8614. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  8615. "if ( useRefract ) {",
  8616. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  8617. "} else { ",
  8618. "reflectVec = reflect( cameraToVertex, normal );",
  8619. "}",
  8620. "#else",
  8621. "reflectVec = vReflect;",
  8622. "#endif",
  8623. "#ifdef DOUBLE_SIDED",
  8624. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  8625. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8626. "#else",
  8627. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8628. "#endif",
  8629. "#ifdef GAMMA_INPUT",
  8630. "cubeColor.xyz *= cubeColor.xyz;",
  8631. "#endif",
  8632. "if ( combine == 1 ) {",
  8633. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  8634. "} else if ( combine == 2 ) {",
  8635. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  8636. "} else {",
  8637. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  8638. "}",
  8639. "#endif"
  8640. ].join("\n"),
  8641. envmap_pars_vertex: [
  8642. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8643. "varying vec3 vReflect;",
  8644. "uniform float refractionRatio;",
  8645. "uniform bool useRefract;",
  8646. "#endif"
  8647. ].join("\n"),
  8648. worldpos_vertex : [
  8649. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  8650. "#ifdef USE_SKINNING",
  8651. "vec4 worldPosition = modelMatrix * skinned;",
  8652. "#endif",
  8653. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8654. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  8655. "#endif",
  8656. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8657. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  8658. "#endif",
  8659. "#endif"
  8660. ].join("\n"),
  8661. envmap_vertex : [
  8662. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8663. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  8664. "worldNormal = normalize( worldNormal );",
  8665. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  8666. "if ( useRefract ) {",
  8667. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  8668. "} else {",
  8669. "vReflect = reflect( cameraToVertex, worldNormal );",
  8670. "}",
  8671. "#endif"
  8672. ].join("\n"),
  8673. // COLOR MAP (particles)
  8674. map_particle_pars_fragment: [
  8675. "#ifdef USE_MAP",
  8676. "uniform sampler2D map;",
  8677. "#endif"
  8678. ].join("\n"),
  8679. map_particle_fragment: [
  8680. "#ifdef USE_MAP",
  8681. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  8682. "#endif"
  8683. ].join("\n"),
  8684. // COLOR MAP (triangles)
  8685. map_pars_vertex: [
  8686. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8687. "varying vec2 vUv;",
  8688. "uniform vec4 offsetRepeat;",
  8689. "#endif"
  8690. ].join("\n"),
  8691. map_pars_fragment: [
  8692. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8693. "varying vec2 vUv;",
  8694. "#endif",
  8695. "#ifdef USE_MAP",
  8696. "uniform sampler2D map;",
  8697. "#endif"
  8698. ].join("\n"),
  8699. map_vertex: [
  8700. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8701. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  8702. "#endif"
  8703. ].join("\n"),
  8704. map_fragment: [
  8705. "#ifdef USE_MAP",
  8706. "vec4 texelColor = texture2D( map, vUv );",
  8707. "#ifdef GAMMA_INPUT",
  8708. "texelColor.xyz *= texelColor.xyz;",
  8709. "#endif",
  8710. "gl_FragColor = gl_FragColor * texelColor;",
  8711. "#endif"
  8712. ].join("\n"),
  8713. // LIGHT MAP
  8714. lightmap_pars_fragment: [
  8715. "#ifdef USE_LIGHTMAP",
  8716. "varying vec2 vUv2;",
  8717. "uniform sampler2D lightMap;",
  8718. "#endif"
  8719. ].join("\n"),
  8720. lightmap_pars_vertex: [
  8721. "#ifdef USE_LIGHTMAP",
  8722. "varying vec2 vUv2;",
  8723. "#endif"
  8724. ].join("\n"),
  8725. lightmap_fragment: [
  8726. "#ifdef USE_LIGHTMAP",
  8727. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  8728. "#endif"
  8729. ].join("\n"),
  8730. lightmap_vertex: [
  8731. "#ifdef USE_LIGHTMAP",
  8732. "vUv2 = uv2;",
  8733. "#endif"
  8734. ].join("\n"),
  8735. // BUMP MAP
  8736. bumpmap_pars_fragment: [
  8737. "#ifdef USE_BUMPMAP",
  8738. "uniform sampler2D bumpMap;",
  8739. "uniform float bumpScale;",
  8740. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  8741. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  8742. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8743. "vec2 dHdxy_fwd() {",
  8744. "vec2 dSTdx = dFdx( vUv );",
  8745. "vec2 dSTdy = dFdy( vUv );",
  8746. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  8747. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  8748. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  8749. "return vec2( dBx, dBy );",
  8750. "}",
  8751. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  8752. "vec3 vSigmaX = dFdx( surf_pos );",
  8753. "vec3 vSigmaY = dFdy( surf_pos );",
  8754. "vec3 vN = surf_norm;", // normalized
  8755. "vec3 R1 = cross( vSigmaY, vN );",
  8756. "vec3 R2 = cross( vN, vSigmaX );",
  8757. "float fDet = dot( vSigmaX, R1 );",
  8758. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  8759. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  8760. "}",
  8761. "#endif"
  8762. ].join("\n"),
  8763. // NORMAL MAP
  8764. normalmap_pars_fragment: [
  8765. "#ifdef USE_NORMALMAP",
  8766. "uniform sampler2D normalMap;",
  8767. "uniform vec2 normalScale;",
  8768. // Per-Pixel Tangent Space Normal Mapping
  8769. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  8770. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  8771. "vec3 q0 = dFdx( eye_pos.xyz );",
  8772. "vec3 q1 = dFdy( eye_pos.xyz );",
  8773. "vec2 st0 = dFdx( vUv.st );",
  8774. "vec2 st1 = dFdy( vUv.st );",
  8775. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  8776. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  8777. "vec3 N = normalize( surf_norm );",
  8778. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  8779. "mapN.xy = normalScale * mapN.xy;",
  8780. "mat3 tsn = mat3( S, T, N );",
  8781. "return normalize( tsn * mapN );",
  8782. "}",
  8783. "#endif"
  8784. ].join("\n"),
  8785. // SPECULAR MAP
  8786. specularmap_pars_fragment: [
  8787. "#ifdef USE_SPECULARMAP",
  8788. "uniform sampler2D specularMap;",
  8789. "#endif"
  8790. ].join("\n"),
  8791. specularmap_fragment: [
  8792. "float specularStrength;",
  8793. "#ifdef USE_SPECULARMAP",
  8794. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  8795. "specularStrength = texelSpecular.r;",
  8796. "#else",
  8797. "specularStrength = 1.0;",
  8798. "#endif"
  8799. ].join("\n"),
  8800. // LIGHTS LAMBERT
  8801. lights_lambert_pars_vertex: [
  8802. "uniform vec3 ambient;",
  8803. "uniform vec3 diffuse;",
  8804. "uniform vec3 emissive;",
  8805. "uniform vec3 ambientLightColor;",
  8806. "#if MAX_DIR_LIGHTS > 0",
  8807. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  8808. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  8809. "#endif",
  8810. "#if MAX_HEMI_LIGHTS > 0",
  8811. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  8812. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  8813. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  8814. "#endif",
  8815. "#if MAX_POINT_LIGHTS > 0",
  8816. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  8817. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8818. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8819. "#endif",
  8820. "#if MAX_SPOT_LIGHTS > 0",
  8821. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  8822. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8823. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  8824. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8825. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  8826. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  8827. "#endif",
  8828. "#ifdef WRAP_AROUND",
  8829. "uniform vec3 wrapRGB;",
  8830. "#endif"
  8831. ].join("\n"),
  8832. lights_lambert_vertex: [
  8833. "vLightFront = vec3( 0.0 );",
  8834. "#ifdef DOUBLE_SIDED",
  8835. "vLightBack = vec3( 0.0 );",
  8836. "#endif",
  8837. "transformedNormal = normalize( transformedNormal );",
  8838. "#if MAX_DIR_LIGHTS > 0",
  8839. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  8840. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  8841. "vec3 dirVector = normalize( lDirection.xyz );",
  8842. "float dotProduct = dot( transformedNormal, dirVector );",
  8843. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8844. "#ifdef DOUBLE_SIDED",
  8845. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8846. "#ifdef WRAP_AROUND",
  8847. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8848. "#endif",
  8849. "#endif",
  8850. "#ifdef WRAP_AROUND",
  8851. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8852. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  8853. "#ifdef DOUBLE_SIDED",
  8854. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  8855. "#endif",
  8856. "#endif",
  8857. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  8858. "#ifdef DOUBLE_SIDED",
  8859. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  8860. "#endif",
  8861. "}",
  8862. "#endif",
  8863. "#if MAX_POINT_LIGHTS > 0",
  8864. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8865. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8866. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8867. "float lDistance = 1.0;",
  8868. "if ( pointLightDistance[ i ] > 0.0 )",
  8869. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8870. "lVector = normalize( lVector );",
  8871. "float dotProduct = dot( transformedNormal, lVector );",
  8872. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8873. "#ifdef DOUBLE_SIDED",
  8874. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8875. "#ifdef WRAP_AROUND",
  8876. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8877. "#endif",
  8878. "#endif",
  8879. "#ifdef WRAP_AROUND",
  8880. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8881. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  8882. "#ifdef DOUBLE_SIDED",
  8883. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  8884. "#endif",
  8885. "#endif",
  8886. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  8887. "#ifdef DOUBLE_SIDED",
  8888. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  8889. "#endif",
  8890. "}",
  8891. "#endif",
  8892. "#if MAX_SPOT_LIGHTS > 0",
  8893. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8894. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8895. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8896. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  8897. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  8898. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  8899. "float lDistance = 1.0;",
  8900. "if ( spotLightDistance[ i ] > 0.0 )",
  8901. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8902. "lVector = normalize( lVector );",
  8903. "float dotProduct = dot( transformedNormal, lVector );",
  8904. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8905. "#ifdef DOUBLE_SIDED",
  8906. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8907. "#ifdef WRAP_AROUND",
  8908. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8909. "#endif",
  8910. "#endif",
  8911. "#ifdef WRAP_AROUND",
  8912. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8913. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  8914. "#ifdef DOUBLE_SIDED",
  8915. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  8916. "#endif",
  8917. "#endif",
  8918. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  8919. "#ifdef DOUBLE_SIDED",
  8920. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  8921. "#endif",
  8922. "}",
  8923. "}",
  8924. "#endif",
  8925. "#if MAX_HEMI_LIGHTS > 0",
  8926. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  8927. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  8928. "vec3 lVector = normalize( lDirection.xyz );",
  8929. "float dotProduct = dot( transformedNormal, lVector );",
  8930. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  8931. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  8932. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  8933. "#ifdef DOUBLE_SIDED",
  8934. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  8935. "#endif",
  8936. "}",
  8937. "#endif",
  8938. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  8939. "#ifdef DOUBLE_SIDED",
  8940. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  8941. "#endif"
  8942. ].join("\n"),
  8943. // LIGHTS PHONG
  8944. lights_phong_pars_vertex: [
  8945. "#ifndef PHONG_PER_PIXEL",
  8946. "#if MAX_POINT_LIGHTS > 0",
  8947. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8948. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8949. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  8950. "#endif",
  8951. "#if MAX_SPOT_LIGHTS > 0",
  8952. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8953. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8954. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  8955. "#endif",
  8956. "#endif",
  8957. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8958. "varying vec3 vWorldPosition;",
  8959. "#endif"
  8960. ].join("\n"),
  8961. lights_phong_vertex: [
  8962. "#ifndef PHONG_PER_PIXEL",
  8963. "#if MAX_POINT_LIGHTS > 0",
  8964. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8965. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8966. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8967. "float lDistance = 1.0;",
  8968. "if ( pointLightDistance[ i ] > 0.0 )",
  8969. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8970. "vPointLight[ i ] = vec4( lVector, lDistance );",
  8971. "}",
  8972. "#endif",
  8973. "#if MAX_SPOT_LIGHTS > 0",
  8974. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8975. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8976. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8977. "float lDistance = 1.0;",
  8978. "if ( spotLightDistance[ i ] > 0.0 )",
  8979. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8980. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  8981. "}",
  8982. "#endif",
  8983. "#endif",
  8984. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8985. "vWorldPosition = worldPosition.xyz;",
  8986. "#endif"
  8987. ].join("\n"),
  8988. lights_phong_pars_fragment: [
  8989. "uniform vec3 ambientLightColor;",
  8990. "#if MAX_DIR_LIGHTS > 0",
  8991. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  8992. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  8993. "#endif",
  8994. "#if MAX_HEMI_LIGHTS > 0",
  8995. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  8996. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  8997. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  8998. "#endif",
  8999. "#if MAX_POINT_LIGHTS > 0",
  9000. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9001. "#ifdef PHONG_PER_PIXEL",
  9002. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9003. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9004. "#else",
  9005. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9006. "#endif",
  9007. "#endif",
  9008. "#if MAX_SPOT_LIGHTS > 0",
  9009. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9010. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9011. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9012. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9013. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9014. "#ifdef PHONG_PER_PIXEL",
  9015. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9016. "#else",
  9017. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9018. "#endif",
  9019. "#endif",
  9020. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9021. "varying vec3 vWorldPosition;",
  9022. "#endif",
  9023. "#ifdef WRAP_AROUND",
  9024. "uniform vec3 wrapRGB;",
  9025. "#endif",
  9026. "varying vec3 vViewPosition;",
  9027. "varying vec3 vNormal;"
  9028. ].join("\n"),
  9029. lights_phong_fragment: [
  9030. "vec3 normal = normalize( vNormal );",
  9031. "vec3 viewPosition = normalize( vViewPosition );",
  9032. "#ifdef DOUBLE_SIDED",
  9033. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9034. "#endif",
  9035. "#ifdef USE_NORMALMAP",
  9036. "normal = perturbNormal2Arb( -viewPosition, normal );",
  9037. "#elif defined( USE_BUMPMAP )",
  9038. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  9039. "#endif",
  9040. "#if MAX_POINT_LIGHTS > 0",
  9041. "vec3 pointDiffuse = vec3( 0.0 );",
  9042. "vec3 pointSpecular = vec3( 0.0 );",
  9043. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9044. "#ifdef PHONG_PER_PIXEL",
  9045. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9046. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9047. "float lDistance = 1.0;",
  9048. "if ( pointLightDistance[ i ] > 0.0 )",
  9049. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9050. "lVector = normalize( lVector );",
  9051. "#else",
  9052. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  9053. "float lDistance = vPointLight[ i ].w;",
  9054. "#endif",
  9055. // diffuse
  9056. "float dotProduct = dot( normal, lVector );",
  9057. "#ifdef WRAP_AROUND",
  9058. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  9059. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9060. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  9061. "#else",
  9062. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  9063. "#endif",
  9064. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  9065. // specular
  9066. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  9067. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  9068. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  9069. "#ifdef PHYSICALLY_BASED_SHADING",
  9070. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9071. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9072. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  9073. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  9074. "#else",
  9075. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  9076. "#endif",
  9077. "}",
  9078. "#endif",
  9079. "#if MAX_SPOT_LIGHTS > 0",
  9080. "vec3 spotDiffuse = vec3( 0.0 );",
  9081. "vec3 spotSpecular = vec3( 0.0 );",
  9082. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9083. "#ifdef PHONG_PER_PIXEL",
  9084. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9085. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9086. "float lDistance = 1.0;",
  9087. "if ( spotLightDistance[ i ] > 0.0 )",
  9088. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9089. "lVector = normalize( lVector );",
  9090. "#else",
  9091. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  9092. "float lDistance = vSpotLight[ i ].w;",
  9093. "#endif",
  9094. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  9095. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9096. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9097. // diffuse
  9098. "float dotProduct = dot( normal, lVector );",
  9099. "#ifdef WRAP_AROUND",
  9100. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  9101. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9102. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  9103. "#else",
  9104. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  9105. "#endif",
  9106. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  9107. // specular
  9108. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  9109. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  9110. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  9111. "#ifdef PHYSICALLY_BASED_SHADING",
  9112. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9113. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9114. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  9115. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  9116. "#else",
  9117. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  9118. "#endif",
  9119. "}",
  9120. "}",
  9121. "#endif",
  9122. "#if MAX_DIR_LIGHTS > 0",
  9123. "vec3 dirDiffuse = vec3( 0.0 );",
  9124. "vec3 dirSpecular = vec3( 0.0 );" ,
  9125. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9126. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9127. "vec3 dirVector = normalize( lDirection.xyz );",
  9128. // diffuse
  9129. "float dotProduct = dot( normal, dirVector );",
  9130. "#ifdef WRAP_AROUND",
  9131. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  9132. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9133. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  9134. "#else",
  9135. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  9136. "#endif",
  9137. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  9138. // specular
  9139. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  9140. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  9141. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  9142. "#ifdef PHYSICALLY_BASED_SHADING",
  9143. /*
  9144. // fresnel term from skin shader
  9145. "const float F0 = 0.128;",
  9146. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  9147. "float exponential = pow( base, 5.0 );",
  9148. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  9149. */
  9150. /*
  9151. // fresnel term from fresnel shader
  9152. "const float mFresnelBias = 0.08;",
  9153. "const float mFresnelScale = 0.3;",
  9154. "const float mFresnelPower = 5.0;",
  9155. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  9156. */
  9157. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9158. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9159. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  9160. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  9161. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  9162. "#else",
  9163. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  9164. "#endif",
  9165. "}",
  9166. "#endif",
  9167. "#if MAX_HEMI_LIGHTS > 0",
  9168. "vec3 hemiDiffuse = vec3( 0.0 );",
  9169. "vec3 hemiSpecular = vec3( 0.0 );" ,
  9170. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9171. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9172. "vec3 lVector = normalize( lDirection.xyz );",
  9173. // diffuse
  9174. "float dotProduct = dot( normal, lVector );",
  9175. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9176. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9177. "hemiDiffuse += diffuse * hemiColor;",
  9178. // specular (sky light)
  9179. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  9180. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  9181. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  9182. // specular (ground light)
  9183. "vec3 lVectorGround = -lVector;",
  9184. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  9185. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  9186. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  9187. "#ifdef PHYSICALLY_BASED_SHADING",
  9188. "float dotProductGround = dot( normal, lVectorGround );",
  9189. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9190. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9191. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  9192. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  9193. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  9194. "#else",
  9195. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  9196. "#endif",
  9197. "}",
  9198. "#endif",
  9199. "vec3 totalDiffuse = vec3( 0.0 );",
  9200. "vec3 totalSpecular = vec3( 0.0 );",
  9201. "#if MAX_DIR_LIGHTS > 0",
  9202. "totalDiffuse += dirDiffuse;",
  9203. "totalSpecular += dirSpecular;",
  9204. "#endif",
  9205. "#if MAX_HEMI_LIGHTS > 0",
  9206. "totalDiffuse += hemiDiffuse;",
  9207. "totalSpecular += hemiSpecular;",
  9208. "#endif",
  9209. "#if MAX_POINT_LIGHTS > 0",
  9210. "totalDiffuse += pointDiffuse;",
  9211. "totalSpecular += pointSpecular;",
  9212. "#endif",
  9213. "#if MAX_SPOT_LIGHTS > 0",
  9214. "totalDiffuse += spotDiffuse;",
  9215. "totalSpecular += spotSpecular;",
  9216. "#endif",
  9217. "#ifdef METAL",
  9218. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  9219. "#else",
  9220. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  9221. "#endif"
  9222. ].join("\n"),
  9223. // VERTEX COLORS
  9224. color_pars_fragment: [
  9225. "#ifdef USE_COLOR",
  9226. "varying vec3 vColor;",
  9227. "#endif"
  9228. ].join("\n"),
  9229. color_fragment: [
  9230. "#ifdef USE_COLOR",
  9231. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  9232. "#endif"
  9233. ].join("\n"),
  9234. color_pars_vertex: [
  9235. "#ifdef USE_COLOR",
  9236. "varying vec3 vColor;",
  9237. "#endif"
  9238. ].join("\n"),
  9239. color_vertex: [
  9240. "#ifdef USE_COLOR",
  9241. "#ifdef GAMMA_INPUT",
  9242. "vColor = color * color;",
  9243. "#else",
  9244. "vColor = color;",
  9245. "#endif",
  9246. "#endif"
  9247. ].join("\n"),
  9248. // SKINNING
  9249. skinning_pars_vertex: [
  9250. "#ifdef USE_SKINNING",
  9251. "#ifdef BONE_TEXTURE",
  9252. "uniform sampler2D boneTexture;",
  9253. "mat4 getBoneMatrix( const in float i ) {",
  9254. "float j = i * 4.0;",
  9255. "float x = mod( j, N_BONE_PIXEL_X );",
  9256. "float y = floor( j / N_BONE_PIXEL_X );",
  9257. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  9258. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  9259. "y = dy * ( y + 0.5 );",
  9260. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  9261. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  9262. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  9263. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  9264. "mat4 bone = mat4( v1, v2, v3, v4 );",
  9265. "return bone;",
  9266. "}",
  9267. "#else",
  9268. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  9269. "mat4 getBoneMatrix( const in float i ) {",
  9270. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  9271. "return bone;",
  9272. "}",
  9273. "#endif",
  9274. "#endif"
  9275. ].join("\n"),
  9276. skinbase_vertex: [
  9277. "#ifdef USE_SKINNING",
  9278. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  9279. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  9280. "#endif"
  9281. ].join("\n"),
  9282. skinning_vertex: [
  9283. "#ifdef USE_SKINNING",
  9284. "#ifdef USE_MORPHTARGETS",
  9285. "vec4 skinVertex = vec4( morphed, 1.0 );",
  9286. "#else",
  9287. "vec4 skinVertex = vec4( position, 1.0 );",
  9288. "#endif",
  9289. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  9290. "skinned += boneMatY * skinVertex * skinWeight.y;",
  9291. "#endif"
  9292. ].join("\n"),
  9293. // MORPHING
  9294. morphtarget_pars_vertex: [
  9295. "#ifdef USE_MORPHTARGETS",
  9296. "#ifndef USE_MORPHNORMALS",
  9297. "uniform float morphTargetInfluences[ 8 ];",
  9298. "#else",
  9299. "uniform float morphTargetInfluences[ 4 ];",
  9300. "#endif",
  9301. "#endif"
  9302. ].join("\n"),
  9303. morphtarget_vertex: [
  9304. "#ifdef USE_MORPHTARGETS",
  9305. "vec3 morphed = vec3( 0.0 );",
  9306. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  9307. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  9308. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  9309. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  9310. "#ifndef USE_MORPHNORMALS",
  9311. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  9312. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  9313. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  9314. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  9315. "#endif",
  9316. "morphed += position;",
  9317. "#endif"
  9318. ].join("\n"),
  9319. default_vertex : [
  9320. "vec4 mvPosition;",
  9321. "#ifdef USE_SKINNING",
  9322. "mvPosition = modelViewMatrix * skinned;",
  9323. "#endif",
  9324. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  9325. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  9326. "#endif",
  9327. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  9328. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9329. "#endif",
  9330. "gl_Position = projectionMatrix * mvPosition;"
  9331. ].join("\n"),
  9332. morphnormal_vertex: [
  9333. "#ifdef USE_MORPHNORMALS",
  9334. "vec3 morphedNormal = vec3( 0.0 );",
  9335. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  9336. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  9337. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  9338. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  9339. "morphedNormal += normal;",
  9340. "#endif"
  9341. ].join("\n"),
  9342. skinnormal_vertex: [
  9343. "#ifdef USE_SKINNING",
  9344. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  9345. "skinMatrix += skinWeight.y * boneMatY;",
  9346. "#ifdef USE_MORPHNORMALS",
  9347. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  9348. "#else",
  9349. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  9350. "#endif",
  9351. "#endif"
  9352. ].join("\n"),
  9353. defaultnormal_vertex: [
  9354. "vec3 objectNormal;",
  9355. "#ifdef USE_SKINNING",
  9356. "objectNormal = skinnedNormal.xyz;",
  9357. "#endif",
  9358. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  9359. "objectNormal = morphedNormal;",
  9360. "#endif",
  9361. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  9362. "objectNormal = normal;",
  9363. "#endif",
  9364. "#ifdef FLIP_SIDED",
  9365. "objectNormal = -objectNormal;",
  9366. "#endif",
  9367. "vec3 transformedNormal = normalMatrix * objectNormal;"
  9368. ].join("\n"),
  9369. // SHADOW MAP
  9370. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  9371. // http://spidergl.org/example.php?id=6
  9372. // http://fabiensanglard.net/shadowmapping
  9373. shadowmap_pars_fragment: [
  9374. "#ifdef USE_SHADOWMAP",
  9375. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  9376. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  9377. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  9378. "uniform float shadowBias[ MAX_SHADOWS ];",
  9379. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  9380. "float unpackDepth( const in vec4 rgba_depth ) {",
  9381. "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 );",
  9382. "float depth = dot( rgba_depth, bit_shift );",
  9383. "return depth;",
  9384. "}",
  9385. "#endif"
  9386. ].join("\n"),
  9387. shadowmap_fragment: [
  9388. "#ifdef USE_SHADOWMAP",
  9389. "#ifdef SHADOWMAP_DEBUG",
  9390. "vec3 frustumColors[3];",
  9391. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  9392. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  9393. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  9394. "#endif",
  9395. "#ifdef SHADOWMAP_CASCADE",
  9396. "int inFrustumCount = 0;",
  9397. "#endif",
  9398. "float fDepth;",
  9399. "vec3 shadowColor = vec3( 1.0 );",
  9400. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  9401. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  9402. // "if ( something && something )" breaks ATI OpenGL shader compiler
  9403. // "if ( all( something, something ) )" using this instead
  9404. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  9405. "bool inFrustum = all( inFrustumVec );",
  9406. // don't shadow pixels outside of light frustum
  9407. // use just first frustum (for cascades)
  9408. // don't shadow pixels behind far plane of light frustum
  9409. "#ifdef SHADOWMAP_CASCADE",
  9410. "inFrustumCount += int( inFrustum );",
  9411. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  9412. "#else",
  9413. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  9414. "#endif",
  9415. "bool frustumTest = all( frustumTestVec );",
  9416. "if ( frustumTest ) {",
  9417. "shadowCoord.z += shadowBias[ i ];",
  9418. "#if defined( SHADOWMAP_TYPE_PCF )",
  9419. // Percentage-close filtering
  9420. // (9 pixel kernel)
  9421. // http://fabiensanglard.net/shadowmappingPCF/
  9422. "float shadow = 0.0;",
  9423. /*
  9424. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  9425. // must enroll loop manually
  9426. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  9427. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  9428. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  9429. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  9430. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  9431. "float fDepth = unpackDepth( rgbaDepth );",
  9432. "if ( fDepth < shadowCoord.z )",
  9433. "shadow += 1.0;",
  9434. "}",
  9435. "shadow /= 9.0;",
  9436. */
  9437. "const float shadowDelta = 1.0 / 9.0;",
  9438. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  9439. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  9440. "float dx0 = -1.25 * xPixelOffset;",
  9441. "float dy0 = -1.25 * yPixelOffset;",
  9442. "float dx1 = 1.25 * xPixelOffset;",
  9443. "float dy1 = 1.25 * yPixelOffset;",
  9444. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  9445. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9446. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  9447. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9448. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  9449. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9450. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  9451. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9452. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  9453. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9454. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  9455. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9456. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  9457. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9458. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  9459. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9460. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  9461. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9462. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  9463. "#elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  9464. // Percentage-close filtering
  9465. // (9 pixel kernel)
  9466. // http://fabiensanglard.net/shadowmappingPCF/
  9467. "float shadow = 0.0;",
  9468. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  9469. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  9470. "float dx0 = -1.0 * xPixelOffset;",
  9471. "float dy0 = -1.0 * yPixelOffset;",
  9472. "float dx1 = 1.0 * xPixelOffset;",
  9473. "float dy1 = 1.0 * yPixelOffset;",
  9474. "mat3 shadowKernel;",
  9475. "mat3 depthKernel;",
  9476. "depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  9477. "if ( depthKernel[0][0] < shadowCoord.z ) shadowKernel[0][0] = 0.25;",
  9478. "else shadowKernel[0][0] = 0.0;",
  9479. "depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  9480. "if ( depthKernel[0][1] < shadowCoord.z ) shadowKernel[0][1] = 0.25;",
  9481. "else shadowKernel[0][1] = 0.0;",
  9482. "depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  9483. "if ( depthKernel[0][2] < shadowCoord.z ) shadowKernel[0][2] = 0.25;",
  9484. "else shadowKernel[0][2] = 0.0;",
  9485. "depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  9486. "if ( depthKernel[1][0] < shadowCoord.z ) shadowKernel[1][0] = 0.25;",
  9487. "else shadowKernel[1][0] = 0.0;",
  9488. "depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  9489. "if ( depthKernel[1][1] < shadowCoord.z ) shadowKernel[1][1] = 0.25;",
  9490. "else shadowKernel[1][1] = 0.0;",
  9491. "depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  9492. "if ( depthKernel[1][2] < shadowCoord.z ) shadowKernel[1][2] = 0.25;",
  9493. "else shadowKernel[1][2] = 0.0;",
  9494. "depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  9495. "if ( depthKernel[2][0] < shadowCoord.z ) shadowKernel[2][0] = 0.25;",
  9496. "else shadowKernel[2][0] = 0.0;",
  9497. "depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  9498. "if ( depthKernel[2][1] < shadowCoord.z ) shadowKernel[2][1] = 0.25;",
  9499. "else shadowKernel[2][1] = 0.0;",
  9500. "depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  9501. "if ( depthKernel[2][2] < shadowCoord.z ) shadowKernel[2][2] = 0.25;",
  9502. "else shadowKernel[2][2] = 0.0;",
  9503. "vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  9504. "shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  9505. "shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  9506. "vec4 shadowValues;",
  9507. "shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  9508. "shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  9509. "shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  9510. "shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  9511. "shadow = dot( shadowValues, vec4( 1.0 ) );",
  9512. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  9513. "#else",
  9514. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  9515. "float fDepth = unpackDepth( rgbaDepth );",
  9516. "if ( fDepth < shadowCoord.z )",
  9517. // spot with multiple shadows is darker
  9518. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  9519. // spot with multiple shadows has the same color as single shadow spot
  9520. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  9521. "#endif",
  9522. "}",
  9523. "#ifdef SHADOWMAP_DEBUG",
  9524. "#ifdef SHADOWMAP_CASCADE",
  9525. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  9526. "#else",
  9527. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  9528. "#endif",
  9529. "#endif",
  9530. "}",
  9531. "#ifdef GAMMA_OUTPUT",
  9532. "shadowColor *= shadowColor;",
  9533. "#endif",
  9534. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  9535. "#endif"
  9536. ].join("\n"),
  9537. shadowmap_pars_vertex: [
  9538. "#ifdef USE_SHADOWMAP",
  9539. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  9540. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  9541. "#endif"
  9542. ].join("\n"),
  9543. shadowmap_vertex: [
  9544. "#ifdef USE_SHADOWMAP",
  9545. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  9546. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  9547. "}",
  9548. "#endif"
  9549. ].join("\n"),
  9550. // ALPHATEST
  9551. alphatest_fragment: [
  9552. "#ifdef ALPHATEST",
  9553. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  9554. "#endif"
  9555. ].join("\n"),
  9556. // LINEAR SPACE
  9557. linear_to_gamma_fragment: [
  9558. "#ifdef GAMMA_OUTPUT",
  9559. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  9560. "#endif"
  9561. ].join("\n")
  9562. };
  9563. THREE.UniformsUtils = {
  9564. merge: function ( uniforms ) {
  9565. var u, p, tmp, merged = {};
  9566. for ( u = 0; u < uniforms.length; u ++ ) {
  9567. tmp = this.clone( uniforms[ u ] );
  9568. for ( p in tmp ) {
  9569. merged[ p ] = tmp[ p ];
  9570. }
  9571. }
  9572. return merged;
  9573. },
  9574. clone: function ( uniforms_src ) {
  9575. var u, p, parameter, parameter_src, uniforms_dst = {};
  9576. for ( u in uniforms_src ) {
  9577. uniforms_dst[ u ] = {};
  9578. for ( p in uniforms_src[ u ] ) {
  9579. parameter_src = uniforms_src[ u ][ p ];
  9580. if ( parameter_src instanceof THREE.Color ||
  9581. parameter_src instanceof THREE.Vector2 ||
  9582. parameter_src instanceof THREE.Vector3 ||
  9583. parameter_src instanceof THREE.Vector4 ||
  9584. parameter_src instanceof THREE.Matrix4 ||
  9585. parameter_src instanceof THREE.Texture ) {
  9586. uniforms_dst[ u ][ p ] = parameter_src.clone();
  9587. } else if ( parameter_src instanceof Array ) {
  9588. uniforms_dst[ u ][ p ] = parameter_src.slice();
  9589. } else {
  9590. uniforms_dst[ u ][ p ] = parameter_src;
  9591. }
  9592. }
  9593. }
  9594. return uniforms_dst;
  9595. }
  9596. };
  9597. THREE.UniformsLib = {
  9598. common: {
  9599. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9600. "opacity" : { type: "f", value: 1.0 },
  9601. "map" : { type: "t", value: null },
  9602. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  9603. "lightMap" : { type: "t", value: null },
  9604. "specularMap" : { type: "t", value: null },
  9605. "envMap" : { type: "t", value: null },
  9606. "flipEnvMap" : { type: "f", value: -1 },
  9607. "useRefract" : { type: "i", value: 0 },
  9608. "reflectivity" : { type: "f", value: 1.0 },
  9609. "refractionRatio" : { type: "f", value: 0.98 },
  9610. "combine" : { type: "i", value: 0 },
  9611. "morphTargetInfluences" : { type: "f", value: 0 }
  9612. },
  9613. bump: {
  9614. "bumpMap" : { type: "t", value: null },
  9615. "bumpScale" : { type: "f", value: 1 }
  9616. },
  9617. normalmap: {
  9618. "normalMap" : { type: "t", value: null },
  9619. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  9620. },
  9621. fog : {
  9622. "fogDensity" : { type: "f", value: 0.00025 },
  9623. "fogNear" : { type: "f", value: 1 },
  9624. "fogFar" : { type: "f", value: 2000 },
  9625. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9626. },
  9627. lights: {
  9628. "ambientLightColor" : { type: "fv", value: [] },
  9629. "directionalLightDirection" : { type: "fv", value: [] },
  9630. "directionalLightColor" : { type: "fv", value: [] },
  9631. "hemisphereLightDirection" : { type: "fv", value: [] },
  9632. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  9633. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  9634. "pointLightColor" : { type: "fv", value: [] },
  9635. "pointLightPosition" : { type: "fv", value: [] },
  9636. "pointLightDistance" : { type: "fv1", value: [] },
  9637. "spotLightColor" : { type: "fv", value: [] },
  9638. "spotLightPosition" : { type: "fv", value: [] },
  9639. "spotLightDirection" : { type: "fv", value: [] },
  9640. "spotLightDistance" : { type: "fv1", value: [] },
  9641. "spotLightAngleCos" : { type: "fv1", value: [] },
  9642. "spotLightExponent" : { type: "fv1", value: [] }
  9643. },
  9644. particle: {
  9645. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9646. "opacity" : { type: "f", value: 1.0 },
  9647. "size" : { type: "f", value: 1.0 },
  9648. "scale" : { type: "f", value: 1.0 },
  9649. "map" : { type: "t", value: null },
  9650. "fogDensity" : { type: "f", value: 0.00025 },
  9651. "fogNear" : { type: "f", value: 1 },
  9652. "fogFar" : { type: "f", value: 2000 },
  9653. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9654. },
  9655. shadowmap: {
  9656. "shadowMap": { type: "tv", value: [] },
  9657. "shadowMapSize": { type: "v2v", value: [] },
  9658. "shadowBias" : { type: "fv1", value: [] },
  9659. "shadowDarkness": { type: "fv1", value: [] },
  9660. "shadowMatrix" : { type: "m4v", value: [] }
  9661. }
  9662. };
  9663. THREE.ShaderLib = {
  9664. 'depth': {
  9665. uniforms: {
  9666. "mNear": { type: "f", value: 1.0 },
  9667. "mFar" : { type: "f", value: 2000.0 },
  9668. "opacity" : { type: "f", value: 1.0 }
  9669. },
  9670. vertexShader: [
  9671. "void main() {",
  9672. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  9673. "}"
  9674. ].join("\n"),
  9675. fragmentShader: [
  9676. "uniform float mNear;",
  9677. "uniform float mFar;",
  9678. "uniform float opacity;",
  9679. "void main() {",
  9680. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  9681. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  9682. "gl_FragColor = vec4( vec3( color ), opacity );",
  9683. "}"
  9684. ].join("\n")
  9685. },
  9686. 'normal': {
  9687. uniforms: {
  9688. "opacity" : { type: "f", value: 1.0 }
  9689. },
  9690. vertexShader: [
  9691. "varying vec3 vNormal;",
  9692. "void main() {",
  9693. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9694. "vNormal = normalize( normalMatrix * normal );",
  9695. "gl_Position = projectionMatrix * mvPosition;",
  9696. "}"
  9697. ].join("\n"),
  9698. fragmentShader: [
  9699. "uniform float opacity;",
  9700. "varying vec3 vNormal;",
  9701. "void main() {",
  9702. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  9703. "}"
  9704. ].join("\n")
  9705. },
  9706. 'basic': {
  9707. uniforms: THREE.UniformsUtils.merge( [
  9708. THREE.UniformsLib[ "common" ],
  9709. THREE.UniformsLib[ "fog" ],
  9710. THREE.UniformsLib[ "shadowmap" ]
  9711. ] ),
  9712. vertexShader: [
  9713. THREE.ShaderChunk[ "map_pars_vertex" ],
  9714. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9715. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9716. THREE.ShaderChunk[ "color_pars_vertex" ],
  9717. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9718. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9719. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9720. "void main() {",
  9721. THREE.ShaderChunk[ "map_vertex" ],
  9722. THREE.ShaderChunk[ "lightmap_vertex" ],
  9723. THREE.ShaderChunk[ "color_vertex" ],
  9724. THREE.ShaderChunk[ "skinbase_vertex" ],
  9725. "#ifdef USE_ENVMAP",
  9726. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9727. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9728. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9729. "#endif",
  9730. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9731. THREE.ShaderChunk[ "skinning_vertex" ],
  9732. THREE.ShaderChunk[ "default_vertex" ],
  9733. THREE.ShaderChunk[ "worldpos_vertex" ],
  9734. THREE.ShaderChunk[ "envmap_vertex" ],
  9735. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9736. "}"
  9737. ].join("\n"),
  9738. fragmentShader: [
  9739. "uniform vec3 diffuse;",
  9740. "uniform float opacity;",
  9741. THREE.ShaderChunk[ "color_pars_fragment" ],
  9742. THREE.ShaderChunk[ "map_pars_fragment" ],
  9743. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9744. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9745. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9746. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9747. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9748. "void main() {",
  9749. "gl_FragColor = vec4( diffuse, opacity );",
  9750. THREE.ShaderChunk[ "map_fragment" ],
  9751. THREE.ShaderChunk[ "alphatest_fragment" ],
  9752. THREE.ShaderChunk[ "specularmap_fragment" ],
  9753. THREE.ShaderChunk[ "lightmap_fragment" ],
  9754. THREE.ShaderChunk[ "color_fragment" ],
  9755. THREE.ShaderChunk[ "envmap_fragment" ],
  9756. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9757. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9758. THREE.ShaderChunk[ "fog_fragment" ],
  9759. "}"
  9760. ].join("\n")
  9761. },
  9762. 'lambert': {
  9763. uniforms: THREE.UniformsUtils.merge( [
  9764. THREE.UniformsLib[ "common" ],
  9765. THREE.UniformsLib[ "fog" ],
  9766. THREE.UniformsLib[ "lights" ],
  9767. THREE.UniformsLib[ "shadowmap" ],
  9768. {
  9769. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9770. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9771. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9772. }
  9773. ] ),
  9774. vertexShader: [
  9775. "#define LAMBERT",
  9776. "varying vec3 vLightFront;",
  9777. "#ifdef DOUBLE_SIDED",
  9778. "varying vec3 vLightBack;",
  9779. "#endif",
  9780. THREE.ShaderChunk[ "map_pars_vertex" ],
  9781. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9782. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9783. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  9784. THREE.ShaderChunk[ "color_pars_vertex" ],
  9785. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9786. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9787. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9788. "void main() {",
  9789. THREE.ShaderChunk[ "map_vertex" ],
  9790. THREE.ShaderChunk[ "lightmap_vertex" ],
  9791. THREE.ShaderChunk[ "color_vertex" ],
  9792. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9793. THREE.ShaderChunk[ "skinbase_vertex" ],
  9794. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9795. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9796. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9797. THREE.ShaderChunk[ "skinning_vertex" ],
  9798. THREE.ShaderChunk[ "default_vertex" ],
  9799. THREE.ShaderChunk[ "worldpos_vertex" ],
  9800. THREE.ShaderChunk[ "envmap_vertex" ],
  9801. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  9802. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9803. "}"
  9804. ].join("\n"),
  9805. fragmentShader: [
  9806. "uniform float opacity;",
  9807. "varying vec3 vLightFront;",
  9808. "#ifdef DOUBLE_SIDED",
  9809. "varying vec3 vLightBack;",
  9810. "#endif",
  9811. THREE.ShaderChunk[ "color_pars_fragment" ],
  9812. THREE.ShaderChunk[ "map_pars_fragment" ],
  9813. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9814. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9815. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9816. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9817. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9818. "void main() {",
  9819. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  9820. THREE.ShaderChunk[ "map_fragment" ],
  9821. THREE.ShaderChunk[ "alphatest_fragment" ],
  9822. THREE.ShaderChunk[ "specularmap_fragment" ],
  9823. "#ifdef DOUBLE_SIDED",
  9824. //"float isFront = float( gl_FrontFacing );",
  9825. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  9826. "if ( gl_FrontFacing )",
  9827. "gl_FragColor.xyz *= vLightFront;",
  9828. "else",
  9829. "gl_FragColor.xyz *= vLightBack;",
  9830. "#else",
  9831. "gl_FragColor.xyz *= vLightFront;",
  9832. "#endif",
  9833. THREE.ShaderChunk[ "lightmap_fragment" ],
  9834. THREE.ShaderChunk[ "color_fragment" ],
  9835. THREE.ShaderChunk[ "envmap_fragment" ],
  9836. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9837. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9838. THREE.ShaderChunk[ "fog_fragment" ],
  9839. "}"
  9840. ].join("\n")
  9841. },
  9842. 'phong': {
  9843. uniforms: THREE.UniformsUtils.merge( [
  9844. THREE.UniformsLib[ "common" ],
  9845. THREE.UniformsLib[ "bump" ],
  9846. THREE.UniformsLib[ "normalmap" ],
  9847. THREE.UniformsLib[ "fog" ],
  9848. THREE.UniformsLib[ "lights" ],
  9849. THREE.UniformsLib[ "shadowmap" ],
  9850. {
  9851. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9852. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9853. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  9854. "shininess": { type: "f", value: 30 },
  9855. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9856. }
  9857. ] ),
  9858. vertexShader: [
  9859. "#define PHONG",
  9860. "varying vec3 vViewPosition;",
  9861. "varying vec3 vNormal;",
  9862. THREE.ShaderChunk[ "map_pars_vertex" ],
  9863. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9864. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9865. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  9866. THREE.ShaderChunk[ "color_pars_vertex" ],
  9867. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9868. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9869. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9870. "void main() {",
  9871. THREE.ShaderChunk[ "map_vertex" ],
  9872. THREE.ShaderChunk[ "lightmap_vertex" ],
  9873. THREE.ShaderChunk[ "color_vertex" ],
  9874. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9875. THREE.ShaderChunk[ "skinbase_vertex" ],
  9876. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9877. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9878. "vNormal = normalize( transformedNormal );",
  9879. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9880. THREE.ShaderChunk[ "skinning_vertex" ],
  9881. THREE.ShaderChunk[ "default_vertex" ],
  9882. "vViewPosition = -mvPosition.xyz;",
  9883. THREE.ShaderChunk[ "worldpos_vertex" ],
  9884. THREE.ShaderChunk[ "envmap_vertex" ],
  9885. THREE.ShaderChunk[ "lights_phong_vertex" ],
  9886. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9887. "}"
  9888. ].join("\n"),
  9889. fragmentShader: [
  9890. "uniform vec3 diffuse;",
  9891. "uniform float opacity;",
  9892. "uniform vec3 ambient;",
  9893. "uniform vec3 emissive;",
  9894. "uniform vec3 specular;",
  9895. "uniform float shininess;",
  9896. THREE.ShaderChunk[ "color_pars_fragment" ],
  9897. THREE.ShaderChunk[ "map_pars_fragment" ],
  9898. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9899. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9900. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9901. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  9902. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9903. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  9904. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  9905. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9906. "void main() {",
  9907. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  9908. THREE.ShaderChunk[ "map_fragment" ],
  9909. THREE.ShaderChunk[ "alphatest_fragment" ],
  9910. THREE.ShaderChunk[ "specularmap_fragment" ],
  9911. THREE.ShaderChunk[ "lights_phong_fragment" ],
  9912. THREE.ShaderChunk[ "lightmap_fragment" ],
  9913. THREE.ShaderChunk[ "color_fragment" ],
  9914. THREE.ShaderChunk[ "envmap_fragment" ],
  9915. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9916. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9917. THREE.ShaderChunk[ "fog_fragment" ],
  9918. "}"
  9919. ].join("\n")
  9920. },
  9921. 'particle_basic': {
  9922. uniforms: THREE.UniformsUtils.merge( [
  9923. THREE.UniformsLib[ "particle" ],
  9924. THREE.UniformsLib[ "shadowmap" ]
  9925. ] ),
  9926. vertexShader: [
  9927. "uniform float size;",
  9928. "uniform float scale;",
  9929. THREE.ShaderChunk[ "color_pars_vertex" ],
  9930. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9931. "void main() {",
  9932. THREE.ShaderChunk[ "color_vertex" ],
  9933. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9934. "#ifdef USE_SIZEATTENUATION",
  9935. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  9936. "#else",
  9937. "gl_PointSize = size;",
  9938. "#endif",
  9939. "gl_Position = projectionMatrix * mvPosition;",
  9940. THREE.ShaderChunk[ "worldpos_vertex" ],
  9941. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9942. "}"
  9943. ].join("\n"),
  9944. fragmentShader: [
  9945. "uniform vec3 psColor;",
  9946. "uniform float opacity;",
  9947. THREE.ShaderChunk[ "color_pars_fragment" ],
  9948. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  9949. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9950. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9951. "void main() {",
  9952. "gl_FragColor = vec4( psColor, opacity );",
  9953. THREE.ShaderChunk[ "map_particle_fragment" ],
  9954. THREE.ShaderChunk[ "alphatest_fragment" ],
  9955. THREE.ShaderChunk[ "color_fragment" ],
  9956. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9957. THREE.ShaderChunk[ "fog_fragment" ],
  9958. "}"
  9959. ].join("\n")
  9960. },
  9961. 'dashed': {
  9962. uniforms: THREE.UniformsUtils.merge( [
  9963. THREE.UniformsLib[ "common" ],
  9964. THREE.UniformsLib[ "fog" ],
  9965. {
  9966. "scale": { type: "f", value: 1 },
  9967. "dashSize": { type: "f", value: 1 },
  9968. "totalSize": { type: "f", value: 2 }
  9969. }
  9970. ] ),
  9971. vertexShader: [
  9972. "uniform float scale;",
  9973. "attribute float lineDistance;",
  9974. "varying float vLineDistance;",
  9975. THREE.ShaderChunk[ "color_pars_vertex" ],
  9976. "void main() {",
  9977. THREE.ShaderChunk[ "color_vertex" ],
  9978. "vLineDistance = scale * lineDistance;",
  9979. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9980. "gl_Position = projectionMatrix * mvPosition;",
  9981. "}"
  9982. ].join("\n"),
  9983. fragmentShader: [
  9984. "uniform vec3 diffuse;",
  9985. "uniform float opacity;",
  9986. "uniform float dashSize;",
  9987. "uniform float totalSize;",
  9988. "varying float vLineDistance;",
  9989. THREE.ShaderChunk[ "color_pars_fragment" ],
  9990. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9991. "void main() {",
  9992. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  9993. "discard;",
  9994. "}",
  9995. "gl_FragColor = vec4( diffuse, opacity );",
  9996. THREE.ShaderChunk[ "color_fragment" ],
  9997. THREE.ShaderChunk[ "fog_fragment" ],
  9998. "}"
  9999. ].join("\n")
  10000. },
  10001. // Depth encoding into RGBA texture
  10002. // based on SpiderGL shadow map example
  10003. // http://spidergl.org/example.php?id=6
  10004. // originally from
  10005. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  10006. // see also here:
  10007. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  10008. 'depthRGBA': {
  10009. uniforms: {},
  10010. vertexShader: [
  10011. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10012. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10013. "void main() {",
  10014. THREE.ShaderChunk[ "skinbase_vertex" ],
  10015. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10016. THREE.ShaderChunk[ "skinning_vertex" ],
  10017. THREE.ShaderChunk[ "default_vertex" ],
  10018. "}"
  10019. ].join("\n"),
  10020. fragmentShader: [
  10021. "vec4 pack_depth( const in float depth ) {",
  10022. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  10023. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  10024. "vec4 res = fract( depth * bit_shift );",
  10025. "res -= res.xxyz * bit_mask;",
  10026. "return res;",
  10027. "}",
  10028. "void main() {",
  10029. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  10030. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  10031. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  10032. //"gl_FragData[ 0 ] = pack_depth( z );",
  10033. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  10034. "}"
  10035. ].join("\n")
  10036. }
  10037. };
  10038. /**
  10039. * @author supereggbert / http://www.paulbrunt.co.uk/
  10040. * @author mrdoob / http://mrdoob.com/
  10041. * @author alteredq / http://alteredqualia.com/
  10042. * @author szimek / https://github.com/szimek/
  10043. */
  10044. THREE.WebGLRenderer = function ( parameters ) {
  10045. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  10046. parameters = parameters || {};
  10047. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  10048. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  10049. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  10050. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  10051. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  10052. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  10053. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  10054. _clearColor = parameters.clearColor !== undefined ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ),
  10055. _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0;
  10056. // public properties
  10057. this.domElement = _canvas;
  10058. this.context = null;
  10059. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  10060. ? parameters.devicePixelRatio
  10061. : window.devicePixelRatio !== undefined
  10062. ? window.devicePixelRatio
  10063. : 1;
  10064. // clearing
  10065. this.autoClear = true;
  10066. this.autoClearColor = true;
  10067. this.autoClearDepth = true;
  10068. this.autoClearStencil = true;
  10069. // scene graph
  10070. this.sortObjects = true;
  10071. this.autoUpdateObjects = true;
  10072. this.autoUpdateScene = true;
  10073. // physically based shading
  10074. this.gammaInput = false;
  10075. this.gammaOutput = false;
  10076. this.physicallyBasedShading = false;
  10077. // shadow map
  10078. this.shadowMapEnabled = false;
  10079. this.shadowMapAutoUpdate = true;
  10080. this.shadowMapType = THREE.PCFShadowMap;
  10081. this.shadowMapCullFace = THREE.CullFaceFront;
  10082. this.shadowMapDebug = false;
  10083. this.shadowMapCascade = false;
  10084. // morphs
  10085. this.maxMorphTargets = 8;
  10086. this.maxMorphNormals = 4;
  10087. // flags
  10088. this.autoScaleCubemaps = true;
  10089. // custom render plugins
  10090. this.renderPluginsPre = [];
  10091. this.renderPluginsPost = [];
  10092. // info
  10093. this.info = {
  10094. memory: {
  10095. programs: 0,
  10096. geometries: 0,
  10097. textures: 0
  10098. },
  10099. render: {
  10100. calls: 0,
  10101. vertices: 0,
  10102. faces: 0,
  10103. points: 0
  10104. }
  10105. };
  10106. // internal properties
  10107. var _this = this,
  10108. _programs = [],
  10109. _programs_counter = 0,
  10110. // internal state cache
  10111. _currentProgram = null,
  10112. _currentFramebuffer = null,
  10113. _currentMaterialId = -1,
  10114. _currentGeometryGroupHash = null,
  10115. _currentCamera = null,
  10116. _geometryGroupCounter = 0,
  10117. _usedTextureUnits = 0,
  10118. // GL state cache
  10119. _oldDoubleSided = -1,
  10120. _oldFlipSided = -1,
  10121. _oldBlending = -1,
  10122. _oldBlendEquation = -1,
  10123. _oldBlendSrc = -1,
  10124. _oldBlendDst = -1,
  10125. _oldDepthTest = -1,
  10126. _oldDepthWrite = -1,
  10127. _oldPolygonOffset = null,
  10128. _oldPolygonOffsetFactor = null,
  10129. _oldPolygonOffsetUnits = null,
  10130. _oldLineWidth = null,
  10131. _viewportX = 0,
  10132. _viewportY = 0,
  10133. _viewportWidth = 0,
  10134. _viewportHeight = 0,
  10135. _currentWidth = 0,
  10136. _currentHeight = 0,
  10137. _enabledAttributes = {},
  10138. // frustum
  10139. _frustum = new THREE.Frustum(),
  10140. // camera matrices cache
  10141. _projScreenMatrix = new THREE.Matrix4(),
  10142. _projScreenMatrixPS = new THREE.Matrix4(),
  10143. _vector3 = new THREE.Vector3(),
  10144. // light arrays cache
  10145. _direction = new THREE.Vector3(),
  10146. _lightsNeedUpdate = true,
  10147. _lights = {
  10148. ambient: [ 0, 0, 0 ],
  10149. directional: { length: 0, colors: new Array(), positions: new Array() },
  10150. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  10151. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  10152. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  10153. };
  10154. // initialize
  10155. var _gl;
  10156. var _glExtensionTextureFloat;
  10157. var _glExtensionStandardDerivatives;
  10158. var _glExtensionTextureFilterAnisotropic;
  10159. var _glExtensionCompressedTextureS3TC;
  10160. initGL();
  10161. setDefaultGLState();
  10162. this.context = _gl;
  10163. // GPU capabilities
  10164. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  10165. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  10166. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  10167. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  10168. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  10169. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  10170. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  10171. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  10172. //
  10173. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  10174. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  10175. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  10176. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  10177. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  10178. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  10179. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  10180. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  10181. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  10182. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  10183. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  10184. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  10185. // clamp precision to maximum available
  10186. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  10187. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  10188. if ( _precision === "highp" && ! highpAvailable ) {
  10189. if ( mediumpAvailable ) {
  10190. _precision = "mediump";
  10191. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  10192. } else {
  10193. _precision = "lowp";
  10194. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  10195. }
  10196. }
  10197. if ( _precision === "mediump" && ! mediumpAvailable ) {
  10198. _precision = "lowp";
  10199. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  10200. }
  10201. // API
  10202. this.getContext = function () {
  10203. return _gl;
  10204. };
  10205. this.supportsVertexTextures = function () {
  10206. return _supportsVertexTextures;
  10207. };
  10208. this.supportsFloatTextures = function () {
  10209. return _glExtensionTextureFloat;
  10210. };
  10211. this.supportsStandardDerivatives = function () {
  10212. return _glExtensionStandardDerivatives;
  10213. };
  10214. this.supportsCompressedTextureS3TC = function () {
  10215. return _glExtensionCompressedTextureS3TC;
  10216. };
  10217. this.getMaxAnisotropy = function () {
  10218. return _maxAnisotropy;
  10219. };
  10220. this.getPrecision = function () {
  10221. return _precision;
  10222. };
  10223. this.setSize = function ( width, height ) {
  10224. _canvas.width = width * this.devicePixelRatio;
  10225. _canvas.height = height * this.devicePixelRatio;
  10226. _canvas.style.width = width + 'px';
  10227. _canvas.style.height = height + 'px';
  10228. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  10229. };
  10230. this.setViewport = function ( x, y, width, height ) {
  10231. _viewportX = x !== undefined ? x : 0;
  10232. _viewportY = y !== undefined ? y : 0;
  10233. _viewportWidth = width !== undefined ? width : _canvas.width;
  10234. _viewportHeight = height !== undefined ? height : _canvas.height;
  10235. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  10236. };
  10237. this.setScissor = function ( x, y, width, height ) {
  10238. _gl.scissor( x, y, width, height );
  10239. };
  10240. this.enableScissorTest = function ( enable ) {
  10241. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  10242. };
  10243. // Clearing
  10244. this.setClearColorHex = function ( hex, alpha ) {
  10245. _clearColor.setHex( hex );
  10246. _clearAlpha = alpha;
  10247. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  10248. };
  10249. this.setClearColor = function ( color, alpha ) {
  10250. _clearColor.copy( color );
  10251. _clearAlpha = alpha;
  10252. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  10253. };
  10254. this.getClearColor = function () {
  10255. return _clearColor;
  10256. };
  10257. this.getClearAlpha = function () {
  10258. return _clearAlpha;
  10259. };
  10260. this.clear = function ( color, depth, stencil ) {
  10261. var bits = 0;
  10262. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  10263. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  10264. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  10265. _gl.clear( bits );
  10266. };
  10267. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  10268. this.setRenderTarget( renderTarget );
  10269. this.clear( color, depth, stencil );
  10270. };
  10271. // Plugins
  10272. this.addPostPlugin = function ( plugin ) {
  10273. plugin.init( this );
  10274. this.renderPluginsPost.push( plugin );
  10275. };
  10276. this.addPrePlugin = function ( plugin ) {
  10277. plugin.init( this );
  10278. this.renderPluginsPre.push( plugin );
  10279. };
  10280. // Rendering
  10281. this.updateShadowMap = function ( scene, camera ) {
  10282. _currentProgram = null;
  10283. _oldBlending = -1;
  10284. _oldDepthTest = -1;
  10285. _oldDepthWrite = -1;
  10286. _currentGeometryGroupHash = -1;
  10287. _currentMaterialId = -1;
  10288. _lightsNeedUpdate = true;
  10289. _oldDoubleSided = -1;
  10290. _oldFlipSided = -1;
  10291. this.shadowMapPlugin.update( scene, camera );
  10292. };
  10293. // Internal functions
  10294. // Buffer allocation
  10295. function createParticleBuffers ( geometry ) {
  10296. geometry.__webglVertexBuffer = _gl.createBuffer();
  10297. geometry.__webglColorBuffer = _gl.createBuffer();
  10298. _this.info.memory.geometries ++;
  10299. };
  10300. function createLineBuffers ( geometry ) {
  10301. geometry.__webglVertexBuffer = _gl.createBuffer();
  10302. geometry.__webglColorBuffer = _gl.createBuffer();
  10303. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  10304. _this.info.memory.geometries ++;
  10305. };
  10306. function createRibbonBuffers ( geometry ) {
  10307. geometry.__webglVertexBuffer = _gl.createBuffer();
  10308. geometry.__webglColorBuffer = _gl.createBuffer();
  10309. geometry.__webglNormalBuffer = _gl.createBuffer();
  10310. _this.info.memory.geometries ++;
  10311. };
  10312. function createMeshBuffers ( geometryGroup ) {
  10313. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  10314. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  10315. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  10316. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  10317. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  10318. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  10319. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  10320. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  10321. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  10322. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  10323. var m, ml;
  10324. if ( geometryGroup.numMorphTargets ) {
  10325. geometryGroup.__webglMorphTargetsBuffers = [];
  10326. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10327. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  10328. }
  10329. }
  10330. if ( geometryGroup.numMorphNormals ) {
  10331. geometryGroup.__webglMorphNormalsBuffers = [];
  10332. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10333. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  10334. }
  10335. }
  10336. _this.info.memory.geometries ++;
  10337. };
  10338. // Events
  10339. var onGeometryDispose = function ( event ) {
  10340. var geometry = event.target;
  10341. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10342. deallocateGeometry( geometry );
  10343. _this.info.memory.geometries --;
  10344. };
  10345. var onTextureDispose = function ( event ) {
  10346. var texture = event.target;
  10347. texture.removeEventListener( 'dispose', onTextureDispose );
  10348. deallocateTexture( texture );
  10349. _this.info.memory.textures --;
  10350. };
  10351. var onRenderTargetDispose = function ( event ) {
  10352. var renderTarget = event.target;
  10353. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  10354. deallocateRenderTarget( renderTarget );
  10355. _this.info.memory.textures --;
  10356. };
  10357. var onMaterialDispose = function ( event ) {
  10358. var material = event.target;
  10359. material.removeEventListener( 'dispose', onMaterialDispose );
  10360. deallocateMaterial( material );
  10361. };
  10362. // Buffer deallocation
  10363. var deallocateGeometry = function ( geometry ) {
  10364. geometry.__webglInit = undefined;
  10365. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10366. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  10367. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  10368. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  10369. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  10370. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  10371. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  10372. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  10373. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  10374. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  10375. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  10376. // geometry groups
  10377. if ( geometry.geometryGroups !== undefined ) {
  10378. for ( var g in geometry.geometryGroups ) {
  10379. var geometryGroup = geometry.geometryGroups[ g ];
  10380. if ( geometryGroup.numMorphTargets !== undefined ) {
  10381. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10382. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  10383. }
  10384. }
  10385. if ( geometryGroup.numMorphNormals !== undefined ) {
  10386. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10387. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  10388. }
  10389. }
  10390. deleteCustomAttributesBuffers( geometryGroup );
  10391. }
  10392. }
  10393. deleteCustomAttributesBuffers( geometry );
  10394. };
  10395. var deallocateTexture = function ( texture ) {
  10396. if ( texture.image && texture.image.__webglTextureCube ) {
  10397. // cube texture
  10398. _gl.deleteTexture( texture.image.__webglTextureCube );
  10399. } else {
  10400. // 2D texture
  10401. if ( ! texture.__webglInit ) return;
  10402. texture.__webglInit = false;
  10403. _gl.deleteTexture( texture.__webglTexture );
  10404. }
  10405. };
  10406. var deallocateRenderTarget = function ( renderTarget ) {
  10407. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  10408. _gl.deleteTexture( renderTarget.__webglTexture );
  10409. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  10410. for ( var i = 0; i < 6; i ++ ) {
  10411. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  10412. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  10413. }
  10414. } else {
  10415. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  10416. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  10417. }
  10418. };
  10419. var deallocateMaterial = function ( material ) {
  10420. var program = material.program;
  10421. if ( program === undefined ) return;
  10422. material.program = undefined;
  10423. // only deallocate GL program if this was the last use of shared program
  10424. // assumed there is only single copy of any program in the _programs list
  10425. // (that's how it's constructed)
  10426. var i, il, programInfo;
  10427. var deleteProgram = false;
  10428. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  10429. programInfo = _programs[ i ];
  10430. if ( programInfo.program === program ) {
  10431. programInfo.usedTimes --;
  10432. if ( programInfo.usedTimes === 0 ) {
  10433. deleteProgram = true;
  10434. }
  10435. break;
  10436. }
  10437. }
  10438. if ( deleteProgram === true ) {
  10439. // avoid using array.splice, this is costlier than creating new array from scratch
  10440. var newPrograms = [];
  10441. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  10442. programInfo = _programs[ i ];
  10443. if ( programInfo.program !== program ) {
  10444. newPrograms.push( programInfo );
  10445. }
  10446. }
  10447. _programs = newPrograms;
  10448. _gl.deleteProgram( program );
  10449. _this.info.memory.programs --;
  10450. }
  10451. };
  10452. //
  10453. /*
  10454. function deleteParticleBuffers ( geometry ) {
  10455. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10456. _gl.deleteBuffer( geometry.__webglColorBuffer );
  10457. deleteCustomAttributesBuffers( geometry );
  10458. _this.info.memory.geometries --;
  10459. };
  10460. function deleteLineBuffers ( geometry ) {
  10461. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10462. _gl.deleteBuffer( geometry.__webglColorBuffer );
  10463. _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  10464. deleteCustomAttributesBuffers( geometry );
  10465. _this.info.memory.geometries --;
  10466. };
  10467. function deleteRibbonBuffers ( geometry ) {
  10468. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10469. _gl.deleteBuffer( geometry.__webglColorBuffer );
  10470. _gl.deleteBuffer( geometry.__webglNormalBuffer );
  10471. deleteCustomAttributesBuffers( geometry );
  10472. _this.info.memory.geometries --;
  10473. };
  10474. function deleteMeshBuffers ( geometryGroup ) {
  10475. _gl.deleteBuffer( geometryGroup.__webglVertexBuffer );
  10476. _gl.deleteBuffer( geometryGroup.__webglNormalBuffer );
  10477. _gl.deleteBuffer( geometryGroup.__webglTangentBuffer );
  10478. _gl.deleteBuffer( geometryGroup.__webglColorBuffer );
  10479. _gl.deleteBuffer( geometryGroup.__webglUVBuffer );
  10480. _gl.deleteBuffer( geometryGroup.__webglUV2Buffer );
  10481. _gl.deleteBuffer( geometryGroup.__webglSkinIndicesBuffer );
  10482. _gl.deleteBuffer( geometryGroup.__webglSkinWeightsBuffer );
  10483. _gl.deleteBuffer( geometryGroup.__webglFaceBuffer );
  10484. _gl.deleteBuffer( geometryGroup.__webglLineBuffer );
  10485. var m, ml;
  10486. if ( geometryGroup.numMorphTargets ) {
  10487. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10488. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  10489. }
  10490. }
  10491. if ( geometryGroup.numMorphNormals ) {
  10492. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10493. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  10494. }
  10495. }
  10496. deleteCustomAttributesBuffers( geometryGroup );
  10497. _this.info.memory.geometries --;
  10498. };
  10499. */
  10500. function deleteCustomAttributesBuffers( geometry ) {
  10501. if ( geometry.__webglCustomAttributesList ) {
  10502. for ( var id in geometry.__webglCustomAttributesList ) {
  10503. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  10504. }
  10505. }
  10506. };
  10507. // Buffer initialization
  10508. function initCustomAttributes ( geometry, object ) {
  10509. var nvertices = geometry.vertices.length;
  10510. var material = object.material;
  10511. if ( material.attributes ) {
  10512. if ( geometry.__webglCustomAttributesList === undefined ) {
  10513. geometry.__webglCustomAttributesList = [];
  10514. }
  10515. for ( var a in material.attributes ) {
  10516. var attribute = material.attributes[ a ];
  10517. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  10518. attribute.__webglInitialized = true;
  10519. var size = 1; // "f" and "i"
  10520. if ( attribute.type === "v2" ) size = 2;
  10521. else if ( attribute.type === "v3" ) size = 3;
  10522. else if ( attribute.type === "v4" ) size = 4;
  10523. else if ( attribute.type === "c" ) size = 3;
  10524. attribute.size = size;
  10525. attribute.array = new Float32Array( nvertices * size );
  10526. attribute.buffer = _gl.createBuffer();
  10527. attribute.buffer.belongsToAttribute = a;
  10528. attribute.needsUpdate = true;
  10529. }
  10530. geometry.__webglCustomAttributesList.push( attribute );
  10531. }
  10532. }
  10533. };
  10534. function initParticleBuffers ( geometry, object ) {
  10535. var nvertices = geometry.vertices.length;
  10536. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  10537. geometry.__colorArray = new Float32Array( nvertices * 3 );
  10538. geometry.__sortArray = [];
  10539. geometry.__webglParticleCount = nvertices;
  10540. initCustomAttributes ( geometry, object );
  10541. };
  10542. function initLineBuffers ( geometry, object ) {
  10543. var nvertices = geometry.vertices.length;
  10544. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  10545. geometry.__colorArray = new Float32Array( nvertices * 3 );
  10546. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  10547. geometry.__webglLineCount = nvertices;
  10548. initCustomAttributes ( geometry, object );
  10549. };
  10550. function initRibbonBuffers ( geometry, object ) {
  10551. var nvertices = geometry.vertices.length;
  10552. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  10553. geometry.__colorArray = new Float32Array( nvertices * 3 );
  10554. geometry.__normalArray = new Float32Array( nvertices * 3 );
  10555. geometry.__webglVertexCount = nvertices;
  10556. initCustomAttributes ( geometry, object );
  10557. };
  10558. function initMeshBuffers ( geometryGroup, object ) {
  10559. var geometry = object.geometry,
  10560. faces3 = geometryGroup.faces3,
  10561. faces4 = geometryGroup.faces4,
  10562. nvertices = faces3.length * 3 + faces4.length * 4,
  10563. ntris = faces3.length * 1 + faces4.length * 2,
  10564. nlines = faces3.length * 3 + faces4.length * 4,
  10565. material = getBufferMaterial( object, geometryGroup ),
  10566. uvType = bufferGuessUVType( material ),
  10567. normalType = bufferGuessNormalType( material ),
  10568. vertexColorType = bufferGuessVertexColorType( material );
  10569. //console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  10570. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  10571. if ( normalType ) {
  10572. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  10573. }
  10574. if ( geometry.hasTangents ) {
  10575. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  10576. }
  10577. if ( vertexColorType ) {
  10578. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  10579. }
  10580. if ( uvType ) {
  10581. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  10582. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  10583. }
  10584. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  10585. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  10586. }
  10587. }
  10588. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  10589. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  10590. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  10591. }
  10592. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  10593. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  10594. var m, ml;
  10595. if ( geometryGroup.numMorphTargets ) {
  10596. geometryGroup.__morphTargetsArrays = [];
  10597. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10598. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  10599. }
  10600. }
  10601. if ( geometryGroup.numMorphNormals ) {
  10602. geometryGroup.__morphNormalsArrays = [];
  10603. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10604. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  10605. }
  10606. }
  10607. geometryGroup.__webglFaceCount = ntris * 3;
  10608. geometryGroup.__webglLineCount = nlines * 2;
  10609. // custom attributes
  10610. if ( material.attributes ) {
  10611. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  10612. geometryGroup.__webglCustomAttributesList = [];
  10613. }
  10614. for ( var a in material.attributes ) {
  10615. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  10616. // attribute buffers which are correctly indexed in the setMeshBuffers function
  10617. var originalAttribute = material.attributes[ a ];
  10618. var attribute = {};
  10619. for ( var property in originalAttribute ) {
  10620. attribute[ property ] = originalAttribute[ property ];
  10621. }
  10622. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  10623. attribute.__webglInitialized = true;
  10624. var size = 1; // "f" and "i"
  10625. if( attribute.type === "v2" ) size = 2;
  10626. else if( attribute.type === "v3" ) size = 3;
  10627. else if( attribute.type === "v4" ) size = 4;
  10628. else if( attribute.type === "c" ) size = 3;
  10629. attribute.size = size;
  10630. attribute.array = new Float32Array( nvertices * size );
  10631. attribute.buffer = _gl.createBuffer();
  10632. attribute.buffer.belongsToAttribute = a;
  10633. originalAttribute.needsUpdate = true;
  10634. attribute.__original = originalAttribute;
  10635. }
  10636. geometryGroup.__webglCustomAttributesList.push( attribute );
  10637. }
  10638. }
  10639. geometryGroup.__inittedArrays = true;
  10640. };
  10641. function getBufferMaterial( object, geometryGroup ) {
  10642. return object.material instanceof THREE.MeshFaceMaterial
  10643. ? object.material.materials[ geometryGroup.materialIndex ]
  10644. : object.material;
  10645. };
  10646. function materialNeedsSmoothNormals ( material ) {
  10647. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  10648. };
  10649. function bufferGuessNormalType ( material ) {
  10650. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  10651. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  10652. return false;
  10653. }
  10654. if ( materialNeedsSmoothNormals( material ) ) {
  10655. return THREE.SmoothShading;
  10656. } else {
  10657. return THREE.FlatShading;
  10658. }
  10659. };
  10660. function bufferGuessVertexColorType ( material ) {
  10661. if ( material.vertexColors ) {
  10662. return material.vertexColors;
  10663. }
  10664. return false;
  10665. };
  10666. function bufferGuessUVType ( material ) {
  10667. // material must use some texture to require uvs
  10668. if ( material.map || material.lightMap || material.bumpMap || material.normalMap || material.specularMap || material instanceof THREE.ShaderMaterial ) {
  10669. return true;
  10670. }
  10671. return false;
  10672. };
  10673. //
  10674. function initDirectBuffers( geometry ) {
  10675. var a, attribute, type;
  10676. for ( a in geometry.attributes ) {
  10677. if ( a === "index" ) {
  10678. type = _gl.ELEMENT_ARRAY_BUFFER;
  10679. } else {
  10680. type = _gl.ARRAY_BUFFER;
  10681. }
  10682. attribute = geometry.attributes[ a ];
  10683. attribute.buffer = _gl.createBuffer();
  10684. _gl.bindBuffer( type, attribute.buffer );
  10685. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  10686. }
  10687. };
  10688. // Buffer setting
  10689. function setParticleBuffers ( geometry, hint, object ) {
  10690. var v, c, vertex, offset, index, color,
  10691. vertices = geometry.vertices,
  10692. vl = vertices.length,
  10693. colors = geometry.colors,
  10694. cl = colors.length,
  10695. vertexArray = geometry.__vertexArray,
  10696. colorArray = geometry.__colorArray,
  10697. sortArray = geometry.__sortArray,
  10698. dirtyVertices = geometry.verticesNeedUpdate,
  10699. dirtyElements = geometry.elementsNeedUpdate,
  10700. dirtyColors = geometry.colorsNeedUpdate,
  10701. customAttributes = geometry.__webglCustomAttributesList,
  10702. i, il,
  10703. a, ca, cal, value,
  10704. customAttribute;
  10705. if ( object.sortParticles ) {
  10706. _projScreenMatrixPS.copy( _projScreenMatrix );
  10707. _projScreenMatrixPS.multiply( object.matrixWorld );
  10708. for ( v = 0; v < vl; v ++ ) {
  10709. vertex = vertices[ v ];
  10710. _vector3.copy( vertex );
  10711. _vector3.applyMatrix4( _projScreenMatrixPS );
  10712. sortArray[ v ] = [ _vector3.z, v ];
  10713. }
  10714. sortArray.sort( numericalSort );
  10715. for ( v = 0; v < vl; v ++ ) {
  10716. vertex = vertices[ sortArray[v][1] ];
  10717. offset = v * 3;
  10718. vertexArray[ offset ] = vertex.x;
  10719. vertexArray[ offset + 1 ] = vertex.y;
  10720. vertexArray[ offset + 2 ] = vertex.z;
  10721. }
  10722. for ( c = 0; c < cl; c ++ ) {
  10723. offset = c * 3;
  10724. color = colors[ sortArray[c][1] ];
  10725. colorArray[ offset ] = color.r;
  10726. colorArray[ offset + 1 ] = color.g;
  10727. colorArray[ offset + 2 ] = color.b;
  10728. }
  10729. if ( customAttributes ) {
  10730. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10731. customAttribute = customAttributes[ i ];
  10732. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  10733. offset = 0;
  10734. cal = customAttribute.value.length;
  10735. if ( customAttribute.size === 1 ) {
  10736. for ( ca = 0; ca < cal; ca ++ ) {
  10737. index = sortArray[ ca ][ 1 ];
  10738. customAttribute.array[ ca ] = customAttribute.value[ index ];
  10739. }
  10740. } else if ( customAttribute.size === 2 ) {
  10741. for ( ca = 0; ca < cal; ca ++ ) {
  10742. index = sortArray[ ca ][ 1 ];
  10743. value = customAttribute.value[ index ];
  10744. customAttribute.array[ offset ] = value.x;
  10745. customAttribute.array[ offset + 1 ] = value.y;
  10746. offset += 2;
  10747. }
  10748. } else if ( customAttribute.size === 3 ) {
  10749. if ( customAttribute.type === "c" ) {
  10750. for ( ca = 0; ca < cal; ca ++ ) {
  10751. index = sortArray[ ca ][ 1 ];
  10752. value = customAttribute.value[ index ];
  10753. customAttribute.array[ offset ] = value.r;
  10754. customAttribute.array[ offset + 1 ] = value.g;
  10755. customAttribute.array[ offset + 2 ] = value.b;
  10756. offset += 3;
  10757. }
  10758. } else {
  10759. for ( ca = 0; ca < cal; ca ++ ) {
  10760. index = sortArray[ ca ][ 1 ];
  10761. value = customAttribute.value[ index ];
  10762. customAttribute.array[ offset ] = value.x;
  10763. customAttribute.array[ offset + 1 ] = value.y;
  10764. customAttribute.array[ offset + 2 ] = value.z;
  10765. offset += 3;
  10766. }
  10767. }
  10768. } else if ( customAttribute.size === 4 ) {
  10769. for ( ca = 0; ca < cal; ca ++ ) {
  10770. index = sortArray[ ca ][ 1 ];
  10771. value = customAttribute.value[ index ];
  10772. customAttribute.array[ offset ] = value.x;
  10773. customAttribute.array[ offset + 1 ] = value.y;
  10774. customAttribute.array[ offset + 2 ] = value.z;
  10775. customAttribute.array[ offset + 3 ] = value.w;
  10776. offset += 4;
  10777. }
  10778. }
  10779. }
  10780. }
  10781. } else {
  10782. if ( dirtyVertices ) {
  10783. for ( v = 0; v < vl; v ++ ) {
  10784. vertex = vertices[ v ];
  10785. offset = v * 3;
  10786. vertexArray[ offset ] = vertex.x;
  10787. vertexArray[ offset + 1 ] = vertex.y;
  10788. vertexArray[ offset + 2 ] = vertex.z;
  10789. }
  10790. }
  10791. if ( dirtyColors ) {
  10792. for ( c = 0; c < cl; c ++ ) {
  10793. color = colors[ c ];
  10794. offset = c * 3;
  10795. colorArray[ offset ] = color.r;
  10796. colorArray[ offset + 1 ] = color.g;
  10797. colorArray[ offset + 2 ] = color.b;
  10798. }
  10799. }
  10800. if ( customAttributes ) {
  10801. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10802. customAttribute = customAttributes[ i ];
  10803. if ( customAttribute.needsUpdate &&
  10804. ( customAttribute.boundTo === undefined ||
  10805. customAttribute.boundTo === "vertices") ) {
  10806. cal = customAttribute.value.length;
  10807. offset = 0;
  10808. if ( customAttribute.size === 1 ) {
  10809. for ( ca = 0; ca < cal; ca ++ ) {
  10810. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10811. }
  10812. } else if ( customAttribute.size === 2 ) {
  10813. for ( ca = 0; ca < cal; ca ++ ) {
  10814. value = customAttribute.value[ ca ];
  10815. customAttribute.array[ offset ] = value.x;
  10816. customAttribute.array[ offset + 1 ] = value.y;
  10817. offset += 2;
  10818. }
  10819. } else if ( customAttribute.size === 3 ) {
  10820. if ( customAttribute.type === "c" ) {
  10821. for ( ca = 0; ca < cal; ca ++ ) {
  10822. value = customAttribute.value[ ca ];
  10823. customAttribute.array[ offset ] = value.r;
  10824. customAttribute.array[ offset + 1 ] = value.g;
  10825. customAttribute.array[ offset + 2 ] = value.b;
  10826. offset += 3;
  10827. }
  10828. } else {
  10829. for ( ca = 0; ca < cal; ca ++ ) {
  10830. value = customAttribute.value[ ca ];
  10831. customAttribute.array[ offset ] = value.x;
  10832. customAttribute.array[ offset + 1 ] = value.y;
  10833. customAttribute.array[ offset + 2 ] = value.z;
  10834. offset += 3;
  10835. }
  10836. }
  10837. } else if ( customAttribute.size === 4 ) {
  10838. for ( ca = 0; ca < cal; ca ++ ) {
  10839. value = customAttribute.value[ ca ];
  10840. customAttribute.array[ offset ] = value.x;
  10841. customAttribute.array[ offset + 1 ] = value.y;
  10842. customAttribute.array[ offset + 2 ] = value.z;
  10843. customAttribute.array[ offset + 3 ] = value.w;
  10844. offset += 4;
  10845. }
  10846. }
  10847. }
  10848. }
  10849. }
  10850. }
  10851. if ( dirtyVertices || object.sortParticles ) {
  10852. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10853. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10854. }
  10855. if ( dirtyColors || object.sortParticles ) {
  10856. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10857. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10858. }
  10859. if ( customAttributes ) {
  10860. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10861. customAttribute = customAttributes[ i ];
  10862. if ( customAttribute.needsUpdate || object.sortParticles ) {
  10863. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10864. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10865. }
  10866. }
  10867. }
  10868. };
  10869. function setLineBuffers ( geometry, hint ) {
  10870. var v, c, d, vertex, offset, color,
  10871. vertices = geometry.vertices,
  10872. colors = geometry.colors,
  10873. lineDistances = geometry.lineDistances,
  10874. vl = vertices.length,
  10875. cl = colors.length,
  10876. dl = lineDistances.length,
  10877. vertexArray = geometry.__vertexArray,
  10878. colorArray = geometry.__colorArray,
  10879. lineDistanceArray = geometry.__lineDistanceArray,
  10880. dirtyVertices = geometry.verticesNeedUpdate,
  10881. dirtyColors = geometry.colorsNeedUpdate,
  10882. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  10883. customAttributes = geometry.__webglCustomAttributesList,
  10884. i, il,
  10885. a, ca, cal, value,
  10886. customAttribute;
  10887. if ( dirtyVertices ) {
  10888. for ( v = 0; v < vl; v ++ ) {
  10889. vertex = vertices[ v ];
  10890. offset = v * 3;
  10891. vertexArray[ offset ] = vertex.x;
  10892. vertexArray[ offset + 1 ] = vertex.y;
  10893. vertexArray[ offset + 2 ] = vertex.z;
  10894. }
  10895. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10896. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10897. }
  10898. if ( dirtyColors ) {
  10899. for ( c = 0; c < cl; c ++ ) {
  10900. color = colors[ c ];
  10901. offset = c * 3;
  10902. colorArray[ offset ] = color.r;
  10903. colorArray[ offset + 1 ] = color.g;
  10904. colorArray[ offset + 2 ] = color.b;
  10905. }
  10906. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10907. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10908. }
  10909. if ( dirtyLineDistances ) {
  10910. for ( d = 0; d < dl; d ++ ) {
  10911. lineDistanceArray[ d ] = lineDistances[ d ];
  10912. }
  10913. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  10914. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  10915. }
  10916. if ( customAttributes ) {
  10917. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10918. customAttribute = customAttributes[ i ];
  10919. if ( customAttribute.needsUpdate &&
  10920. ( customAttribute.boundTo === undefined ||
  10921. customAttribute.boundTo === "vertices" ) ) {
  10922. offset = 0;
  10923. cal = customAttribute.value.length;
  10924. if ( customAttribute.size === 1 ) {
  10925. for ( ca = 0; ca < cal; ca ++ ) {
  10926. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10927. }
  10928. } else if ( customAttribute.size === 2 ) {
  10929. for ( ca = 0; ca < cal; ca ++ ) {
  10930. value = customAttribute.value[ ca ];
  10931. customAttribute.array[ offset ] = value.x;
  10932. customAttribute.array[ offset + 1 ] = value.y;
  10933. offset += 2;
  10934. }
  10935. } else if ( customAttribute.size === 3 ) {
  10936. if ( customAttribute.type === "c" ) {
  10937. for ( ca = 0; ca < cal; ca ++ ) {
  10938. value = customAttribute.value[ ca ];
  10939. customAttribute.array[ offset ] = value.r;
  10940. customAttribute.array[ offset + 1 ] = value.g;
  10941. customAttribute.array[ offset + 2 ] = value.b;
  10942. offset += 3;
  10943. }
  10944. } else {
  10945. for ( ca = 0; ca < cal; ca ++ ) {
  10946. value = customAttribute.value[ ca ];
  10947. customAttribute.array[ offset ] = value.x;
  10948. customAttribute.array[ offset + 1 ] = value.y;
  10949. customAttribute.array[ offset + 2 ] = value.z;
  10950. offset += 3;
  10951. }
  10952. }
  10953. } else if ( customAttribute.size === 4 ) {
  10954. for ( ca = 0; ca < cal; ca ++ ) {
  10955. value = customAttribute.value[ ca ];
  10956. customAttribute.array[ offset ] = value.x;
  10957. customAttribute.array[ offset + 1 ] = value.y;
  10958. customAttribute.array[ offset + 2 ] = value.z;
  10959. customAttribute.array[ offset + 3 ] = value.w;
  10960. offset += 4;
  10961. }
  10962. }
  10963. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10964. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10965. }
  10966. }
  10967. }
  10968. };
  10969. function setRibbonBuffers ( geometry, hint ) {
  10970. var v, c, n, vertex, offset, color, normal,
  10971. i, il, ca, cal, customAttribute, value,
  10972. vertices = geometry.vertices,
  10973. colors = geometry.colors,
  10974. normals = geometry.normals,
  10975. vl = vertices.length,
  10976. cl = colors.length,
  10977. nl = normals.length,
  10978. vertexArray = geometry.__vertexArray,
  10979. colorArray = geometry.__colorArray,
  10980. normalArray = geometry.__normalArray,
  10981. dirtyVertices = geometry.verticesNeedUpdate,
  10982. dirtyColors = geometry.colorsNeedUpdate,
  10983. dirtyNormals = geometry.normalsNeedUpdate,
  10984. customAttributes = geometry.__webglCustomAttributesList;
  10985. if ( dirtyVertices ) {
  10986. for ( v = 0; v < vl; v ++ ) {
  10987. vertex = vertices[ v ];
  10988. offset = v * 3;
  10989. vertexArray[ offset ] = vertex.x;
  10990. vertexArray[ offset + 1 ] = vertex.y;
  10991. vertexArray[ offset + 2 ] = vertex.z;
  10992. }
  10993. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10994. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10995. }
  10996. if ( dirtyColors ) {
  10997. for ( c = 0; c < cl; c ++ ) {
  10998. color = colors[ c ];
  10999. offset = c * 3;
  11000. colorArray[ offset ] = color.r;
  11001. colorArray[ offset + 1 ] = color.g;
  11002. colorArray[ offset + 2 ] = color.b;
  11003. }
  11004. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11005. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11006. }
  11007. if ( dirtyNormals ) {
  11008. for ( n = 0; n < nl; n ++ ) {
  11009. normal = normals[ n ];
  11010. offset = n * 3;
  11011. normalArray[ offset ] = normal.x;
  11012. normalArray[ offset + 1 ] = normal.y;
  11013. normalArray[ offset + 2 ] = normal.z;
  11014. }
  11015. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglNormalBuffer );
  11016. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  11017. }
  11018. if ( customAttributes ) {
  11019. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11020. customAttribute = customAttributes[ i ];
  11021. if ( customAttribute.needsUpdate &&
  11022. ( customAttribute.boundTo === undefined ||
  11023. customAttribute.boundTo === "vertices" ) ) {
  11024. offset = 0;
  11025. cal = customAttribute.value.length;
  11026. if ( customAttribute.size === 1 ) {
  11027. for ( ca = 0; ca < cal; ca ++ ) {
  11028. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11029. }
  11030. } else if ( customAttribute.size === 2 ) {
  11031. for ( ca = 0; ca < cal; ca ++ ) {
  11032. value = customAttribute.value[ ca ];
  11033. customAttribute.array[ offset ] = value.x;
  11034. customAttribute.array[ offset + 1 ] = value.y;
  11035. offset += 2;
  11036. }
  11037. } else if ( customAttribute.size === 3 ) {
  11038. if ( customAttribute.type === "c" ) {
  11039. for ( ca = 0; ca < cal; ca ++ ) {
  11040. value = customAttribute.value[ ca ];
  11041. customAttribute.array[ offset ] = value.r;
  11042. customAttribute.array[ offset + 1 ] = value.g;
  11043. customAttribute.array[ offset + 2 ] = value.b;
  11044. offset += 3;
  11045. }
  11046. } else {
  11047. for ( ca = 0; ca < cal; ca ++ ) {
  11048. value = customAttribute.value[ ca ];
  11049. customAttribute.array[ offset ] = value.x;
  11050. customAttribute.array[ offset + 1 ] = value.y;
  11051. customAttribute.array[ offset + 2 ] = value.z;
  11052. offset += 3;
  11053. }
  11054. }
  11055. } else if ( customAttribute.size === 4 ) {
  11056. for ( ca = 0; ca < cal; ca ++ ) {
  11057. value = customAttribute.value[ ca ];
  11058. customAttribute.array[ offset ] = value.x;
  11059. customAttribute.array[ offset + 1 ] = value.y;
  11060. customAttribute.array[ offset + 2 ] = value.z;
  11061. customAttribute.array[ offset + 3 ] = value.w;
  11062. offset += 4;
  11063. }
  11064. }
  11065. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11066. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11067. }
  11068. }
  11069. }
  11070. };
  11071. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  11072. if ( ! geometryGroup.__inittedArrays ) {
  11073. return;
  11074. }
  11075. var normalType = bufferGuessNormalType( material ),
  11076. vertexColorType = bufferGuessVertexColorType( material ),
  11077. uvType = bufferGuessUVType( material ),
  11078. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  11079. var f, fl, fi, face,
  11080. vertexNormals, faceNormal, normal,
  11081. vertexColors, faceColor,
  11082. vertexTangents,
  11083. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  11084. c1, c2, c3, c4,
  11085. sw1, sw2, sw3, sw4,
  11086. si1, si2, si3, si4,
  11087. sa1, sa2, sa3, sa4,
  11088. sb1, sb2, sb3, sb4,
  11089. m, ml, i, il,
  11090. vn, uvi, uv2i,
  11091. vk, vkl, vka,
  11092. nka, chf, faceVertexNormals,
  11093. a,
  11094. vertexIndex = 0,
  11095. offset = 0,
  11096. offset_uv = 0,
  11097. offset_uv2 = 0,
  11098. offset_face = 0,
  11099. offset_normal = 0,
  11100. offset_tangent = 0,
  11101. offset_line = 0,
  11102. offset_color = 0,
  11103. offset_skin = 0,
  11104. offset_morphTarget = 0,
  11105. offset_custom = 0,
  11106. offset_customSrc = 0,
  11107. value,
  11108. vertexArray = geometryGroup.__vertexArray,
  11109. uvArray = geometryGroup.__uvArray,
  11110. uv2Array = geometryGroup.__uv2Array,
  11111. normalArray = geometryGroup.__normalArray,
  11112. tangentArray = geometryGroup.__tangentArray,
  11113. colorArray = geometryGroup.__colorArray,
  11114. skinIndexArray = geometryGroup.__skinIndexArray,
  11115. skinWeightArray = geometryGroup.__skinWeightArray,
  11116. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  11117. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  11118. customAttributes = geometryGroup.__webglCustomAttributesList,
  11119. customAttribute,
  11120. faceArray = geometryGroup.__faceArray,
  11121. lineArray = geometryGroup.__lineArray,
  11122. geometry = object.geometry, // this is shared for all chunks
  11123. dirtyVertices = geometry.verticesNeedUpdate,
  11124. dirtyElements = geometry.elementsNeedUpdate,
  11125. dirtyUvs = geometry.uvsNeedUpdate,
  11126. dirtyNormals = geometry.normalsNeedUpdate,
  11127. dirtyTangents = geometry.tangentsNeedUpdate,
  11128. dirtyColors = geometry.colorsNeedUpdate,
  11129. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  11130. vertices = geometry.vertices,
  11131. chunk_faces3 = geometryGroup.faces3,
  11132. chunk_faces4 = geometryGroup.faces4,
  11133. obj_faces = geometry.faces,
  11134. obj_uvs = geometry.faceVertexUvs[ 0 ],
  11135. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  11136. obj_colors = geometry.colors,
  11137. obj_skinIndices = geometry.skinIndices,
  11138. obj_skinWeights = geometry.skinWeights,
  11139. morphTargets = geometry.morphTargets,
  11140. morphNormals = geometry.morphNormals;
  11141. if ( dirtyVertices ) {
  11142. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11143. face = obj_faces[ chunk_faces3[ f ] ];
  11144. v1 = vertices[ face.a ];
  11145. v2 = vertices[ face.b ];
  11146. v3 = vertices[ face.c ];
  11147. vertexArray[ offset ] = v1.x;
  11148. vertexArray[ offset + 1 ] = v1.y;
  11149. vertexArray[ offset + 2 ] = v1.z;
  11150. vertexArray[ offset + 3 ] = v2.x;
  11151. vertexArray[ offset + 4 ] = v2.y;
  11152. vertexArray[ offset + 5 ] = v2.z;
  11153. vertexArray[ offset + 6 ] = v3.x;
  11154. vertexArray[ offset + 7 ] = v3.y;
  11155. vertexArray[ offset + 8 ] = v3.z;
  11156. offset += 9;
  11157. }
  11158. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11159. face = obj_faces[ chunk_faces4[ f ] ];
  11160. v1 = vertices[ face.a ];
  11161. v2 = vertices[ face.b ];
  11162. v3 = vertices[ face.c ];
  11163. v4 = vertices[ face.d ];
  11164. vertexArray[ offset ] = v1.x;
  11165. vertexArray[ offset + 1 ] = v1.y;
  11166. vertexArray[ offset + 2 ] = v1.z;
  11167. vertexArray[ offset + 3 ] = v2.x;
  11168. vertexArray[ offset + 4 ] = v2.y;
  11169. vertexArray[ offset + 5 ] = v2.z;
  11170. vertexArray[ offset + 6 ] = v3.x;
  11171. vertexArray[ offset + 7 ] = v3.y;
  11172. vertexArray[ offset + 8 ] = v3.z;
  11173. vertexArray[ offset + 9 ] = v4.x;
  11174. vertexArray[ offset + 10 ] = v4.y;
  11175. vertexArray[ offset + 11 ] = v4.z;
  11176. offset += 12;
  11177. }
  11178. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11179. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11180. }
  11181. if ( dirtyMorphTargets ) {
  11182. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  11183. offset_morphTarget = 0;
  11184. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11185. chf = chunk_faces3[ f ];
  11186. face = obj_faces[ chf ];
  11187. // morph positions
  11188. v1 = morphTargets[ vk ].vertices[ face.a ];
  11189. v2 = morphTargets[ vk ].vertices[ face.b ];
  11190. v3 = morphTargets[ vk ].vertices[ face.c ];
  11191. vka = morphTargetsArrays[ vk ];
  11192. vka[ offset_morphTarget ] = v1.x;
  11193. vka[ offset_morphTarget + 1 ] = v1.y;
  11194. vka[ offset_morphTarget + 2 ] = v1.z;
  11195. vka[ offset_morphTarget + 3 ] = v2.x;
  11196. vka[ offset_morphTarget + 4 ] = v2.y;
  11197. vka[ offset_morphTarget + 5 ] = v2.z;
  11198. vka[ offset_morphTarget + 6 ] = v3.x;
  11199. vka[ offset_morphTarget + 7 ] = v3.y;
  11200. vka[ offset_morphTarget + 8 ] = v3.z;
  11201. // morph normals
  11202. if ( material.morphNormals ) {
  11203. if ( needsSmoothNormals ) {
  11204. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  11205. n1 = faceVertexNormals.a;
  11206. n2 = faceVertexNormals.b;
  11207. n3 = faceVertexNormals.c;
  11208. } else {
  11209. n1 = morphNormals[ vk ].faceNormals[ chf ];
  11210. n2 = n1;
  11211. n3 = n1;
  11212. }
  11213. nka = morphNormalsArrays[ vk ];
  11214. nka[ offset_morphTarget ] = n1.x;
  11215. nka[ offset_morphTarget + 1 ] = n1.y;
  11216. nka[ offset_morphTarget + 2 ] = n1.z;
  11217. nka[ offset_morphTarget + 3 ] = n2.x;
  11218. nka[ offset_morphTarget + 4 ] = n2.y;
  11219. nka[ offset_morphTarget + 5 ] = n2.z;
  11220. nka[ offset_morphTarget + 6 ] = n3.x;
  11221. nka[ offset_morphTarget + 7 ] = n3.y;
  11222. nka[ offset_morphTarget + 8 ] = n3.z;
  11223. }
  11224. //
  11225. offset_morphTarget += 9;
  11226. }
  11227. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11228. chf = chunk_faces4[ f ];
  11229. face = obj_faces[ chf ];
  11230. // morph positions
  11231. v1 = morphTargets[ vk ].vertices[ face.a ];
  11232. v2 = morphTargets[ vk ].vertices[ face.b ];
  11233. v3 = morphTargets[ vk ].vertices[ face.c ];
  11234. v4 = morphTargets[ vk ].vertices[ face.d ];
  11235. vka = morphTargetsArrays[ vk ];
  11236. vka[ offset_morphTarget ] = v1.x;
  11237. vka[ offset_morphTarget + 1 ] = v1.y;
  11238. vka[ offset_morphTarget + 2 ] = v1.z;
  11239. vka[ offset_morphTarget + 3 ] = v2.x;
  11240. vka[ offset_morphTarget + 4 ] = v2.y;
  11241. vka[ offset_morphTarget + 5 ] = v2.z;
  11242. vka[ offset_morphTarget + 6 ] = v3.x;
  11243. vka[ offset_morphTarget + 7 ] = v3.y;
  11244. vka[ offset_morphTarget + 8 ] = v3.z;
  11245. vka[ offset_morphTarget + 9 ] = v4.x;
  11246. vka[ offset_morphTarget + 10 ] = v4.y;
  11247. vka[ offset_morphTarget + 11 ] = v4.z;
  11248. // morph normals
  11249. if ( material.morphNormals ) {
  11250. if ( needsSmoothNormals ) {
  11251. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  11252. n1 = faceVertexNormals.a;
  11253. n2 = faceVertexNormals.b;
  11254. n3 = faceVertexNormals.c;
  11255. n4 = faceVertexNormals.d;
  11256. } else {
  11257. n1 = morphNormals[ vk ].faceNormals[ chf ];
  11258. n2 = n1;
  11259. n3 = n1;
  11260. n4 = n1;
  11261. }
  11262. nka = morphNormalsArrays[ vk ];
  11263. nka[ offset_morphTarget ] = n1.x;
  11264. nka[ offset_morphTarget + 1 ] = n1.y;
  11265. nka[ offset_morphTarget + 2 ] = n1.z;
  11266. nka[ offset_morphTarget + 3 ] = n2.x;
  11267. nka[ offset_morphTarget + 4 ] = n2.y;
  11268. nka[ offset_morphTarget + 5 ] = n2.z;
  11269. nka[ offset_morphTarget + 6 ] = n3.x;
  11270. nka[ offset_morphTarget + 7 ] = n3.y;
  11271. nka[ offset_morphTarget + 8 ] = n3.z;
  11272. nka[ offset_morphTarget + 9 ] = n4.x;
  11273. nka[ offset_morphTarget + 10 ] = n4.y;
  11274. nka[ offset_morphTarget + 11 ] = n4.z;
  11275. }
  11276. //
  11277. offset_morphTarget += 12;
  11278. }
  11279. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  11280. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  11281. if ( material.morphNormals ) {
  11282. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  11283. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  11284. }
  11285. }
  11286. }
  11287. if ( obj_skinWeights.length ) {
  11288. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11289. face = obj_faces[ chunk_faces3[ f ] ];
  11290. // weights
  11291. sw1 = obj_skinWeights[ face.a ];
  11292. sw2 = obj_skinWeights[ face.b ];
  11293. sw3 = obj_skinWeights[ face.c ];
  11294. skinWeightArray[ offset_skin ] = sw1.x;
  11295. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  11296. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  11297. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  11298. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  11299. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  11300. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  11301. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  11302. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  11303. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  11304. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  11305. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  11306. // indices
  11307. si1 = obj_skinIndices[ face.a ];
  11308. si2 = obj_skinIndices[ face.b ];
  11309. si3 = obj_skinIndices[ face.c ];
  11310. skinIndexArray[ offset_skin ] = si1.x;
  11311. skinIndexArray[ offset_skin + 1 ] = si1.y;
  11312. skinIndexArray[ offset_skin + 2 ] = si1.z;
  11313. skinIndexArray[ offset_skin + 3 ] = si1.w;
  11314. skinIndexArray[ offset_skin + 4 ] = si2.x;
  11315. skinIndexArray[ offset_skin + 5 ] = si2.y;
  11316. skinIndexArray[ offset_skin + 6 ] = si2.z;
  11317. skinIndexArray[ offset_skin + 7 ] = si2.w;
  11318. skinIndexArray[ offset_skin + 8 ] = si3.x;
  11319. skinIndexArray[ offset_skin + 9 ] = si3.y;
  11320. skinIndexArray[ offset_skin + 10 ] = si3.z;
  11321. skinIndexArray[ offset_skin + 11 ] = si3.w;
  11322. offset_skin += 12;
  11323. }
  11324. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11325. face = obj_faces[ chunk_faces4[ f ] ];
  11326. // weights
  11327. sw1 = obj_skinWeights[ face.a ];
  11328. sw2 = obj_skinWeights[ face.b ];
  11329. sw3 = obj_skinWeights[ face.c ];
  11330. sw4 = obj_skinWeights[ face.d ];
  11331. skinWeightArray[ offset_skin ] = sw1.x;
  11332. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  11333. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  11334. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  11335. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  11336. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  11337. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  11338. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  11339. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  11340. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  11341. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  11342. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  11343. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  11344. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  11345. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  11346. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  11347. // indices
  11348. si1 = obj_skinIndices[ face.a ];
  11349. si2 = obj_skinIndices[ face.b ];
  11350. si3 = obj_skinIndices[ face.c ];
  11351. si4 = obj_skinIndices[ face.d ];
  11352. skinIndexArray[ offset_skin ] = si1.x;
  11353. skinIndexArray[ offset_skin + 1 ] = si1.y;
  11354. skinIndexArray[ offset_skin + 2 ] = si1.z;
  11355. skinIndexArray[ offset_skin + 3 ] = si1.w;
  11356. skinIndexArray[ offset_skin + 4 ] = si2.x;
  11357. skinIndexArray[ offset_skin + 5 ] = si2.y;
  11358. skinIndexArray[ offset_skin + 6 ] = si2.z;
  11359. skinIndexArray[ offset_skin + 7 ] = si2.w;
  11360. skinIndexArray[ offset_skin + 8 ] = si3.x;
  11361. skinIndexArray[ offset_skin + 9 ] = si3.y;
  11362. skinIndexArray[ offset_skin + 10 ] = si3.z;
  11363. skinIndexArray[ offset_skin + 11 ] = si3.w;
  11364. skinIndexArray[ offset_skin + 12 ] = si4.x;
  11365. skinIndexArray[ offset_skin + 13 ] = si4.y;
  11366. skinIndexArray[ offset_skin + 14 ] = si4.z;
  11367. skinIndexArray[ offset_skin + 15 ] = si4.w;
  11368. offset_skin += 16;
  11369. }
  11370. if ( offset_skin > 0 ) {
  11371. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  11372. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  11373. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  11374. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  11375. }
  11376. }
  11377. if ( dirtyColors && vertexColorType ) {
  11378. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11379. face = obj_faces[ chunk_faces3[ f ] ];
  11380. vertexColors = face.vertexColors;
  11381. faceColor = face.color;
  11382. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  11383. c1 = vertexColors[ 0 ];
  11384. c2 = vertexColors[ 1 ];
  11385. c3 = vertexColors[ 2 ];
  11386. } else {
  11387. c1 = faceColor;
  11388. c2 = faceColor;
  11389. c3 = faceColor;
  11390. }
  11391. colorArray[ offset_color ] = c1.r;
  11392. colorArray[ offset_color + 1 ] = c1.g;
  11393. colorArray[ offset_color + 2 ] = c1.b;
  11394. colorArray[ offset_color + 3 ] = c2.r;
  11395. colorArray[ offset_color + 4 ] = c2.g;
  11396. colorArray[ offset_color + 5 ] = c2.b;
  11397. colorArray[ offset_color + 6 ] = c3.r;
  11398. colorArray[ offset_color + 7 ] = c3.g;
  11399. colorArray[ offset_color + 8 ] = c3.b;
  11400. offset_color += 9;
  11401. }
  11402. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11403. face = obj_faces[ chunk_faces4[ f ] ];
  11404. vertexColors = face.vertexColors;
  11405. faceColor = face.color;
  11406. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  11407. c1 = vertexColors[ 0 ];
  11408. c2 = vertexColors[ 1 ];
  11409. c3 = vertexColors[ 2 ];
  11410. c4 = vertexColors[ 3 ];
  11411. } else {
  11412. c1 = faceColor;
  11413. c2 = faceColor;
  11414. c3 = faceColor;
  11415. c4 = faceColor;
  11416. }
  11417. colorArray[ offset_color ] = c1.r;
  11418. colorArray[ offset_color + 1 ] = c1.g;
  11419. colorArray[ offset_color + 2 ] = c1.b;
  11420. colorArray[ offset_color + 3 ] = c2.r;
  11421. colorArray[ offset_color + 4 ] = c2.g;
  11422. colorArray[ offset_color + 5 ] = c2.b;
  11423. colorArray[ offset_color + 6 ] = c3.r;
  11424. colorArray[ offset_color + 7 ] = c3.g;
  11425. colorArray[ offset_color + 8 ] = c3.b;
  11426. colorArray[ offset_color + 9 ] = c4.r;
  11427. colorArray[ offset_color + 10 ] = c4.g;
  11428. colorArray[ offset_color + 11 ] = c4.b;
  11429. offset_color += 12;
  11430. }
  11431. if ( offset_color > 0 ) {
  11432. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  11433. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11434. }
  11435. }
  11436. if ( dirtyTangents && geometry.hasTangents ) {
  11437. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11438. face = obj_faces[ chunk_faces3[ f ] ];
  11439. vertexTangents = face.vertexTangents;
  11440. t1 = vertexTangents[ 0 ];
  11441. t2 = vertexTangents[ 1 ];
  11442. t3 = vertexTangents[ 2 ];
  11443. tangentArray[ offset_tangent ] = t1.x;
  11444. tangentArray[ offset_tangent + 1 ] = t1.y;
  11445. tangentArray[ offset_tangent + 2 ] = t1.z;
  11446. tangentArray[ offset_tangent + 3 ] = t1.w;
  11447. tangentArray[ offset_tangent + 4 ] = t2.x;
  11448. tangentArray[ offset_tangent + 5 ] = t2.y;
  11449. tangentArray[ offset_tangent + 6 ] = t2.z;
  11450. tangentArray[ offset_tangent + 7 ] = t2.w;
  11451. tangentArray[ offset_tangent + 8 ] = t3.x;
  11452. tangentArray[ offset_tangent + 9 ] = t3.y;
  11453. tangentArray[ offset_tangent + 10 ] = t3.z;
  11454. tangentArray[ offset_tangent + 11 ] = t3.w;
  11455. offset_tangent += 12;
  11456. }
  11457. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11458. face = obj_faces[ chunk_faces4[ f ] ];
  11459. vertexTangents = face.vertexTangents;
  11460. t1 = vertexTangents[ 0 ];
  11461. t2 = vertexTangents[ 1 ];
  11462. t3 = vertexTangents[ 2 ];
  11463. t4 = vertexTangents[ 3 ];
  11464. tangentArray[ offset_tangent ] = t1.x;
  11465. tangentArray[ offset_tangent + 1 ] = t1.y;
  11466. tangentArray[ offset_tangent + 2 ] = t1.z;
  11467. tangentArray[ offset_tangent + 3 ] = t1.w;
  11468. tangentArray[ offset_tangent + 4 ] = t2.x;
  11469. tangentArray[ offset_tangent + 5 ] = t2.y;
  11470. tangentArray[ offset_tangent + 6 ] = t2.z;
  11471. tangentArray[ offset_tangent + 7 ] = t2.w;
  11472. tangentArray[ offset_tangent + 8 ] = t3.x;
  11473. tangentArray[ offset_tangent + 9 ] = t3.y;
  11474. tangentArray[ offset_tangent + 10 ] = t3.z;
  11475. tangentArray[ offset_tangent + 11 ] = t3.w;
  11476. tangentArray[ offset_tangent + 12 ] = t4.x;
  11477. tangentArray[ offset_tangent + 13 ] = t4.y;
  11478. tangentArray[ offset_tangent + 14 ] = t4.z;
  11479. tangentArray[ offset_tangent + 15 ] = t4.w;
  11480. offset_tangent += 16;
  11481. }
  11482. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  11483. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  11484. }
  11485. if ( dirtyNormals && normalType ) {
  11486. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11487. face = obj_faces[ chunk_faces3[ f ] ];
  11488. vertexNormals = face.vertexNormals;
  11489. faceNormal = face.normal;
  11490. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  11491. for ( i = 0; i < 3; i ++ ) {
  11492. vn = vertexNormals[ i ];
  11493. normalArray[ offset_normal ] = vn.x;
  11494. normalArray[ offset_normal + 1 ] = vn.y;
  11495. normalArray[ offset_normal + 2 ] = vn.z;
  11496. offset_normal += 3;
  11497. }
  11498. } else {
  11499. for ( i = 0; i < 3; i ++ ) {
  11500. normalArray[ offset_normal ] = faceNormal.x;
  11501. normalArray[ offset_normal + 1 ] = faceNormal.y;
  11502. normalArray[ offset_normal + 2 ] = faceNormal.z;
  11503. offset_normal += 3;
  11504. }
  11505. }
  11506. }
  11507. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11508. face = obj_faces[ chunk_faces4[ f ] ];
  11509. vertexNormals = face.vertexNormals;
  11510. faceNormal = face.normal;
  11511. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  11512. for ( i = 0; i < 4; i ++ ) {
  11513. vn = vertexNormals[ i ];
  11514. normalArray[ offset_normal ] = vn.x;
  11515. normalArray[ offset_normal + 1 ] = vn.y;
  11516. normalArray[ offset_normal + 2 ] = vn.z;
  11517. offset_normal += 3;
  11518. }
  11519. } else {
  11520. for ( i = 0; i < 4; i ++ ) {
  11521. normalArray[ offset_normal ] = faceNormal.x;
  11522. normalArray[ offset_normal + 1 ] = faceNormal.y;
  11523. normalArray[ offset_normal + 2 ] = faceNormal.z;
  11524. offset_normal += 3;
  11525. }
  11526. }
  11527. }
  11528. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  11529. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  11530. }
  11531. if ( dirtyUvs && obj_uvs && uvType ) {
  11532. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11533. fi = chunk_faces3[ f ];
  11534. uv = obj_uvs[ fi ];
  11535. if ( uv === undefined ) continue;
  11536. for ( i = 0; i < 3; i ++ ) {
  11537. uvi = uv[ i ];
  11538. uvArray[ offset_uv ] = uvi.x;
  11539. uvArray[ offset_uv + 1 ] = uvi.y;
  11540. offset_uv += 2;
  11541. }
  11542. }
  11543. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11544. fi = chunk_faces4[ f ];
  11545. uv = obj_uvs[ fi ];
  11546. if ( uv === undefined ) continue;
  11547. for ( i = 0; i < 4; i ++ ) {
  11548. uvi = uv[ i ];
  11549. uvArray[ offset_uv ] = uvi.x;
  11550. uvArray[ offset_uv + 1 ] = uvi.y;
  11551. offset_uv += 2;
  11552. }
  11553. }
  11554. if ( offset_uv > 0 ) {
  11555. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  11556. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  11557. }
  11558. }
  11559. if ( dirtyUvs && obj_uvs2 && uvType ) {
  11560. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11561. fi = chunk_faces3[ f ];
  11562. uv2 = obj_uvs2[ fi ];
  11563. if ( uv2 === undefined ) continue;
  11564. for ( i = 0; i < 3; i ++ ) {
  11565. uv2i = uv2[ i ];
  11566. uv2Array[ offset_uv2 ] = uv2i.x;
  11567. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  11568. offset_uv2 += 2;
  11569. }
  11570. }
  11571. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11572. fi = chunk_faces4[ f ];
  11573. uv2 = obj_uvs2[ fi ];
  11574. if ( uv2 === undefined ) continue;
  11575. for ( i = 0; i < 4; i ++ ) {
  11576. uv2i = uv2[ i ];
  11577. uv2Array[ offset_uv2 ] = uv2i.x;
  11578. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  11579. offset_uv2 += 2;
  11580. }
  11581. }
  11582. if ( offset_uv2 > 0 ) {
  11583. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  11584. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  11585. }
  11586. }
  11587. if ( dirtyElements ) {
  11588. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11589. faceArray[ offset_face ] = vertexIndex;
  11590. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  11591. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  11592. offset_face += 3;
  11593. lineArray[ offset_line ] = vertexIndex;
  11594. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  11595. lineArray[ offset_line + 2 ] = vertexIndex;
  11596. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  11597. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  11598. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  11599. offset_line += 6;
  11600. vertexIndex += 3;
  11601. }
  11602. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11603. faceArray[ offset_face ] = vertexIndex;
  11604. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  11605. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  11606. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  11607. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  11608. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  11609. offset_face += 6;
  11610. lineArray[ offset_line ] = vertexIndex;
  11611. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  11612. lineArray[ offset_line + 2 ] = vertexIndex;
  11613. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  11614. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  11615. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  11616. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  11617. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  11618. offset_line += 8;
  11619. vertexIndex += 4;
  11620. }
  11621. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  11622. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  11623. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  11624. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  11625. }
  11626. if ( customAttributes ) {
  11627. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11628. customAttribute = customAttributes[ i ];
  11629. if ( ! customAttribute.__original.needsUpdate ) continue;
  11630. offset_custom = 0;
  11631. offset_customSrc = 0;
  11632. if ( customAttribute.size === 1 ) {
  11633. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11634. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11635. face = obj_faces[ chunk_faces3[ f ] ];
  11636. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  11637. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  11638. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  11639. offset_custom += 3;
  11640. }
  11641. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11642. face = obj_faces[ chunk_faces4[ f ] ];
  11643. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  11644. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  11645. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  11646. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  11647. offset_custom += 4;
  11648. }
  11649. } else if ( customAttribute.boundTo === "faces" ) {
  11650. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11651. value = customAttribute.value[ chunk_faces3[ f ] ];
  11652. customAttribute.array[ offset_custom ] = value;
  11653. customAttribute.array[ offset_custom + 1 ] = value;
  11654. customAttribute.array[ offset_custom + 2 ] = value;
  11655. offset_custom += 3;
  11656. }
  11657. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11658. value = customAttribute.value[ chunk_faces4[ f ] ];
  11659. customAttribute.array[ offset_custom ] = value;
  11660. customAttribute.array[ offset_custom + 1 ] = value;
  11661. customAttribute.array[ offset_custom + 2 ] = value;
  11662. customAttribute.array[ offset_custom + 3 ] = value;
  11663. offset_custom += 4;
  11664. }
  11665. }
  11666. } else if ( customAttribute.size === 2 ) {
  11667. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11668. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11669. face = obj_faces[ chunk_faces3[ f ] ];
  11670. v1 = customAttribute.value[ face.a ];
  11671. v2 = customAttribute.value[ face.b ];
  11672. v3 = customAttribute.value[ face.c ];
  11673. customAttribute.array[ offset_custom ] = v1.x;
  11674. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11675. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11676. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11677. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11678. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11679. offset_custom += 6;
  11680. }
  11681. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11682. face = obj_faces[ chunk_faces4[ f ] ];
  11683. v1 = customAttribute.value[ face.a ];
  11684. v2 = customAttribute.value[ face.b ];
  11685. v3 = customAttribute.value[ face.c ];
  11686. v4 = customAttribute.value[ face.d ];
  11687. customAttribute.array[ offset_custom ] = v1.x;
  11688. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11689. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11690. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11691. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11692. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11693. customAttribute.array[ offset_custom + 6 ] = v4.x;
  11694. customAttribute.array[ offset_custom + 7 ] = v4.y;
  11695. offset_custom += 8;
  11696. }
  11697. } else if ( customAttribute.boundTo === "faces" ) {
  11698. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11699. value = customAttribute.value[ chunk_faces3[ f ] ];
  11700. v1 = value;
  11701. v2 = value;
  11702. v3 = value;
  11703. customAttribute.array[ offset_custom ] = v1.x;
  11704. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11705. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11706. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11707. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11708. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11709. offset_custom += 6;
  11710. }
  11711. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11712. value = customAttribute.value[ chunk_faces4[ f ] ];
  11713. v1 = value;
  11714. v2 = value;
  11715. v3 = value;
  11716. v4 = value;
  11717. customAttribute.array[ offset_custom ] = v1.x;
  11718. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11719. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11720. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11721. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11722. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11723. customAttribute.array[ offset_custom + 6 ] = v4.x;
  11724. customAttribute.array[ offset_custom + 7 ] = v4.y;
  11725. offset_custom += 8;
  11726. }
  11727. }
  11728. } else if ( customAttribute.size === 3 ) {
  11729. var pp;
  11730. if ( customAttribute.type === "c" ) {
  11731. pp = [ "r", "g", "b" ];
  11732. } else {
  11733. pp = [ "x", "y", "z" ];
  11734. }
  11735. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11736. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11737. face = obj_faces[ chunk_faces3[ f ] ];
  11738. v1 = customAttribute.value[ face.a ];
  11739. v2 = customAttribute.value[ face.b ];
  11740. v3 = customAttribute.value[ face.c ];
  11741. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11742. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11743. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11744. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11745. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11746. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11747. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11748. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11749. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11750. offset_custom += 9;
  11751. }
  11752. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11753. face = obj_faces[ chunk_faces4[ f ] ];
  11754. v1 = customAttribute.value[ face.a ];
  11755. v2 = customAttribute.value[ face.b ];
  11756. v3 = customAttribute.value[ face.c ];
  11757. v4 = customAttribute.value[ face.d ];
  11758. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11759. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11760. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11761. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11762. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11763. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11764. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11765. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11766. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11767. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11768. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11769. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11770. offset_custom += 12;
  11771. }
  11772. } else if ( customAttribute.boundTo === "faces" ) {
  11773. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11774. value = customAttribute.value[ chunk_faces3[ f ] ];
  11775. v1 = value;
  11776. v2 = value;
  11777. v3 = value;
  11778. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11779. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11780. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11781. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11782. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11783. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11784. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11785. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11786. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11787. offset_custom += 9;
  11788. }
  11789. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11790. value = customAttribute.value[ chunk_faces4[ f ] ];
  11791. v1 = value;
  11792. v2 = value;
  11793. v3 = value;
  11794. v4 = value;
  11795. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11796. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11797. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11798. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11799. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11800. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11801. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11802. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11803. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11804. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11805. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11806. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11807. offset_custom += 12;
  11808. }
  11809. } else if ( customAttribute.boundTo === "faceVertices" ) {
  11810. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11811. value = customAttribute.value[ chunk_faces3[ f ] ];
  11812. v1 = value[ 0 ];
  11813. v2 = value[ 1 ];
  11814. v3 = value[ 2 ];
  11815. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11816. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11817. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11818. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11819. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11820. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11821. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11822. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11823. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11824. offset_custom += 9;
  11825. }
  11826. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11827. value = customAttribute.value[ chunk_faces4[ f ] ];
  11828. v1 = value[ 0 ];
  11829. v2 = value[ 1 ];
  11830. v3 = value[ 2 ];
  11831. v4 = value[ 3 ];
  11832. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11833. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11834. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11835. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11836. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11837. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11838. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11839. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11840. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11841. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11842. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11843. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11844. offset_custom += 12;
  11845. }
  11846. }
  11847. } else if ( customAttribute.size === 4 ) {
  11848. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11849. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11850. face = obj_faces[ chunk_faces3[ f ] ];
  11851. v1 = customAttribute.value[ face.a ];
  11852. v2 = customAttribute.value[ face.b ];
  11853. v3 = customAttribute.value[ face.c ];
  11854. customAttribute.array[ offset_custom ] = v1.x;
  11855. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11856. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11857. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11858. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11859. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11860. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11861. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11862. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11863. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11864. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11865. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11866. offset_custom += 12;
  11867. }
  11868. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11869. face = obj_faces[ chunk_faces4[ f ] ];
  11870. v1 = customAttribute.value[ face.a ];
  11871. v2 = customAttribute.value[ face.b ];
  11872. v3 = customAttribute.value[ face.c ];
  11873. v4 = customAttribute.value[ face.d ];
  11874. customAttribute.array[ offset_custom ] = v1.x;
  11875. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11876. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11877. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11878. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11879. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11880. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11881. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11882. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11883. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11884. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11885. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11886. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11887. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11888. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11889. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11890. offset_custom += 16;
  11891. }
  11892. } else if ( customAttribute.boundTo === "faces" ) {
  11893. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11894. value = customAttribute.value[ chunk_faces3[ f ] ];
  11895. v1 = value;
  11896. v2 = value;
  11897. v3 = value;
  11898. customAttribute.array[ offset_custom ] = v1.x;
  11899. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11900. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11901. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11902. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11903. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11904. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11905. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11906. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11907. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11908. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11909. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11910. offset_custom += 12;
  11911. }
  11912. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11913. value = customAttribute.value[ chunk_faces4[ f ] ];
  11914. v1 = value;
  11915. v2 = value;
  11916. v3 = value;
  11917. v4 = value;
  11918. customAttribute.array[ offset_custom ] = v1.x;
  11919. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11920. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11921. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11922. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11923. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11924. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11925. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11926. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11927. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11928. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11929. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11930. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11931. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11932. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11933. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11934. offset_custom += 16;
  11935. }
  11936. } else if ( customAttribute.boundTo === "faceVertices" ) {
  11937. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11938. value = customAttribute.value[ chunk_faces3[ f ] ];
  11939. v1 = value[ 0 ];
  11940. v2 = value[ 1 ];
  11941. v3 = value[ 2 ];
  11942. customAttribute.array[ offset_custom ] = v1.x;
  11943. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11944. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11945. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11946. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11947. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11948. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11949. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11950. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11951. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11952. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11953. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11954. offset_custom += 12;
  11955. }
  11956. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11957. value = customAttribute.value[ chunk_faces4[ f ] ];
  11958. v1 = value[ 0 ];
  11959. v2 = value[ 1 ];
  11960. v3 = value[ 2 ];
  11961. v4 = value[ 3 ];
  11962. customAttribute.array[ offset_custom ] = v1.x;
  11963. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11964. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11965. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11966. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11967. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11968. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11969. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11970. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11971. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11972. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11973. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11974. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11975. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11976. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11977. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11978. offset_custom += 16;
  11979. }
  11980. }
  11981. }
  11982. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11983. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11984. }
  11985. }
  11986. if ( dispose ) {
  11987. delete geometryGroup.__inittedArrays;
  11988. delete geometryGroup.__colorArray;
  11989. delete geometryGroup.__normalArray;
  11990. delete geometryGroup.__tangentArray;
  11991. delete geometryGroup.__uvArray;
  11992. delete geometryGroup.__uv2Array;
  11993. delete geometryGroup.__faceArray;
  11994. delete geometryGroup.__vertexArray;
  11995. delete geometryGroup.__lineArray;
  11996. delete geometryGroup.__skinIndexArray;
  11997. delete geometryGroup.__skinWeightArray;
  11998. }
  11999. };
  12000. function setDirectBuffers ( geometry, hint, dispose ) {
  12001. var attributes = geometry.attributes;
  12002. var index = attributes[ "index" ];
  12003. var position = attributes[ "position" ];
  12004. var normal = attributes[ "normal" ];
  12005. var uv = attributes[ "uv" ];
  12006. var color = attributes[ "color" ];
  12007. var tangent = attributes[ "tangent" ];
  12008. if ( geometry.elementsNeedUpdate && index !== undefined ) {
  12009. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12010. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, index.array, hint );
  12011. }
  12012. if ( geometry.verticesNeedUpdate && position !== undefined ) {
  12013. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12014. _gl.bufferData( _gl.ARRAY_BUFFER, position.array, hint );
  12015. }
  12016. if ( geometry.normalsNeedUpdate && normal !== undefined ) {
  12017. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  12018. _gl.bufferData( _gl.ARRAY_BUFFER, normal.array, hint );
  12019. }
  12020. if ( geometry.uvsNeedUpdate && uv !== undefined ) {
  12021. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  12022. _gl.bufferData( _gl.ARRAY_BUFFER, uv.array, hint );
  12023. }
  12024. if ( geometry.colorsNeedUpdate && color !== undefined ) {
  12025. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12026. _gl.bufferData( _gl.ARRAY_BUFFER, color.array, hint );
  12027. }
  12028. if ( geometry.tangentsNeedUpdate && tangent !== undefined ) {
  12029. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  12030. _gl.bufferData( _gl.ARRAY_BUFFER, tangent.array, hint );
  12031. }
  12032. if ( dispose ) {
  12033. for ( var i in geometry.attributes ) {
  12034. delete geometry.attributes[ i ].array;
  12035. }
  12036. }
  12037. };
  12038. // Buffer rendering
  12039. this.renderBufferImmediate = function ( object, program, material ) {
  12040. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  12041. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  12042. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  12043. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  12044. if ( object.hasPositions ) {
  12045. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  12046. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  12047. _gl.enableVertexAttribArray( program.attributes.position );
  12048. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12049. }
  12050. if ( object.hasNormals ) {
  12051. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  12052. if ( material.shading === THREE.FlatShading ) {
  12053. var nx, ny, nz,
  12054. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  12055. normalArray,
  12056. i, il = object.count * 3;
  12057. for( i = 0; i < il; i += 9 ) {
  12058. normalArray = object.normalArray;
  12059. nax = normalArray[ i ];
  12060. nay = normalArray[ i + 1 ];
  12061. naz = normalArray[ i + 2 ];
  12062. nbx = normalArray[ i + 3 ];
  12063. nby = normalArray[ i + 4 ];
  12064. nbz = normalArray[ i + 5 ];
  12065. ncx = normalArray[ i + 6 ];
  12066. ncy = normalArray[ i + 7 ];
  12067. ncz = normalArray[ i + 8 ];
  12068. nx = ( nax + nbx + ncx ) / 3;
  12069. ny = ( nay + nby + ncy ) / 3;
  12070. nz = ( naz + nbz + ncz ) / 3;
  12071. normalArray[ i ] = nx;
  12072. normalArray[ i + 1 ] = ny;
  12073. normalArray[ i + 2 ] = nz;
  12074. normalArray[ i + 3 ] = nx;
  12075. normalArray[ i + 4 ] = ny;
  12076. normalArray[ i + 5 ] = nz;
  12077. normalArray[ i + 6 ] = nx;
  12078. normalArray[ i + 7 ] = ny;
  12079. normalArray[ i + 8 ] = nz;
  12080. }
  12081. }
  12082. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  12083. _gl.enableVertexAttribArray( program.attributes.normal );
  12084. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12085. }
  12086. if ( object.hasUvs && material.map ) {
  12087. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  12088. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  12089. _gl.enableVertexAttribArray( program.attributes.uv );
  12090. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12091. }
  12092. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  12093. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  12094. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  12095. _gl.enableVertexAttribArray( program.attributes.color );
  12096. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12097. }
  12098. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  12099. object.count = 0;
  12100. };
  12101. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  12102. if ( material.visible === false ) return;
  12103. var program, attributes, linewidth, primitives, a, attribute;
  12104. program = setProgram( camera, lights, fog, material, object );
  12105. attributes = program.attributes;
  12106. var updateBuffers = false,
  12107. wireframeBit = material.wireframe ? 1 : 0,
  12108. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  12109. if ( geometryHash !== _currentGeometryGroupHash ) {
  12110. _currentGeometryGroupHash = geometryHash;
  12111. updateBuffers = true;
  12112. }
  12113. if ( updateBuffers ) {
  12114. disableAttributes();
  12115. }
  12116. // render mesh
  12117. if ( object instanceof THREE.Mesh ) {
  12118. var index = geometry.attributes[ "index" ];
  12119. // indexed triangles
  12120. if ( index ) {
  12121. var offsets = geometry.offsets;
  12122. // if there is more than 1 chunk
  12123. // must set attribute pointers to use new offsets for each chunk
  12124. // even if geometry and materials didn't change
  12125. if ( offsets.length > 1 ) updateBuffers = true;
  12126. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  12127. var startIndex = offsets[ i ].index;
  12128. if ( updateBuffers ) {
  12129. // vertices
  12130. var position = geometry.attributes[ "position" ];
  12131. var positionSize = position.itemSize;
  12132. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12133. enableAttribute( attributes.position );
  12134. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, startIndex * positionSize * 4 ); // 4 bytes per Float32
  12135. // normals
  12136. var normal = geometry.attributes[ "normal" ];
  12137. if ( attributes.normal >= 0 && normal ) {
  12138. var normalSize = normal.itemSize;
  12139. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  12140. enableAttribute( attributes.normal );
  12141. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, startIndex * normalSize * 4 );
  12142. }
  12143. // uvs
  12144. var uv = geometry.attributes[ "uv" ];
  12145. if ( attributes.uv >= 0 && uv ) {
  12146. var uvSize = uv.itemSize;
  12147. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  12148. enableAttribute( attributes.uv );
  12149. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, startIndex * uvSize * 4 );
  12150. }
  12151. // colors
  12152. var color = geometry.attributes[ "color" ];
  12153. if ( attributes.color >= 0 && color ) {
  12154. var colorSize = color.itemSize;
  12155. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12156. enableAttribute( attributes.color );
  12157. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, startIndex * colorSize * 4 );
  12158. }
  12159. // tangents
  12160. var tangent = geometry.attributes[ "tangent" ];
  12161. if ( attributes.tangent >= 0 && tangent ) {
  12162. var tangentSize = tangent.itemSize;
  12163. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  12164. enableAttribute( attributes.tangent );
  12165. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, startIndex * tangentSize * 4 );
  12166. }
  12167. // indices
  12168. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12169. }
  12170. // render indexed triangles
  12171. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  12172. _this.info.render.calls ++;
  12173. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  12174. _this.info.render.faces += offsets[ i ].count / 3;
  12175. }
  12176. // non-indexed triangles
  12177. } else {
  12178. if ( updateBuffers ) {
  12179. // vertices
  12180. var position = geometry.attributes[ "position" ];
  12181. var positionSize = position.itemSize;
  12182. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12183. enableAttribute( attributes.position );
  12184. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  12185. // normals
  12186. var normal = geometry.attributes[ "normal" ];
  12187. if ( attributes.normal >= 0 && normal ) {
  12188. var normalSize = normal.itemSize;
  12189. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  12190. enableAttribute( attributes.normal );
  12191. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, 0 );
  12192. }
  12193. // uvs
  12194. var uv = geometry.attributes[ "uv" ];
  12195. if ( attributes.uv >= 0 && uv ) {
  12196. var uvSize = uv.itemSize;
  12197. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  12198. enableAttribute( attributes.uv );
  12199. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, 0 );
  12200. }
  12201. // colors
  12202. var color = geometry.attributes[ "color" ];
  12203. if ( attributes.color >= 0 && color ) {
  12204. var colorSize = color.itemSize;
  12205. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12206. enableAttribute( attributes.color );
  12207. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  12208. }
  12209. // tangents
  12210. var tangent = geometry.attributes[ "tangent" ];
  12211. if ( attributes.tangent >= 0 && tangent ) {
  12212. var tangentSize = tangent.itemSize;
  12213. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  12214. enableAttribute( attributes.tangent );
  12215. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, 0 );
  12216. }
  12217. }
  12218. // render non-indexed triangles
  12219. _gl.drawArrays( _gl.TRIANGLES, 0, position.numItems / 3 );
  12220. _this.info.render.calls ++;
  12221. _this.info.render.vertices += position.numItems / 3;
  12222. _this.info.render.faces += position.numItems / 3 / 3;
  12223. }
  12224. // render particles
  12225. } else if ( object instanceof THREE.ParticleSystem ) {
  12226. if ( updateBuffers ) {
  12227. // vertices
  12228. var position = geometry.attributes[ "position" ];
  12229. var positionSize = position.itemSize;
  12230. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12231. enableAttribute( attributes.position );
  12232. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  12233. // colors
  12234. var color = geometry.attributes[ "color" ];
  12235. if ( attributes.color >= 0 && color ) {
  12236. var colorSize = color.itemSize;
  12237. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12238. enableAttribute( attributes.color );
  12239. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  12240. }
  12241. // render particles
  12242. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  12243. _this.info.render.calls ++;
  12244. _this.info.render.points += position.numItems / 3;
  12245. }
  12246. } else if ( object instanceof THREE.Line ) {
  12247. if ( updateBuffers ) {
  12248. // vertices
  12249. var position = geometry.attributes[ "position" ];
  12250. var positionSize = position.itemSize;
  12251. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12252. enableAttribute( attributes.position );
  12253. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  12254. // colors
  12255. var color = geometry.attributes[ "color" ];
  12256. if ( attributes.color >= 0 && color ) {
  12257. var colorSize = color.itemSize;
  12258. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12259. enableAttribute( attributes.color );
  12260. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  12261. }
  12262. // render lines
  12263. _gl.drawArrays( _gl.LINE_STRIP, 0, position.numItems / 3 );
  12264. _this.info.render.calls ++;
  12265. _this.info.render.points += position.numItems;
  12266. }
  12267. }
  12268. };
  12269. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  12270. if ( material.visible === false ) return;
  12271. var program, attributes, linewidth, primitives, a, attribute, i, il;
  12272. program = setProgram( camera, lights, fog, material, object );
  12273. attributes = program.attributes;
  12274. var updateBuffers = false,
  12275. wireframeBit = material.wireframe ? 1 : 0,
  12276. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  12277. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  12278. _currentGeometryGroupHash = geometryGroupHash;
  12279. updateBuffers = true;
  12280. }
  12281. if ( updateBuffers ) {
  12282. disableAttributes();
  12283. }
  12284. // vertices
  12285. if ( !material.morphTargets && attributes.position >= 0 ) {
  12286. if ( updateBuffers ) {
  12287. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12288. enableAttribute( attributes.position );
  12289. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12290. }
  12291. } else {
  12292. if ( object.morphTargetBase ) {
  12293. setupMorphTargets( material, geometryGroup, object );
  12294. }
  12295. }
  12296. if ( updateBuffers ) {
  12297. // custom attributes
  12298. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  12299. if ( geometryGroup.__webglCustomAttributesList ) {
  12300. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  12301. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  12302. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  12303. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  12304. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  12305. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  12306. }
  12307. }
  12308. }
  12309. // colors
  12310. if ( attributes.color >= 0 ) {
  12311. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12312. enableAttribute( attributes.color );
  12313. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12314. }
  12315. // normals
  12316. if ( attributes.normal >= 0 ) {
  12317. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12318. enableAttribute( attributes.normal );
  12319. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12320. }
  12321. // tangents
  12322. if ( attributes.tangent >= 0 ) {
  12323. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12324. enableAttribute( attributes.tangent );
  12325. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  12326. }
  12327. // uvs
  12328. if ( attributes.uv >= 0 ) {
  12329. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12330. enableAttribute( attributes.uv );
  12331. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12332. }
  12333. if ( attributes.uv2 >= 0 ) {
  12334. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12335. enableAttribute( attributes.uv2 );
  12336. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  12337. }
  12338. if ( material.skinning &&
  12339. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  12340. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  12341. enableAttribute( attributes.skinIndex );
  12342. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  12343. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  12344. enableAttribute( attributes.skinWeight );
  12345. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  12346. }
  12347. // line distances
  12348. if ( attributes.lineDistance >= 0 ) {
  12349. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  12350. enableAttribute( attributes.lineDistance );
  12351. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  12352. }
  12353. }
  12354. // render mesh
  12355. if ( object instanceof THREE.Mesh ) {
  12356. // wireframe
  12357. if ( material.wireframe ) {
  12358. setLineWidth( material.wireframeLinewidth );
  12359. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  12360. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  12361. // triangles
  12362. } else {
  12363. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12364. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  12365. }
  12366. _this.info.render.calls ++;
  12367. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  12368. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  12369. // render lines
  12370. } else if ( object instanceof THREE.Line ) {
  12371. primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  12372. setLineWidth( material.linewidth );
  12373. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  12374. _this.info.render.calls ++;
  12375. // render particles
  12376. } else if ( object instanceof THREE.ParticleSystem ) {
  12377. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  12378. _this.info.render.calls ++;
  12379. _this.info.render.points += geometryGroup.__webglParticleCount;
  12380. // render ribbon
  12381. } else if ( object instanceof THREE.Ribbon ) {
  12382. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  12383. _this.info.render.calls ++;
  12384. }
  12385. };
  12386. function enableAttribute( attribute ) {
  12387. if ( ! _enabledAttributes[ attribute ] ) {
  12388. _gl.enableVertexAttribArray( attribute );
  12389. _enabledAttributes[ attribute ] = true;
  12390. }
  12391. };
  12392. function disableAttributes() {
  12393. for ( var attribute in _enabledAttributes ) {
  12394. if ( _enabledAttributes[ attribute ] ) {
  12395. _gl.disableVertexAttribArray( attribute );
  12396. _enabledAttributes[ attribute ] = false;
  12397. }
  12398. }
  12399. };
  12400. function setupMorphTargets ( material, geometryGroup, object ) {
  12401. // set base
  12402. var attributes = material.program.attributes;
  12403. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  12404. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  12405. enableAttribute( attributes.position );
  12406. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12407. } else if ( attributes.position >= 0 ) {
  12408. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12409. enableAttribute( attributes.position );
  12410. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12411. }
  12412. if ( object.morphTargetForcedOrder.length ) {
  12413. // set forced order
  12414. var m = 0;
  12415. var order = object.morphTargetForcedOrder;
  12416. var influences = object.morphTargetInfluences;
  12417. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  12418. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  12419. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  12420. enableAttribute( attributes[ "morphTarget" + m ] );
  12421. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12422. }
  12423. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  12424. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  12425. enableAttribute( attributes[ "morphNormal" + m ] );
  12426. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12427. }
  12428. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  12429. m ++;
  12430. }
  12431. } else {
  12432. // find the most influencing
  12433. var influence, activeInfluenceIndices = [];
  12434. var influences = object.morphTargetInfluences;
  12435. var i, il = influences.length;
  12436. for ( i = 0; i < il; i ++ ) {
  12437. influence = influences[ i ];
  12438. if ( influence > 0 ) {
  12439. activeInfluenceIndices.push( [ influence, i ] );
  12440. }
  12441. }
  12442. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  12443. activeInfluenceIndices.sort( numericalSort );
  12444. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  12445. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  12446. activeInfluenceIndices.sort( numericalSort );
  12447. } else if ( activeInfluenceIndices.length === 0 ) {
  12448. activeInfluenceIndices.push( [ 0, 0 ] );
  12449. };
  12450. var influenceIndex, m = 0;
  12451. while ( m < material.numSupportedMorphTargets ) {
  12452. if ( activeInfluenceIndices[ m ] ) {
  12453. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  12454. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  12455. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  12456. enableAttribute( attributes[ "morphTarget" + m ] );
  12457. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12458. }
  12459. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  12460. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  12461. enableAttribute( attributes[ "morphNormal" + m ] );
  12462. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12463. }
  12464. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  12465. } else {
  12466. /*
  12467. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12468. if ( material.morphNormals ) {
  12469. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12470. }
  12471. */
  12472. object.__webglMorphTargetInfluences[ m ] = 0;
  12473. }
  12474. m ++;
  12475. }
  12476. }
  12477. // load updated influences uniform
  12478. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  12479. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  12480. }
  12481. };
  12482. // Sorting
  12483. function painterSortStable ( a, b ) {
  12484. if ( a.z !== b.z ) {
  12485. return b.z - a.z;
  12486. } else {
  12487. return b.id - a.id;
  12488. }
  12489. };
  12490. function numericalSort ( a, b ) {
  12491. return b[ 0 ] - a[ 0 ];
  12492. };
  12493. // Rendering
  12494. this.render = function ( scene, camera, renderTarget, forceClear ) {
  12495. if ( camera instanceof THREE.Camera === false ) {
  12496. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  12497. return;
  12498. }
  12499. var i, il,
  12500. webglObject, object,
  12501. renderList,
  12502. lights = scene.__lights,
  12503. fog = scene.fog;
  12504. // reset caching for this frame
  12505. _currentMaterialId = -1;
  12506. _lightsNeedUpdate = true;
  12507. // update scene graph
  12508. if ( this.autoUpdateScene ) scene.updateMatrixWorld();
  12509. // update camera matrices and frustum
  12510. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  12511. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  12512. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  12513. _frustum.setFromMatrix( _projScreenMatrix );
  12514. // update WebGL objects
  12515. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  12516. // custom render plugins (pre pass)
  12517. renderPlugins( this.renderPluginsPre, scene, camera );
  12518. //
  12519. _this.info.render.calls = 0;
  12520. _this.info.render.vertices = 0;
  12521. _this.info.render.faces = 0;
  12522. _this.info.render.points = 0;
  12523. this.setRenderTarget( renderTarget );
  12524. if ( this.autoClear || forceClear ) {
  12525. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  12526. }
  12527. // set matrices for regular objects (frustum culled)
  12528. renderList = scene.__webglObjects;
  12529. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  12530. webglObject = renderList[ i ];
  12531. object = webglObject.object;
  12532. webglObject.render = false;
  12533. if ( object.visible ) {
  12534. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  12535. setupMatrices( object, camera );
  12536. unrollBufferMaterial( webglObject );
  12537. webglObject.render = true;
  12538. if ( this.sortObjects === true ) {
  12539. if ( object.renderDepth !== null ) {
  12540. webglObject.z = object.renderDepth;
  12541. } else {
  12542. _vector3.copy( object.matrixWorld.getPosition() );
  12543. _vector3.applyMatrix4( _projScreenMatrix );
  12544. webglObject.z = _vector3.z;
  12545. }
  12546. webglObject.id = object.id;
  12547. }
  12548. }
  12549. }
  12550. }
  12551. if ( this.sortObjects ) {
  12552. renderList.sort( painterSortStable );
  12553. }
  12554. // set matrices for immediate objects
  12555. renderList = scene.__webglObjectsImmediate;
  12556. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  12557. webglObject = renderList[ i ];
  12558. object = webglObject.object;
  12559. if ( object.visible ) {
  12560. setupMatrices( object, camera );
  12561. unrollImmediateBufferMaterial( webglObject );
  12562. }
  12563. }
  12564. if ( scene.overrideMaterial ) {
  12565. var material = scene.overrideMaterial;
  12566. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  12567. this.setDepthTest( material.depthTest );
  12568. this.setDepthWrite( material.depthWrite );
  12569. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12570. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  12571. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  12572. } else {
  12573. var material = null;
  12574. // opaque pass (front-to-back order)
  12575. this.setBlending( THREE.NoBlending );
  12576. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  12577. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  12578. // transparent pass (back-to-front order)
  12579. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  12580. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  12581. }
  12582. // custom render plugins (post pass)
  12583. renderPlugins( this.renderPluginsPost, scene, camera );
  12584. // Generate mipmap if we're using any kind of mipmap filtering
  12585. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  12586. updateRenderTargetMipmap( renderTarget );
  12587. }
  12588. // Ensure depth buffer writing is enabled so it can be cleared on next render
  12589. this.setDepthTest( true );
  12590. this.setDepthWrite( true );
  12591. // _gl.finish();
  12592. };
  12593. function renderPlugins( plugins, scene, camera ) {
  12594. if ( ! plugins.length ) return;
  12595. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  12596. // reset state for plugin (to start from clean slate)
  12597. _currentProgram = null;
  12598. _currentCamera = null;
  12599. _oldBlending = -1;
  12600. _oldDepthTest = -1;
  12601. _oldDepthWrite = -1;
  12602. _oldDoubleSided = -1;
  12603. _oldFlipSided = -1;
  12604. _currentGeometryGroupHash = -1;
  12605. _currentMaterialId = -1;
  12606. _lightsNeedUpdate = true;
  12607. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  12608. // reset state after plugin (anything could have changed)
  12609. _currentProgram = null;
  12610. _currentCamera = null;
  12611. _oldBlending = -1;
  12612. _oldDepthTest = -1;
  12613. _oldDepthWrite = -1;
  12614. _oldDoubleSided = -1;
  12615. _oldFlipSided = -1;
  12616. _currentGeometryGroupHash = -1;
  12617. _currentMaterialId = -1;
  12618. _lightsNeedUpdate = true;
  12619. }
  12620. };
  12621. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  12622. var webglObject, object, buffer, material, start, end, delta;
  12623. if ( reverse ) {
  12624. start = renderList.length - 1;
  12625. end = -1;
  12626. delta = -1;
  12627. } else {
  12628. start = 0;
  12629. end = renderList.length;
  12630. delta = 1;
  12631. }
  12632. for ( var i = start; i !== end; i += delta ) {
  12633. webglObject = renderList[ i ];
  12634. if ( webglObject.render ) {
  12635. object = webglObject.object;
  12636. buffer = webglObject.buffer;
  12637. if ( overrideMaterial ) {
  12638. material = overrideMaterial;
  12639. } else {
  12640. material = webglObject[ materialType ];
  12641. if ( ! material ) continue;
  12642. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  12643. _this.setDepthTest( material.depthTest );
  12644. _this.setDepthWrite( material.depthWrite );
  12645. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12646. }
  12647. _this.setMaterialFaces( material );
  12648. if ( buffer instanceof THREE.BufferGeometry ) {
  12649. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  12650. } else {
  12651. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  12652. }
  12653. }
  12654. }
  12655. };
  12656. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  12657. var webglObject, object, material, program;
  12658. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  12659. webglObject = renderList[ i ];
  12660. object = webglObject.object;
  12661. if ( object.visible ) {
  12662. if ( overrideMaterial ) {
  12663. material = overrideMaterial;
  12664. } else {
  12665. material = webglObject[ materialType ];
  12666. if ( ! material ) continue;
  12667. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  12668. _this.setDepthTest( material.depthTest );
  12669. _this.setDepthWrite( material.depthWrite );
  12670. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12671. }
  12672. _this.renderImmediateObject( camera, lights, fog, material, object );
  12673. }
  12674. }
  12675. };
  12676. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  12677. var program = setProgram( camera, lights, fog, material, object );
  12678. _currentGeometryGroupHash = -1;
  12679. _this.setMaterialFaces( material );
  12680. if ( object.immediateRenderCallback ) {
  12681. object.immediateRenderCallback( program, _gl, _frustum );
  12682. } else {
  12683. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  12684. }
  12685. };
  12686. function unrollImmediateBufferMaterial ( globject ) {
  12687. var object = globject.object,
  12688. material = object.material;
  12689. if ( material.transparent ) {
  12690. globject.transparent = material;
  12691. globject.opaque = null;
  12692. } else {
  12693. globject.opaque = material;
  12694. globject.transparent = null;
  12695. }
  12696. };
  12697. function unrollBufferMaterial ( globject ) {
  12698. var object = globject.object,
  12699. buffer = globject.buffer,
  12700. material, materialIndex, meshMaterial;
  12701. meshMaterial = object.material;
  12702. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  12703. materialIndex = buffer.materialIndex;
  12704. material = meshMaterial.materials[ materialIndex ];
  12705. if ( material.transparent ) {
  12706. globject.transparent = material;
  12707. globject.opaque = null;
  12708. } else {
  12709. globject.opaque = material;
  12710. globject.transparent = null;
  12711. }
  12712. } else {
  12713. material = meshMaterial;
  12714. if ( material ) {
  12715. if ( material.transparent ) {
  12716. globject.transparent = material;
  12717. globject.opaque = null;
  12718. } else {
  12719. globject.opaque = material;
  12720. globject.transparent = null;
  12721. }
  12722. }
  12723. }
  12724. };
  12725. // Geometry splitting
  12726. function sortFacesByMaterial ( geometry, material ) {
  12727. var f, fl, face, materialIndex, vertices,
  12728. groupHash, hash_map = {};
  12729. var numMorphTargets = geometry.morphTargets.length;
  12730. var numMorphNormals = geometry.morphNormals.length;
  12731. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  12732. geometry.geometryGroups = {};
  12733. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  12734. face = geometry.faces[ f ];
  12735. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  12736. if ( hash_map[ materialIndex ] === undefined ) {
  12737. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  12738. }
  12739. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  12740. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  12741. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  12742. }
  12743. vertices = face instanceof THREE.Face3 ? 3 : 4;
  12744. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  12745. hash_map[ materialIndex ].counter += 1;
  12746. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  12747. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  12748. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  12749. }
  12750. }
  12751. if ( face instanceof THREE.Face3 ) {
  12752. geometry.geometryGroups[ groupHash ].faces3.push( f );
  12753. } else {
  12754. geometry.geometryGroups[ groupHash ].faces4.push( f );
  12755. }
  12756. geometry.geometryGroups[ groupHash ].vertices += vertices;
  12757. }
  12758. geometry.geometryGroupsList = [];
  12759. for ( var g in geometry.geometryGroups ) {
  12760. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  12761. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  12762. }
  12763. };
  12764. // Objects refresh
  12765. this.initWebGLObjects = function ( scene ) {
  12766. if ( !scene.__webglObjects ) {
  12767. scene.__webglObjects = [];
  12768. scene.__webglObjectsImmediate = [];
  12769. scene.__webglSprites = [];
  12770. scene.__webglFlares = [];
  12771. }
  12772. while ( scene.__objectsAdded.length ) {
  12773. addObject( scene.__objectsAdded[ 0 ], scene );
  12774. scene.__objectsAdded.splice( 0, 1 );
  12775. }
  12776. while ( scene.__objectsRemoved.length ) {
  12777. removeObject( scene.__objectsRemoved[ 0 ], scene );
  12778. scene.__objectsRemoved.splice( 0, 1 );
  12779. }
  12780. // update must be called after objects adding / removal
  12781. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  12782. updateObject( scene.__webglObjects[ o ].object );
  12783. }
  12784. };
  12785. // Objects adding
  12786. function addObject ( object, scene ) {
  12787. var g, geometry, material, geometryGroup;
  12788. if ( ! object.__webglInit ) {
  12789. object.__webglInit = true;
  12790. object._modelViewMatrix = new THREE.Matrix4();
  12791. object._normalMatrix = new THREE.Matrix3();
  12792. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  12793. object.geometry.__webglInit = true;
  12794. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  12795. }
  12796. if ( object instanceof THREE.Mesh ) {
  12797. geometry = object.geometry;
  12798. material = object.material;
  12799. if ( geometry instanceof THREE.Geometry ) {
  12800. if ( geometry.geometryGroups === undefined ) {
  12801. sortFacesByMaterial( geometry, material );
  12802. }
  12803. // create separate VBOs per geometry chunk
  12804. for ( g in geometry.geometryGroups ) {
  12805. geometryGroup = geometry.geometryGroups[ g ];
  12806. // initialise VBO on the first access
  12807. if ( ! geometryGroup.__webglVertexBuffer ) {
  12808. createMeshBuffers( geometryGroup );
  12809. initMeshBuffers( geometryGroup, object );
  12810. geometry.verticesNeedUpdate = true;
  12811. geometry.morphTargetsNeedUpdate = true;
  12812. geometry.elementsNeedUpdate = true;
  12813. geometry.uvsNeedUpdate = true;
  12814. geometry.normalsNeedUpdate = true;
  12815. geometry.tangentsNeedUpdate = true;
  12816. geometry.colorsNeedUpdate = true;
  12817. }
  12818. }
  12819. } else if ( geometry instanceof THREE.BufferGeometry ) {
  12820. initDirectBuffers( geometry );
  12821. }
  12822. } else if ( object instanceof THREE.Ribbon ) {
  12823. geometry = object.geometry;
  12824. if ( ! geometry.__webglVertexBuffer ) {
  12825. createRibbonBuffers( geometry );
  12826. initRibbonBuffers( geometry, object );
  12827. geometry.verticesNeedUpdate = true;
  12828. geometry.colorsNeedUpdate = true;
  12829. geometry.normalsNeedUpdate = true;
  12830. }
  12831. } else if ( object instanceof THREE.Line ) {
  12832. geometry = object.geometry;
  12833. if ( ! geometry.__webglVertexBuffer ) {
  12834. if ( geometry instanceof THREE.Geometry ) {
  12835. createLineBuffers( geometry );
  12836. initLineBuffers( geometry, object );
  12837. geometry.verticesNeedUpdate = true;
  12838. geometry.colorsNeedUpdate = true;
  12839. geometry.lineDistancesNeedUpdate = true;
  12840. } else if ( geometry instanceof THREE.BufferGeometry ) {
  12841. initDirectBuffers( geometry );
  12842. }
  12843. }
  12844. } else if ( object instanceof THREE.ParticleSystem ) {
  12845. geometry = object.geometry;
  12846. if ( ! geometry.__webglVertexBuffer ) {
  12847. if ( geometry instanceof THREE.Geometry ) {
  12848. createParticleBuffers( geometry );
  12849. initParticleBuffers( geometry, object );
  12850. geometry.verticesNeedUpdate = true;
  12851. geometry.colorsNeedUpdate = true;
  12852. } else if ( geometry instanceof THREE.BufferGeometry ) {
  12853. initDirectBuffers( geometry );
  12854. }
  12855. }
  12856. }
  12857. }
  12858. if ( ! object.__webglActive ) {
  12859. if ( object instanceof THREE.Mesh ) {
  12860. geometry = object.geometry;
  12861. if ( geometry instanceof THREE.BufferGeometry ) {
  12862. addBuffer( scene.__webglObjects, geometry, object );
  12863. } else if ( geometry instanceof THREE.Geometry ) {
  12864. for ( g in geometry.geometryGroups ) {
  12865. geometryGroup = geometry.geometryGroups[ g ];
  12866. addBuffer( scene.__webglObjects, geometryGroup, object );
  12867. }
  12868. }
  12869. } else if ( object instanceof THREE.Ribbon ||
  12870. object instanceof THREE.Line ||
  12871. object instanceof THREE.ParticleSystem ) {
  12872. geometry = object.geometry;
  12873. addBuffer( scene.__webglObjects, geometry, object );
  12874. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  12875. addBufferImmediate( scene.__webglObjectsImmediate, object );
  12876. } else if ( object instanceof THREE.Sprite ) {
  12877. scene.__webglSprites.push( object );
  12878. } else if ( object instanceof THREE.LensFlare ) {
  12879. scene.__webglFlares.push( object );
  12880. }
  12881. object.__webglActive = true;
  12882. }
  12883. };
  12884. function addBuffer ( objlist, buffer, object ) {
  12885. objlist.push(
  12886. {
  12887. buffer: buffer,
  12888. object: object,
  12889. opaque: null,
  12890. transparent: null
  12891. }
  12892. );
  12893. };
  12894. function addBufferImmediate ( objlist, object ) {
  12895. objlist.push(
  12896. {
  12897. object: object,
  12898. opaque: null,
  12899. transparent: null
  12900. }
  12901. );
  12902. };
  12903. // Objects updates
  12904. function updateObject ( object ) {
  12905. var geometry = object.geometry,
  12906. geometryGroup, customAttributesDirty, material;
  12907. if ( object instanceof THREE.Mesh ) {
  12908. if ( geometry instanceof THREE.BufferGeometry ) {
  12909. if ( geometry.verticesNeedUpdate || geometry.elementsNeedUpdate ||
  12910. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  12911. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate ) {
  12912. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  12913. }
  12914. geometry.verticesNeedUpdate = false;
  12915. geometry.elementsNeedUpdate = false;
  12916. geometry.uvsNeedUpdate = false;
  12917. geometry.normalsNeedUpdate = false;
  12918. geometry.colorsNeedUpdate = false;
  12919. geometry.tangentsNeedUpdate = false;
  12920. } else {
  12921. // check all geometry groups
  12922. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  12923. geometryGroup = geometry.geometryGroupsList[ i ];
  12924. material = getBufferMaterial( object, geometryGroup );
  12925. if ( geometry.buffersNeedUpdate ) {
  12926. initMeshBuffers( geometryGroup, object );
  12927. }
  12928. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12929. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  12930. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  12931. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  12932. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  12933. }
  12934. }
  12935. geometry.verticesNeedUpdate = false;
  12936. geometry.morphTargetsNeedUpdate = false;
  12937. geometry.elementsNeedUpdate = false;
  12938. geometry.uvsNeedUpdate = false;
  12939. geometry.normalsNeedUpdate = false;
  12940. geometry.colorsNeedUpdate = false;
  12941. geometry.tangentsNeedUpdate = false;
  12942. geometry.buffersNeedUpdate = false;
  12943. material.attributes && clearCustomAttributes( material );
  12944. }
  12945. } else if ( object instanceof THREE.Ribbon ) {
  12946. material = getBufferMaterial( object, geometry );
  12947. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12948. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.normalsNeedUpdate || customAttributesDirty ) {
  12949. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  12950. }
  12951. geometry.verticesNeedUpdate = false;
  12952. geometry.colorsNeedUpdate = false;
  12953. geometry.normalsNeedUpdate = false;
  12954. material.attributes && clearCustomAttributes( material );
  12955. } else if ( object instanceof THREE.Line ) {
  12956. if ( geometry instanceof THREE.BufferGeometry ) {
  12957. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  12958. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  12959. }
  12960. geometry.verticesNeedUpdate = false;
  12961. geometry.colorsNeedUpdate = false;
  12962. } else {
  12963. material = getBufferMaterial( object, geometry );
  12964. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12965. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  12966. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  12967. }
  12968. geometry.verticesNeedUpdate = false;
  12969. geometry.colorsNeedUpdate = false;
  12970. geometry.lineDistancesNeedUpdate = false;
  12971. material.attributes && clearCustomAttributes( material );
  12972. }
  12973. } else if ( object instanceof THREE.ParticleSystem ) {
  12974. if ( geometry instanceof THREE.BufferGeometry ) {
  12975. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  12976. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  12977. }
  12978. geometry.verticesNeedUpdate = false;
  12979. geometry.colorsNeedUpdate = false;
  12980. } else {
  12981. material = getBufferMaterial( object, geometry );
  12982. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12983. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  12984. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  12985. }
  12986. geometry.verticesNeedUpdate = false;
  12987. geometry.colorsNeedUpdate = false;
  12988. material.attributes && clearCustomAttributes( material );
  12989. }
  12990. }
  12991. };
  12992. // Objects updates - custom attributes check
  12993. function areCustomAttributesDirty ( material ) {
  12994. for ( var a in material.attributes ) {
  12995. if ( material.attributes[ a ].needsUpdate ) return true;
  12996. }
  12997. return false;
  12998. };
  12999. function clearCustomAttributes ( material ) {
  13000. for ( var a in material.attributes ) {
  13001. material.attributes[ a ].needsUpdate = false;
  13002. }
  13003. };
  13004. // Objects removal
  13005. function removeObject ( object, scene ) {
  13006. if ( object instanceof THREE.Mesh ||
  13007. object instanceof THREE.ParticleSystem ||
  13008. object instanceof THREE.Ribbon ||
  13009. object instanceof THREE.Line ) {
  13010. removeInstances( scene.__webglObjects, object );
  13011. } else if ( object instanceof THREE.Sprite ) {
  13012. removeInstancesDirect( scene.__webglSprites, object );
  13013. } else if ( object instanceof THREE.LensFlare ) {
  13014. removeInstancesDirect( scene.__webglFlares, object );
  13015. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13016. removeInstances( scene.__webglObjectsImmediate, object );
  13017. }
  13018. object.__webglActive = false;
  13019. };
  13020. function removeInstances ( objlist, object ) {
  13021. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13022. if ( objlist[ o ].object === object ) {
  13023. objlist.splice( o, 1 );
  13024. }
  13025. }
  13026. };
  13027. function removeInstancesDirect ( objlist, object ) {
  13028. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13029. if ( objlist[ o ] === object ) {
  13030. objlist.splice( o, 1 );
  13031. }
  13032. }
  13033. };
  13034. // Materials
  13035. this.initMaterial = function ( material, lights, fog, object ) {
  13036. material.addEventListener( 'dispose', onMaterialDispose );
  13037. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  13038. if ( material instanceof THREE.MeshDepthMaterial ) {
  13039. shaderID = 'depth';
  13040. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13041. shaderID = 'normal';
  13042. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  13043. shaderID = 'basic';
  13044. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13045. shaderID = 'lambert';
  13046. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13047. shaderID = 'phong';
  13048. } else if ( material instanceof THREE.LineBasicMaterial ) {
  13049. shaderID = 'basic';
  13050. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13051. shaderID = 'dashed';
  13052. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  13053. shaderID = 'particle_basic';
  13054. }
  13055. if ( shaderID ) {
  13056. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  13057. }
  13058. // heuristics to create shader parameters according to lights in the scene
  13059. // (not to blow over maxLights budget)
  13060. maxLightCount = allocateLights( lights );
  13061. maxShadows = allocateShadows( lights );
  13062. maxBones = allocateBones( object );
  13063. parameters = {
  13064. map: !!material.map,
  13065. envMap: !!material.envMap,
  13066. lightMap: !!material.lightMap,
  13067. bumpMap: !!material.bumpMap,
  13068. normalMap: !!material.normalMap,
  13069. specularMap: !!material.specularMap,
  13070. vertexColors: material.vertexColors,
  13071. fog: fog,
  13072. useFog: material.fog,
  13073. fogExp: fog instanceof THREE.FogExp2,
  13074. sizeAttenuation: material.sizeAttenuation,
  13075. skinning: material.skinning,
  13076. maxBones: maxBones,
  13077. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  13078. boneTextureWidth: object && object.boneTextureWidth,
  13079. boneTextureHeight: object && object.boneTextureHeight,
  13080. morphTargets: material.morphTargets,
  13081. morphNormals: material.morphNormals,
  13082. maxMorphTargets: this.maxMorphTargets,
  13083. maxMorphNormals: this.maxMorphNormals,
  13084. maxDirLights: maxLightCount.directional,
  13085. maxPointLights: maxLightCount.point,
  13086. maxSpotLights: maxLightCount.spot,
  13087. maxHemiLights: maxLightCount.hemi,
  13088. maxShadows: maxShadows,
  13089. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  13090. shadowMapType: this.shadowMapType,
  13091. shadowMapDebug: this.shadowMapDebug,
  13092. shadowMapCascade: this.shadowMapCascade,
  13093. alphaTest: material.alphaTest,
  13094. metal: material.metal,
  13095. perPixel: material.perPixel,
  13096. wrapAround: material.wrapAround,
  13097. doubleSided: material.side === THREE.DoubleSide,
  13098. flipSided: material.side === THREE.BackSide
  13099. };
  13100. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters );
  13101. var attributes = material.program.attributes;
  13102. if ( material.morphTargets ) {
  13103. material.numSupportedMorphTargets = 0;
  13104. var id, base = "morphTarget";
  13105. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  13106. id = base + i;
  13107. if ( attributes[ id ] >= 0 ) {
  13108. material.numSupportedMorphTargets ++;
  13109. }
  13110. }
  13111. }
  13112. if ( material.morphNormals ) {
  13113. material.numSupportedMorphNormals = 0;
  13114. var id, base = "morphNormal";
  13115. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  13116. id = base + i;
  13117. if ( attributes[ id ] >= 0 ) {
  13118. material.numSupportedMorphNormals ++;
  13119. }
  13120. }
  13121. }
  13122. material.uniformsList = [];
  13123. for ( u in material.uniforms ) {
  13124. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  13125. }
  13126. };
  13127. function setMaterialShaders( material, shaders ) {
  13128. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  13129. material.vertexShader = shaders.vertexShader;
  13130. material.fragmentShader = shaders.fragmentShader;
  13131. };
  13132. function setProgram( camera, lights, fog, material, object ) {
  13133. _usedTextureUnits = 0;
  13134. if ( material.needsUpdate ) {
  13135. if ( material.program ) deallocateMaterial( material );
  13136. _this.initMaterial( material, lights, fog, object );
  13137. material.needsUpdate = false;
  13138. }
  13139. if ( material.morphTargets ) {
  13140. if ( ! object.__webglMorphTargetInfluences ) {
  13141. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  13142. }
  13143. }
  13144. var refreshMaterial = false;
  13145. var program = material.program,
  13146. p_uniforms = program.uniforms,
  13147. m_uniforms = material.uniforms;
  13148. if ( program !== _currentProgram ) {
  13149. _gl.useProgram( program );
  13150. _currentProgram = program;
  13151. refreshMaterial = true;
  13152. }
  13153. if ( material.id !== _currentMaterialId ) {
  13154. _currentMaterialId = material.id;
  13155. refreshMaterial = true;
  13156. }
  13157. if ( refreshMaterial || camera !== _currentCamera ) {
  13158. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  13159. if ( camera !== _currentCamera ) _currentCamera = camera;
  13160. }
  13161. // skinning uniforms must be set even if material didn't change
  13162. // auto-setting of texture unit for bone texture must go before other textures
  13163. // not sure why, but otherwise weird things happen
  13164. if ( material.skinning ) {
  13165. if ( _supportsBoneTextures && object.useVertexTexture ) {
  13166. if ( p_uniforms.boneTexture !== null ) {
  13167. var textureUnit = getTextureUnit();
  13168. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  13169. _this.setTexture( object.boneTexture, textureUnit );
  13170. }
  13171. } else {
  13172. if ( p_uniforms.boneGlobalMatrices !== null ) {
  13173. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  13174. }
  13175. }
  13176. }
  13177. if ( refreshMaterial ) {
  13178. // refresh uniforms common to several materials
  13179. if ( fog && material.fog ) {
  13180. refreshUniformsFog( m_uniforms, fog );
  13181. }
  13182. if ( material instanceof THREE.MeshPhongMaterial ||
  13183. material instanceof THREE.MeshLambertMaterial ||
  13184. material.lights ) {
  13185. if ( _lightsNeedUpdate ) {
  13186. setupLights( program, lights );
  13187. _lightsNeedUpdate = false;
  13188. }
  13189. refreshUniformsLights( m_uniforms, _lights );
  13190. }
  13191. if ( material instanceof THREE.MeshBasicMaterial ||
  13192. material instanceof THREE.MeshLambertMaterial ||
  13193. material instanceof THREE.MeshPhongMaterial ) {
  13194. refreshUniformsCommon( m_uniforms, material );
  13195. }
  13196. // refresh single material specific uniforms
  13197. if ( material instanceof THREE.LineBasicMaterial ) {
  13198. refreshUniformsLine( m_uniforms, material );
  13199. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13200. refreshUniformsLine( m_uniforms, material );
  13201. refreshUniformsDash( m_uniforms, material );
  13202. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  13203. refreshUniformsParticle( m_uniforms, material );
  13204. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13205. refreshUniformsPhong( m_uniforms, material );
  13206. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13207. refreshUniformsLambert( m_uniforms, material );
  13208. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  13209. m_uniforms.mNear.value = camera.near;
  13210. m_uniforms.mFar.value = camera.far;
  13211. m_uniforms.opacity.value = material.opacity;
  13212. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13213. m_uniforms.opacity.value = material.opacity;
  13214. }
  13215. if ( object.receiveShadow && ! material._shadowPass ) {
  13216. refreshUniformsShadow( m_uniforms, lights );
  13217. }
  13218. // load common uniforms
  13219. loadUniformsGeneric( program, material.uniformsList );
  13220. // load material specific uniforms
  13221. // (shader material also gets them for the sake of genericity)
  13222. if ( material instanceof THREE.ShaderMaterial ||
  13223. material instanceof THREE.MeshPhongMaterial ||
  13224. material.envMap ) {
  13225. if ( p_uniforms.cameraPosition !== null ) {
  13226. var position = camera.matrixWorld.getPosition();
  13227. _gl.uniform3f( p_uniforms.cameraPosition, position.x, position.y, position.z );
  13228. }
  13229. }
  13230. if ( material instanceof THREE.MeshPhongMaterial ||
  13231. material instanceof THREE.MeshLambertMaterial ||
  13232. material instanceof THREE.ShaderMaterial ||
  13233. material.skinning ) {
  13234. if ( p_uniforms.viewMatrix !== null ) {
  13235. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  13236. }
  13237. }
  13238. }
  13239. loadUniformsMatrices( p_uniforms, object );
  13240. if ( p_uniforms.modelMatrix !== null ) {
  13241. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  13242. }
  13243. return program;
  13244. };
  13245. // Uniforms (refresh uniforms objects)
  13246. function refreshUniformsCommon ( uniforms, material ) {
  13247. uniforms.opacity.value = material.opacity;
  13248. if ( _this.gammaInput ) {
  13249. uniforms.diffuse.value.copyGammaToLinear( material.color );
  13250. } else {
  13251. uniforms.diffuse.value = material.color;
  13252. }
  13253. uniforms.map.value = material.map;
  13254. uniforms.lightMap.value = material.lightMap;
  13255. uniforms.specularMap.value = material.specularMap;
  13256. if ( material.bumpMap ) {
  13257. uniforms.bumpMap.value = material.bumpMap;
  13258. uniforms.bumpScale.value = material.bumpScale;
  13259. }
  13260. if ( material.normalMap ) {
  13261. uniforms.normalMap.value = material.normalMap;
  13262. uniforms.normalScale.value.copy( material.normalScale );
  13263. }
  13264. // uv repeat and offset setting priorities
  13265. // 1. color map
  13266. // 2. specular map
  13267. // 3. normal map
  13268. // 4. bump map
  13269. var uvScaleMap;
  13270. if ( material.map ) {
  13271. uvScaleMap = material.map;
  13272. } else if ( material.specularMap ) {
  13273. uvScaleMap = material.specularMap;
  13274. } else if ( material.normalMap ) {
  13275. uvScaleMap = material.normalMap;
  13276. } else if ( material.bumpMap ) {
  13277. uvScaleMap = material.bumpMap;
  13278. }
  13279. if ( uvScaleMap !== undefined ) {
  13280. var offset = uvScaleMap.offset;
  13281. var repeat = uvScaleMap.repeat;
  13282. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  13283. }
  13284. uniforms.envMap.value = material.envMap;
  13285. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  13286. if ( _this.gammaInput ) {
  13287. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  13288. uniforms.reflectivity.value = material.reflectivity;
  13289. } else {
  13290. uniforms.reflectivity.value = material.reflectivity;
  13291. }
  13292. uniforms.refractionRatio.value = material.refractionRatio;
  13293. uniforms.combine.value = material.combine;
  13294. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  13295. };
  13296. function refreshUniformsLine ( uniforms, material ) {
  13297. uniforms.diffuse.value = material.color;
  13298. uniforms.opacity.value = material.opacity;
  13299. };
  13300. function refreshUniformsDash ( uniforms, material ) {
  13301. uniforms.dashSize.value = material.dashSize;
  13302. uniforms.totalSize.value = material.dashSize + material.gapSize;
  13303. uniforms.scale.value = material.scale;
  13304. };
  13305. function refreshUniformsParticle ( uniforms, material ) {
  13306. uniforms.psColor.value = material.color;
  13307. uniforms.opacity.value = material.opacity;
  13308. uniforms.size.value = material.size;
  13309. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  13310. uniforms.map.value = material.map;
  13311. };
  13312. function refreshUniformsFog ( uniforms, fog ) {
  13313. uniforms.fogColor.value = fog.color;
  13314. if ( fog instanceof THREE.Fog ) {
  13315. uniforms.fogNear.value = fog.near;
  13316. uniforms.fogFar.value = fog.far;
  13317. } else if ( fog instanceof THREE.FogExp2 ) {
  13318. uniforms.fogDensity.value = fog.density;
  13319. }
  13320. };
  13321. function refreshUniformsPhong ( uniforms, material ) {
  13322. uniforms.shininess.value = material.shininess;
  13323. if ( _this.gammaInput ) {
  13324. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  13325. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  13326. uniforms.specular.value.copyGammaToLinear( material.specular );
  13327. } else {
  13328. uniforms.ambient.value = material.ambient;
  13329. uniforms.emissive.value = material.emissive;
  13330. uniforms.specular.value = material.specular;
  13331. }
  13332. if ( material.wrapAround ) {
  13333. uniforms.wrapRGB.value.copy( material.wrapRGB );
  13334. }
  13335. };
  13336. function refreshUniformsLambert ( uniforms, material ) {
  13337. if ( _this.gammaInput ) {
  13338. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  13339. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  13340. } else {
  13341. uniforms.ambient.value = material.ambient;
  13342. uniforms.emissive.value = material.emissive;
  13343. }
  13344. if ( material.wrapAround ) {
  13345. uniforms.wrapRGB.value.copy( material.wrapRGB );
  13346. }
  13347. };
  13348. function refreshUniformsLights ( uniforms, lights ) {
  13349. uniforms.ambientLightColor.value = lights.ambient;
  13350. uniforms.directionalLightColor.value = lights.directional.colors;
  13351. uniforms.directionalLightDirection.value = lights.directional.positions;
  13352. uniforms.pointLightColor.value = lights.point.colors;
  13353. uniforms.pointLightPosition.value = lights.point.positions;
  13354. uniforms.pointLightDistance.value = lights.point.distances;
  13355. uniforms.spotLightColor.value = lights.spot.colors;
  13356. uniforms.spotLightPosition.value = lights.spot.positions;
  13357. uniforms.spotLightDistance.value = lights.spot.distances;
  13358. uniforms.spotLightDirection.value = lights.spot.directions;
  13359. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  13360. uniforms.spotLightExponent.value = lights.spot.exponents;
  13361. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  13362. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  13363. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  13364. };
  13365. function refreshUniformsShadow ( uniforms, lights ) {
  13366. if ( uniforms.shadowMatrix ) {
  13367. var j = 0;
  13368. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  13369. var light = lights[ i ];
  13370. if ( ! light.castShadow ) continue;
  13371. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  13372. uniforms.shadowMap.value[ j ] = light.shadowMap;
  13373. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  13374. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  13375. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  13376. uniforms.shadowBias.value[ j ] = light.shadowBias;
  13377. j ++;
  13378. }
  13379. }
  13380. }
  13381. };
  13382. // Uniforms (load to GPU)
  13383. function loadUniformsMatrices ( uniforms, object ) {
  13384. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  13385. if ( uniforms.normalMatrix ) {
  13386. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  13387. }
  13388. };
  13389. function getTextureUnit() {
  13390. var textureUnit = _usedTextureUnits;
  13391. if ( textureUnit >= _maxTextures ) {
  13392. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  13393. }
  13394. _usedTextureUnits += 1;
  13395. return textureUnit;
  13396. };
  13397. function loadUniformsGeneric ( program, uniforms ) {
  13398. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  13399. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  13400. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  13401. if ( !location ) continue;
  13402. uniform = uniforms[ j ][ 0 ];
  13403. type = uniform.type;
  13404. value = uniform.value;
  13405. if ( type === "i" ) { // single integer
  13406. _gl.uniform1i( location, value );
  13407. } else if ( type === "f" ) { // single float
  13408. _gl.uniform1f( location, value );
  13409. } else if ( type === "v2" ) { // single THREE.Vector2
  13410. _gl.uniform2f( location, value.x, value.y );
  13411. } else if ( type === "v3" ) { // single THREE.Vector3
  13412. _gl.uniform3f( location, value.x, value.y, value.z );
  13413. } else if ( type === "v4" ) { // single THREE.Vector4
  13414. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  13415. } else if ( type === "c" ) { // single THREE.Color
  13416. _gl.uniform3f( location, value.r, value.g, value.b );
  13417. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  13418. _gl.uniform1iv( location, value );
  13419. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  13420. _gl.uniform3iv( location, value );
  13421. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  13422. _gl.uniform1fv( location, value );
  13423. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  13424. _gl.uniform3fv( location, value );
  13425. } else if ( type === "v2v" ) { // array of THREE.Vector2
  13426. if ( uniform._array === undefined ) {
  13427. uniform._array = new Float32Array( 2 * value.length );
  13428. }
  13429. for ( i = 0, il = value.length; i < il; i ++ ) {
  13430. offset = i * 2;
  13431. uniform._array[ offset ] = value[ i ].x;
  13432. uniform._array[ offset + 1 ] = value[ i ].y;
  13433. }
  13434. _gl.uniform2fv( location, uniform._array );
  13435. } else if ( type === "v3v" ) { // array of THREE.Vector3
  13436. if ( uniform._array === undefined ) {
  13437. uniform._array = new Float32Array( 3 * value.length );
  13438. }
  13439. for ( i = 0, il = value.length; i < il; i ++ ) {
  13440. offset = i * 3;
  13441. uniform._array[ offset ] = value[ i ].x;
  13442. uniform._array[ offset + 1 ] = value[ i ].y;
  13443. uniform._array[ offset + 2 ] = value[ i ].z;
  13444. }
  13445. _gl.uniform3fv( location, uniform._array );
  13446. } else if ( type === "v4v" ) { // array of THREE.Vector4
  13447. if ( uniform._array === undefined ) {
  13448. uniform._array = new Float32Array( 4 * value.length );
  13449. }
  13450. for ( i = 0, il = value.length; i < il; i ++ ) {
  13451. offset = i * 4;
  13452. uniform._array[ offset ] = value[ i ].x;
  13453. uniform._array[ offset + 1 ] = value[ i ].y;
  13454. uniform._array[ offset + 2 ] = value[ i ].z;
  13455. uniform._array[ offset + 3 ] = value[ i ].w;
  13456. }
  13457. _gl.uniform4fv( location, uniform._array );
  13458. } else if ( type === "m4") { // single THREE.Matrix4
  13459. if ( uniform._array === undefined ) {
  13460. uniform._array = new Float32Array( 16 );
  13461. }
  13462. value.flattenToArray( uniform._array );
  13463. _gl.uniformMatrix4fv( location, false, uniform._array );
  13464. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  13465. if ( uniform._array === undefined ) {
  13466. uniform._array = new Float32Array( 16 * value.length );
  13467. }
  13468. for ( i = 0, il = value.length; i < il; i ++ ) {
  13469. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  13470. }
  13471. _gl.uniformMatrix4fv( location, false, uniform._array );
  13472. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  13473. texture = value;
  13474. textureUnit = getTextureUnit();
  13475. _gl.uniform1i( location, textureUnit );
  13476. if ( !texture ) continue;
  13477. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  13478. setCubeTexture( texture, textureUnit );
  13479. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  13480. setCubeTextureDynamic( texture, textureUnit );
  13481. } else {
  13482. _this.setTexture( texture, textureUnit );
  13483. }
  13484. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  13485. if ( uniform._array === undefined ) {
  13486. uniform._array = [];
  13487. }
  13488. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  13489. uniform._array[ i ] = getTextureUnit();
  13490. }
  13491. _gl.uniform1iv( location, uniform._array );
  13492. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  13493. texture = uniform.value[ i ];
  13494. textureUnit = uniform._array[ i ];
  13495. if ( !texture ) continue;
  13496. _this.setTexture( texture, textureUnit );
  13497. }
  13498. }
  13499. }
  13500. };
  13501. function setupMatrices ( object, camera ) {
  13502. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  13503. object._normalMatrix.getInverse( object._modelViewMatrix );
  13504. object._normalMatrix.transpose();
  13505. };
  13506. //
  13507. function setColorGamma( array, offset, color, intensitySq ) {
  13508. array[ offset ] = color.r * color.r * intensitySq;
  13509. array[ offset + 1 ] = color.g * color.g * intensitySq;
  13510. array[ offset + 2 ] = color.b * color.b * intensitySq;
  13511. };
  13512. function setColorLinear( array, offset, color, intensity ) {
  13513. array[ offset ] = color.r * intensity;
  13514. array[ offset + 1 ] = color.g * intensity;
  13515. array[ offset + 2 ] = color.b * intensity;
  13516. };
  13517. function setupLights ( program, lights ) {
  13518. var l, ll, light, n,
  13519. r = 0, g = 0, b = 0,
  13520. color, skyColor, groundColor,
  13521. intensity, intensitySq,
  13522. position,
  13523. distance,
  13524. zlights = _lights,
  13525. dirColors = zlights.directional.colors,
  13526. dirPositions = zlights.directional.positions,
  13527. pointColors = zlights.point.colors,
  13528. pointPositions = zlights.point.positions,
  13529. pointDistances = zlights.point.distances,
  13530. spotColors = zlights.spot.colors,
  13531. spotPositions = zlights.spot.positions,
  13532. spotDistances = zlights.spot.distances,
  13533. spotDirections = zlights.spot.directions,
  13534. spotAnglesCos = zlights.spot.anglesCos,
  13535. spotExponents = zlights.spot.exponents,
  13536. hemiSkyColors = zlights.hemi.skyColors,
  13537. hemiGroundColors = zlights.hemi.groundColors,
  13538. hemiPositions = zlights.hemi.positions,
  13539. dirLength = 0,
  13540. pointLength = 0,
  13541. spotLength = 0,
  13542. hemiLength = 0,
  13543. dirCount = 0,
  13544. pointCount = 0,
  13545. spotCount = 0,
  13546. hemiCount = 0,
  13547. dirOffset = 0,
  13548. pointOffset = 0,
  13549. spotOffset = 0,
  13550. hemiOffset = 0;
  13551. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  13552. light = lights[ l ];
  13553. if ( light.onlyShadow ) continue;
  13554. color = light.color;
  13555. intensity = light.intensity;
  13556. distance = light.distance;
  13557. if ( light instanceof THREE.AmbientLight ) {
  13558. if ( ! light.visible ) continue;
  13559. if ( _this.gammaInput ) {
  13560. r += color.r * color.r;
  13561. g += color.g * color.g;
  13562. b += color.b * color.b;
  13563. } else {
  13564. r += color.r;
  13565. g += color.g;
  13566. b += color.b;
  13567. }
  13568. } else if ( light instanceof THREE.DirectionalLight ) {
  13569. dirCount += 1;
  13570. if ( ! light.visible ) continue;
  13571. _direction.copy( light.matrixWorld.getPosition() );
  13572. _direction.sub( light.target.matrixWorld.getPosition() );
  13573. _direction.normalize();
  13574. // skip lights with undefined direction
  13575. // these create troubles in OpenGL (making pixel black)
  13576. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  13577. dirOffset = dirLength * 3;
  13578. dirPositions[ dirOffset ] = _direction.x;
  13579. dirPositions[ dirOffset + 1 ] = _direction.y;
  13580. dirPositions[ dirOffset + 2 ] = _direction.z;
  13581. if ( _this.gammaInput ) {
  13582. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  13583. } else {
  13584. setColorLinear( dirColors, dirOffset, color, intensity );
  13585. }
  13586. dirLength += 1;
  13587. } else if ( light instanceof THREE.PointLight ) {
  13588. pointCount += 1;
  13589. if ( ! light.visible ) continue;
  13590. pointOffset = pointLength * 3;
  13591. if ( _this.gammaInput ) {
  13592. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  13593. } else {
  13594. setColorLinear( pointColors, pointOffset, color, intensity );
  13595. }
  13596. position = light.matrixWorld.getPosition();
  13597. pointPositions[ pointOffset ] = position.x;
  13598. pointPositions[ pointOffset + 1 ] = position.y;
  13599. pointPositions[ pointOffset + 2 ] = position.z;
  13600. pointDistances[ pointLength ] = distance;
  13601. pointLength += 1;
  13602. } else if ( light instanceof THREE.SpotLight ) {
  13603. spotCount += 1;
  13604. if ( ! light.visible ) continue;
  13605. spotOffset = spotLength * 3;
  13606. if ( _this.gammaInput ) {
  13607. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  13608. } else {
  13609. setColorLinear( spotColors, spotOffset, color, intensity );
  13610. }
  13611. position = light.matrixWorld.getPosition();
  13612. spotPositions[ spotOffset ] = position.x;
  13613. spotPositions[ spotOffset + 1 ] = position.y;
  13614. spotPositions[ spotOffset + 2 ] = position.z;
  13615. spotDistances[ spotLength ] = distance;
  13616. _direction.copy( position );
  13617. _direction.sub( light.target.matrixWorld.getPosition() );
  13618. _direction.normalize();
  13619. spotDirections[ spotOffset ] = _direction.x;
  13620. spotDirections[ spotOffset + 1 ] = _direction.y;
  13621. spotDirections[ spotOffset + 2 ] = _direction.z;
  13622. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  13623. spotExponents[ spotLength ] = light.exponent;
  13624. spotLength += 1;
  13625. } else if ( light instanceof THREE.HemisphereLight ) {
  13626. hemiCount += 1;
  13627. if ( ! light.visible ) continue;
  13628. _direction.copy( light.matrixWorld.getPosition() );
  13629. _direction.normalize();
  13630. // skip lights with undefined direction
  13631. // these create troubles in OpenGL (making pixel black)
  13632. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  13633. hemiOffset = hemiLength * 3;
  13634. hemiPositions[ hemiOffset ] = _direction.x;
  13635. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  13636. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  13637. skyColor = light.color;
  13638. groundColor = light.groundColor;
  13639. if ( _this.gammaInput ) {
  13640. intensitySq = intensity * intensity;
  13641. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  13642. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  13643. } else {
  13644. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  13645. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  13646. }
  13647. hemiLength += 1;
  13648. }
  13649. }
  13650. // null eventual remains from removed lights
  13651. // (this is to avoid if in shader)
  13652. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  13653. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  13654. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  13655. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  13656. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  13657. zlights.directional.length = dirLength;
  13658. zlights.point.length = pointLength;
  13659. zlights.spot.length = spotLength;
  13660. zlights.hemi.length = hemiLength;
  13661. zlights.ambient[ 0 ] = r;
  13662. zlights.ambient[ 1 ] = g;
  13663. zlights.ambient[ 2 ] = b;
  13664. };
  13665. // GL state setting
  13666. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  13667. if ( cullFace === THREE.CullFaceNone ) {
  13668. _gl.disable( _gl.CULL_FACE );
  13669. } else {
  13670. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  13671. _gl.frontFace( _gl.CW );
  13672. } else {
  13673. _gl.frontFace( _gl.CCW );
  13674. }
  13675. if ( cullFace === THREE.CullFaceBack ) {
  13676. _gl.cullFace( _gl.BACK );
  13677. } else if ( cullFace === THREE.CullFaceFront ) {
  13678. _gl.cullFace( _gl.FRONT );
  13679. } else {
  13680. _gl.cullFace( _gl.FRONT_AND_BACK );
  13681. }
  13682. _gl.enable( _gl.CULL_FACE );
  13683. }
  13684. };
  13685. this.setMaterialFaces = function ( material ) {
  13686. var doubleSided = material.side === THREE.DoubleSide;
  13687. var flipSided = material.side === THREE.BackSide;
  13688. if ( _oldDoubleSided !== doubleSided ) {
  13689. if ( doubleSided ) {
  13690. _gl.disable( _gl.CULL_FACE );
  13691. } else {
  13692. _gl.enable( _gl.CULL_FACE );
  13693. }
  13694. _oldDoubleSided = doubleSided;
  13695. }
  13696. if ( _oldFlipSided !== flipSided ) {
  13697. if ( flipSided ) {
  13698. _gl.frontFace( _gl.CW );
  13699. } else {
  13700. _gl.frontFace( _gl.CCW );
  13701. }
  13702. _oldFlipSided = flipSided;
  13703. }
  13704. };
  13705. this.setDepthTest = function ( depthTest ) {
  13706. if ( _oldDepthTest !== depthTest ) {
  13707. if ( depthTest ) {
  13708. _gl.enable( _gl.DEPTH_TEST );
  13709. } else {
  13710. _gl.disable( _gl.DEPTH_TEST );
  13711. }
  13712. _oldDepthTest = depthTest;
  13713. }
  13714. };
  13715. this.setDepthWrite = function ( depthWrite ) {
  13716. if ( _oldDepthWrite !== depthWrite ) {
  13717. _gl.depthMask( depthWrite );
  13718. _oldDepthWrite = depthWrite;
  13719. }
  13720. };
  13721. function setLineWidth ( width ) {
  13722. if ( width !== _oldLineWidth ) {
  13723. _gl.lineWidth( width );
  13724. _oldLineWidth = width;
  13725. }
  13726. };
  13727. function setPolygonOffset ( polygonoffset, factor, units ) {
  13728. if ( _oldPolygonOffset !== polygonoffset ) {
  13729. if ( polygonoffset ) {
  13730. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  13731. } else {
  13732. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  13733. }
  13734. _oldPolygonOffset = polygonoffset;
  13735. }
  13736. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  13737. _gl.polygonOffset( factor, units );
  13738. _oldPolygonOffsetFactor = factor;
  13739. _oldPolygonOffsetUnits = units;
  13740. }
  13741. };
  13742. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  13743. if ( blending !== _oldBlending ) {
  13744. if ( blending === THREE.NoBlending ) {
  13745. _gl.disable( _gl.BLEND );
  13746. } else if ( blending === THREE.AdditiveBlending ) {
  13747. _gl.enable( _gl.BLEND );
  13748. _gl.blendEquation( _gl.FUNC_ADD );
  13749. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  13750. } else if ( blending === THREE.SubtractiveBlending ) {
  13751. // TODO: Find blendFuncSeparate() combination
  13752. _gl.enable( _gl.BLEND );
  13753. _gl.blendEquation( _gl.FUNC_ADD );
  13754. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  13755. } else if ( blending === THREE.MultiplyBlending ) {
  13756. // TODO: Find blendFuncSeparate() combination
  13757. _gl.enable( _gl.BLEND );
  13758. _gl.blendEquation( _gl.FUNC_ADD );
  13759. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  13760. } else if ( blending === THREE.CustomBlending ) {
  13761. _gl.enable( _gl.BLEND );
  13762. } else {
  13763. _gl.enable( _gl.BLEND );
  13764. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  13765. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  13766. }
  13767. _oldBlending = blending;
  13768. }
  13769. if ( blending === THREE.CustomBlending ) {
  13770. if ( blendEquation !== _oldBlendEquation ) {
  13771. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  13772. _oldBlendEquation = blendEquation;
  13773. }
  13774. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  13775. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  13776. _oldBlendSrc = blendSrc;
  13777. _oldBlendDst = blendDst;
  13778. }
  13779. } else {
  13780. _oldBlendEquation = null;
  13781. _oldBlendSrc = null;
  13782. _oldBlendDst = null;
  13783. }
  13784. };
  13785. // Defines
  13786. function generateDefines ( defines ) {
  13787. var value, chunk, chunks = [];
  13788. for ( var d in defines ) {
  13789. value = defines[ d ];
  13790. if ( value === false ) continue;
  13791. chunk = "#define " + d + " " + value;
  13792. chunks.push( chunk );
  13793. }
  13794. return chunks.join( "\n" );
  13795. };
  13796. // Shaders
  13797. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters ) {
  13798. var p, pl, d, program, code;
  13799. var chunks = [];
  13800. // Generate code
  13801. if ( shaderID ) {
  13802. chunks.push( shaderID );
  13803. } else {
  13804. chunks.push( fragmentShader );
  13805. chunks.push( vertexShader );
  13806. }
  13807. for ( d in defines ) {
  13808. chunks.push( d );
  13809. chunks.push( defines[ d ] );
  13810. }
  13811. for ( p in parameters ) {
  13812. chunks.push( p );
  13813. chunks.push( parameters[ p ] );
  13814. }
  13815. code = chunks.join();
  13816. // Check if code has been already compiled
  13817. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  13818. var programInfo = _programs[ p ];
  13819. if ( programInfo.code === code ) {
  13820. //console.log( "Code already compiled." /*: \n\n" + code*/ );
  13821. programInfo.usedTimes ++;
  13822. return programInfo.program;
  13823. }
  13824. }
  13825. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  13826. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  13827. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  13828. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  13829. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  13830. }
  13831. //console.log( "building new program " );
  13832. //
  13833. var customDefines = generateDefines( defines );
  13834. //
  13835. program = _gl.createProgram();
  13836. var prefix_vertex = [
  13837. "precision " + _precision + " float;",
  13838. customDefines,
  13839. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  13840. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  13841. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  13842. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  13843. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  13844. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  13845. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  13846. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  13847. "#define MAX_SHADOWS " + parameters.maxShadows,
  13848. "#define MAX_BONES " + parameters.maxBones,
  13849. parameters.map ? "#define USE_MAP" : "",
  13850. parameters.envMap ? "#define USE_ENVMAP" : "",
  13851. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  13852. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  13853. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  13854. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  13855. parameters.vertexColors ? "#define USE_COLOR" : "",
  13856. parameters.skinning ? "#define USE_SKINNING" : "",
  13857. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  13858. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  13859. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  13860. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  13861. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  13862. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  13863. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  13864. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  13865. parameters.flipSided ? "#define FLIP_SIDED" : "",
  13866. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  13867. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  13868. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  13869. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  13870. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  13871. "uniform mat4 modelMatrix;",
  13872. "uniform mat4 modelViewMatrix;",
  13873. "uniform mat4 projectionMatrix;",
  13874. "uniform mat4 viewMatrix;",
  13875. "uniform mat3 normalMatrix;",
  13876. "uniform vec3 cameraPosition;",
  13877. "attribute vec3 position;",
  13878. "attribute vec3 normal;",
  13879. "attribute vec2 uv;",
  13880. "attribute vec2 uv2;",
  13881. "#ifdef USE_COLOR",
  13882. "attribute vec3 color;",
  13883. "#endif",
  13884. "#ifdef USE_MORPHTARGETS",
  13885. "attribute vec3 morphTarget0;",
  13886. "attribute vec3 morphTarget1;",
  13887. "attribute vec3 morphTarget2;",
  13888. "attribute vec3 morphTarget3;",
  13889. "#ifdef USE_MORPHNORMALS",
  13890. "attribute vec3 morphNormal0;",
  13891. "attribute vec3 morphNormal1;",
  13892. "attribute vec3 morphNormal2;",
  13893. "attribute vec3 morphNormal3;",
  13894. "#else",
  13895. "attribute vec3 morphTarget4;",
  13896. "attribute vec3 morphTarget5;",
  13897. "attribute vec3 morphTarget6;",
  13898. "attribute vec3 morphTarget7;",
  13899. "#endif",
  13900. "#endif",
  13901. "#ifdef USE_SKINNING",
  13902. "attribute vec4 skinIndex;",
  13903. "attribute vec4 skinWeight;",
  13904. "#endif",
  13905. ""
  13906. ].join("\n");
  13907. var prefix_fragment = [
  13908. "precision " + _precision + " float;",
  13909. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  13910. customDefines,
  13911. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  13912. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  13913. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  13914. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  13915. "#define MAX_SHADOWS " + parameters.maxShadows,
  13916. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  13917. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  13918. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  13919. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  13920. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  13921. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  13922. parameters.map ? "#define USE_MAP" : "",
  13923. parameters.envMap ? "#define USE_ENVMAP" : "",
  13924. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  13925. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  13926. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  13927. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  13928. parameters.vertexColors ? "#define USE_COLOR" : "",
  13929. parameters.metal ? "#define METAL" : "",
  13930. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  13931. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  13932. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  13933. parameters.flipSided ? "#define FLIP_SIDED" : "",
  13934. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  13935. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  13936. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  13937. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  13938. "uniform mat4 viewMatrix;",
  13939. "uniform vec3 cameraPosition;",
  13940. ""
  13941. ].join("\n");
  13942. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  13943. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  13944. _gl.attachShader( program, glVertexShader );
  13945. _gl.attachShader( program, glFragmentShader );
  13946. _gl.linkProgram( program );
  13947. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  13948. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  13949. }
  13950. // clean up
  13951. _gl.deleteShader( glFragmentShader );
  13952. _gl.deleteShader( glVertexShader );
  13953. //console.log( prefix_fragment + fragmentShader );
  13954. //console.log( prefix_vertex + vertexShader );
  13955. program.uniforms = {};
  13956. program.attributes = {};
  13957. var identifiers, u, a, i;
  13958. // cache uniform locations
  13959. identifiers = [
  13960. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  13961. 'morphTargetInfluences'
  13962. ];
  13963. if ( parameters.useVertexTexture ) {
  13964. identifiers.push( 'boneTexture' );
  13965. } else {
  13966. identifiers.push( 'boneGlobalMatrices' );
  13967. }
  13968. for ( u in uniforms ) {
  13969. identifiers.push( u );
  13970. }
  13971. cacheUniformLocations( program, identifiers );
  13972. // cache attributes locations
  13973. identifiers = [
  13974. "position", "normal", "uv", "uv2", "tangent", "color",
  13975. "skinIndex", "skinWeight", "lineDistance"
  13976. ];
  13977. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  13978. identifiers.push( "morphTarget" + i );
  13979. }
  13980. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  13981. identifiers.push( "morphNormal" + i );
  13982. }
  13983. for ( a in attributes ) {
  13984. identifiers.push( a );
  13985. }
  13986. cacheAttributeLocations( program, identifiers );
  13987. program.id = _programs_counter ++;
  13988. _programs.push( { program: program, code: code, usedTimes: 1 } );
  13989. _this.info.memory.programs = _programs.length;
  13990. return program;
  13991. };
  13992. // Shader parameters cache
  13993. function cacheUniformLocations ( program, identifiers ) {
  13994. var i, l, id;
  13995. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  13996. id = identifiers[ i ];
  13997. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  13998. }
  13999. };
  14000. function cacheAttributeLocations ( program, identifiers ) {
  14001. var i, l, id;
  14002. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14003. id = identifiers[ i ];
  14004. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  14005. }
  14006. };
  14007. function addLineNumbers ( string ) {
  14008. var chunks = string.split( "\n" );
  14009. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  14010. // Chrome reports shader errors on lines
  14011. // starting counting from 1
  14012. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  14013. }
  14014. return chunks.join( "\n" );
  14015. };
  14016. function getShader ( type, string ) {
  14017. var shader;
  14018. if ( type === "fragment" ) {
  14019. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  14020. } else if ( type === "vertex" ) {
  14021. shader = _gl.createShader( _gl.VERTEX_SHADER );
  14022. }
  14023. _gl.shaderSource( shader, string );
  14024. _gl.compileShader( shader );
  14025. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  14026. console.error( _gl.getShaderInfoLog( shader ) );
  14027. console.error( addLineNumbers( string ) );
  14028. return null;
  14029. }
  14030. return shader;
  14031. };
  14032. // Textures
  14033. function isPowerOfTwo ( value ) {
  14034. return ( value & ( value - 1 ) ) === 0;
  14035. };
  14036. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  14037. if ( isImagePowerOfTwo ) {
  14038. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  14039. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  14040. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  14041. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  14042. } else {
  14043. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  14044. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  14045. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  14046. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  14047. }
  14048. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  14049. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  14050. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  14051. texture.__oldAnisotropy = texture.anisotropy;
  14052. }
  14053. }
  14054. };
  14055. this.setTexture = function ( texture, slot ) {
  14056. if ( texture.needsUpdate ) {
  14057. if ( ! texture.__webglInit ) {
  14058. texture.__webglInit = true;
  14059. texture.addEventListener( 'dispose', onTextureDispose );
  14060. texture.__webglTexture = _gl.createTexture();
  14061. _this.info.memory.textures ++;
  14062. }
  14063. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14064. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14065. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14066. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14067. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14068. var image = texture.image,
  14069. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  14070. glFormat = paramThreeToGL( texture.format ),
  14071. glType = paramThreeToGL( texture.type );
  14072. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  14073. var mipmap, mipmaps = texture.mipmaps;
  14074. if ( texture instanceof THREE.DataTexture ) {
  14075. // use manually created mipmaps if available
  14076. // if there are no manual mipmaps
  14077. // set 0 level mipmap and then use GL to generate other mipmap levels
  14078. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14079. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14080. mipmap = mipmaps[ i ];
  14081. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14082. }
  14083. texture.generateMipmaps = false;
  14084. } else {
  14085. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14086. }
  14087. } else if ( texture instanceof THREE.CompressedTexture ) {
  14088. // compressed textures can only use manually created mipmaps
  14089. // WebGL can't generate mipmaps for DDS textures
  14090. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14091. mipmap = mipmaps[ i ];
  14092. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14093. }
  14094. } else { // regular Texture (image, video, canvas)
  14095. // use manually created mipmaps if available
  14096. // if there are no manual mipmaps
  14097. // set 0 level mipmap and then use GL to generate other mipmap levels
  14098. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14099. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14100. mipmap = mipmaps[ i ];
  14101. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  14102. }
  14103. texture.generateMipmaps = false;
  14104. } else {
  14105. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  14106. }
  14107. }
  14108. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14109. texture.needsUpdate = false;
  14110. if ( texture.onUpdate ) texture.onUpdate();
  14111. } else {
  14112. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14113. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14114. }
  14115. };
  14116. function clampToMaxSize ( image, maxSize ) {
  14117. if ( image.width <= maxSize && image.height <= maxSize ) {
  14118. return image;
  14119. }
  14120. // Warning: Scaling through the canvas will only work with images that use
  14121. // premultiplied alpha.
  14122. var maxDimension = Math.max( image.width, image.height );
  14123. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  14124. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  14125. var canvas = document.createElement( 'canvas' );
  14126. canvas.width = newWidth;
  14127. canvas.height = newHeight;
  14128. var ctx = canvas.getContext( "2d" );
  14129. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  14130. return canvas;
  14131. }
  14132. function setCubeTexture ( texture, slot ) {
  14133. if ( texture.image.length === 6 ) {
  14134. if ( texture.needsUpdate ) {
  14135. if ( ! texture.image.__webglTextureCube ) {
  14136. texture.image.__webglTextureCube = _gl.createTexture();
  14137. _this.info.memory.textures ++;
  14138. }
  14139. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14140. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  14141. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14142. var isCompressed = texture instanceof THREE.CompressedTexture;
  14143. var cubeImage = [];
  14144. for ( var i = 0; i < 6; i ++ ) {
  14145. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  14146. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  14147. } else {
  14148. cubeImage[ i ] = texture.image[ i ];
  14149. }
  14150. }
  14151. var image = cubeImage[ 0 ],
  14152. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  14153. glFormat = paramThreeToGL( texture.format ),
  14154. glType = paramThreeToGL( texture.type );
  14155. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  14156. for ( var i = 0; i < 6; i ++ ) {
  14157. if ( isCompressed ) {
  14158. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  14159. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  14160. mipmap = mipmaps[ j ];
  14161. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14162. }
  14163. } else {
  14164. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  14165. }
  14166. }
  14167. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  14168. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14169. }
  14170. texture.needsUpdate = false;
  14171. if ( texture.onUpdate ) texture.onUpdate();
  14172. } else {
  14173. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14174. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  14175. }
  14176. }
  14177. };
  14178. function setCubeTextureDynamic ( texture, slot ) {
  14179. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14180. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  14181. };
  14182. // Render targets
  14183. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  14184. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14185. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  14186. };
  14187. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  14188. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  14189. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14190. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  14191. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14192. /* For some reason this is not working. Defaulting to RGBA4.
  14193. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14194. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  14195. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14196. */
  14197. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14198. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  14199. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14200. } else {
  14201. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  14202. }
  14203. };
  14204. this.setRenderTarget = function ( renderTarget ) {
  14205. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  14206. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  14207. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  14208. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  14209. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  14210. renderTarget.__webglTexture = _gl.createTexture();
  14211. _this.info.memory.textures ++;
  14212. // Setup texture, create render and frame buffers
  14213. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  14214. glFormat = paramThreeToGL( renderTarget.format ),
  14215. glType = paramThreeToGL( renderTarget.type );
  14216. if ( isCube ) {
  14217. renderTarget.__webglFramebuffer = [];
  14218. renderTarget.__webglRenderbuffer = [];
  14219. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  14220. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  14221. for ( var i = 0; i < 6; i ++ ) {
  14222. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  14223. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  14224. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14225. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  14226. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  14227. }
  14228. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14229. } else {
  14230. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  14231. if ( renderTarget.shareDepthFrom ) {
  14232. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  14233. } else {
  14234. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  14235. }
  14236. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  14237. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  14238. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14239. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  14240. if ( renderTarget.shareDepthFrom ) {
  14241. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14242. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  14243. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14244. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  14245. }
  14246. } else {
  14247. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  14248. }
  14249. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14250. }
  14251. // Release everything
  14252. if ( isCube ) {
  14253. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  14254. } else {
  14255. _gl.bindTexture( _gl.TEXTURE_2D, null );
  14256. }
  14257. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  14258. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14259. }
  14260. var framebuffer, width, height, vx, vy;
  14261. if ( renderTarget ) {
  14262. if ( isCube ) {
  14263. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  14264. } else {
  14265. framebuffer = renderTarget.__webglFramebuffer;
  14266. }
  14267. width = renderTarget.width;
  14268. height = renderTarget.height;
  14269. vx = 0;
  14270. vy = 0;
  14271. } else {
  14272. framebuffer = null;
  14273. width = _viewportWidth;
  14274. height = _viewportHeight;
  14275. vx = _viewportX;
  14276. vy = _viewportY;
  14277. }
  14278. if ( framebuffer !== _currentFramebuffer ) {
  14279. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14280. _gl.viewport( vx, vy, width, height );
  14281. _currentFramebuffer = framebuffer;
  14282. }
  14283. _currentWidth = width;
  14284. _currentHeight = height;
  14285. };
  14286. function updateRenderTargetMipmap ( renderTarget ) {
  14287. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  14288. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  14289. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14290. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  14291. } else {
  14292. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  14293. _gl.generateMipmap( _gl.TEXTURE_2D );
  14294. _gl.bindTexture( _gl.TEXTURE_2D, null );
  14295. }
  14296. };
  14297. // Fallback filters for non-power-of-2 textures
  14298. function filterFallback ( f ) {
  14299. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  14300. return _gl.NEAREST;
  14301. }
  14302. return _gl.LINEAR;
  14303. };
  14304. // Map three.js constants to WebGL constants
  14305. function paramThreeToGL ( p ) {
  14306. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  14307. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  14308. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  14309. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  14310. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  14311. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  14312. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  14313. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  14314. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  14315. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  14316. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  14317. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  14318. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  14319. if ( p === THREE.ByteType ) return _gl.BYTE;
  14320. if ( p === THREE.ShortType ) return _gl.SHORT;
  14321. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  14322. if ( p === THREE.IntType ) return _gl.INT;
  14323. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  14324. if ( p === THREE.FloatType ) return _gl.FLOAT;
  14325. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  14326. if ( p === THREE.RGBFormat ) return _gl.RGB;
  14327. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  14328. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  14329. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  14330. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  14331. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  14332. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  14333. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  14334. if ( p === THREE.OneFactor ) return _gl.ONE;
  14335. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  14336. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  14337. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  14338. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  14339. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  14340. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  14341. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  14342. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  14343. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  14344. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  14345. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14346. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14347. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14348. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14349. }
  14350. return 0;
  14351. };
  14352. // Allocations
  14353. function allocateBones ( object ) {
  14354. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  14355. return 1024;
  14356. } else {
  14357. // default for when object is not specified
  14358. // ( for example when prebuilding shader
  14359. // to be used with multiple objects )
  14360. //
  14361. // - leave some extra space for other uniforms
  14362. // - limit here is ANGLE's 254 max uniform vectors
  14363. // (up to 54 should be safe)
  14364. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  14365. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  14366. var maxBones = nVertexMatrices;
  14367. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  14368. maxBones = Math.min( object.bones.length, maxBones );
  14369. if ( maxBones < object.bones.length ) {
  14370. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  14371. }
  14372. }
  14373. return maxBones;
  14374. }
  14375. };
  14376. function allocateLights ( lights ) {
  14377. var l, ll, light, dirLights, pointLights, spotLights, hemiLights;
  14378. dirLights = pointLights = spotLights = hemiLights = 0;
  14379. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14380. light = lights[ l ];
  14381. if ( light.onlyShadow ) continue;
  14382. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  14383. if ( light instanceof THREE.PointLight ) pointLights ++;
  14384. if ( light instanceof THREE.SpotLight ) spotLights ++;
  14385. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  14386. }
  14387. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  14388. };
  14389. function allocateShadows ( lights ) {
  14390. var l, ll, light, maxShadows = 0;
  14391. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  14392. light = lights[ l ];
  14393. if ( ! light.castShadow ) continue;
  14394. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  14395. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  14396. }
  14397. return maxShadows;
  14398. };
  14399. // Initialization
  14400. function initGL () {
  14401. try {
  14402. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  14403. throw 'Error creating WebGL context.';
  14404. }
  14405. } catch ( error ) {
  14406. console.error( error );
  14407. }
  14408. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  14409. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  14410. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) ||
  14411. _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) ||
  14412. _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  14413. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) ||
  14414. _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) ||
  14415. _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  14416. if ( ! _glExtensionTextureFloat ) {
  14417. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  14418. }
  14419. if ( ! _glExtensionStandardDerivatives ) {
  14420. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  14421. }
  14422. if ( ! _glExtensionTextureFilterAnisotropic ) {
  14423. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  14424. }
  14425. if ( ! _glExtensionCompressedTextureS3TC ) {
  14426. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  14427. }
  14428. };
  14429. function setDefaultGLState () {
  14430. _gl.clearColor( 0, 0, 0, 1 );
  14431. _gl.clearDepth( 1 );
  14432. _gl.clearStencil( 0 );
  14433. _gl.enable( _gl.DEPTH_TEST );
  14434. _gl.depthFunc( _gl.LEQUAL );
  14435. _gl.frontFace( _gl.CCW );
  14436. _gl.cullFace( _gl.BACK );
  14437. _gl.enable( _gl.CULL_FACE );
  14438. _gl.enable( _gl.BLEND );
  14439. _gl.blendEquation( _gl.FUNC_ADD );
  14440. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  14441. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  14442. };
  14443. // default plugins (order is important)
  14444. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  14445. this.addPrePlugin( this.shadowMapPlugin );
  14446. this.addPostPlugin( new THREE.SpritePlugin() );
  14447. this.addPostPlugin( new THREE.LensFlarePlugin() );
  14448. };
  14449. /**
  14450. * @author szimek / https://github.com/szimek/
  14451. * @author alteredq / http://alteredqualia.com/
  14452. */
  14453. THREE.WebGLRenderTarget = function ( width, height, options ) {
  14454. THREE.EventDispatcher.call( this );
  14455. this.width = width;
  14456. this.height = height;
  14457. options = options || {};
  14458. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  14459. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  14460. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  14461. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  14462. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  14463. this.offset = new THREE.Vector2( 0, 0 );
  14464. this.repeat = new THREE.Vector2( 1, 1 );
  14465. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  14466. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  14467. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  14468. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  14469. this.generateMipmaps = true;
  14470. this.shareDepthFrom = null;
  14471. };
  14472. THREE.WebGLRenderTarget.prototype.clone = function() {
  14473. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  14474. tmp.wrapS = this.wrapS;
  14475. tmp.wrapT = this.wrapT;
  14476. tmp.magFilter = this.magFilter;
  14477. tmp.minFilter = this.minFilter;
  14478. tmp.anisotropy = this.anisotropy;
  14479. tmp.offset.copy( this.offset );
  14480. tmp.repeat.copy( this.repeat );
  14481. tmp.format = this.format;
  14482. tmp.type = this.type;
  14483. tmp.depthBuffer = this.depthBuffer;
  14484. tmp.stencilBuffer = this.stencilBuffer;
  14485. tmp.generateMipmaps = this.generateMipmaps;
  14486. tmp.shareDepthFrom = this.shareDepthFrom;
  14487. return tmp;
  14488. };
  14489. THREE.WebGLRenderTarget.prototype.dispose = function () {
  14490. this.dispatchEvent( { type: 'dispose' } );
  14491. };
  14492. /**
  14493. * @author alteredq / http://alteredqualia.com
  14494. */
  14495. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  14496. THREE.WebGLRenderTarget.call( this, width, height, options );
  14497. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  14498. };
  14499. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  14500. /**
  14501. * @author mrdoob / http://mrdoob.com/
  14502. */
  14503. THREE.RenderableVertex = function () {
  14504. this.positionWorld = new THREE.Vector3();
  14505. this.positionScreen = new THREE.Vector4();
  14506. this.visible = true;
  14507. };
  14508. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  14509. this.positionWorld.copy( vertex.positionWorld );
  14510. this.positionScreen.copy( vertex.positionScreen );
  14511. };
  14512. /**
  14513. * @author mrdoob / http://mrdoob.com/
  14514. */
  14515. THREE.RenderableFace3 = function () {
  14516. this.v1 = new THREE.RenderableVertex();
  14517. this.v2 = new THREE.RenderableVertex();
  14518. this.v3 = new THREE.RenderableVertex();
  14519. this.centroidModel = new THREE.Vector3();
  14520. this.normalModel = new THREE.Vector3();
  14521. this.normalModelView = new THREE.Vector3();
  14522. this.vertexNormalsLength = 0;
  14523. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  14524. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  14525. this.color = null;
  14526. this.material = null;
  14527. this.uvs = [[]];
  14528. this.z = null;
  14529. };
  14530. /**
  14531. * @author mrdoob / http://mrdoob.com/
  14532. */
  14533. THREE.RenderableFace4 = function () {
  14534. this.v1 = new THREE.RenderableVertex();
  14535. this.v2 = new THREE.RenderableVertex();
  14536. this.v3 = new THREE.RenderableVertex();
  14537. this.v4 = new THREE.RenderableVertex();
  14538. this.centroidModel = new THREE.Vector3();
  14539. this.normalModel = new THREE.Vector3();
  14540. this.normalModelView = new THREE.Vector3();
  14541. this.vertexNormalsLength = 0;
  14542. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  14543. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  14544. this.color = null;
  14545. this.material = null;
  14546. this.uvs = [[]];
  14547. this.z = null;
  14548. };
  14549. /**
  14550. * @author mrdoob / http://mrdoob.com/
  14551. */
  14552. THREE.RenderableObject = function () {
  14553. this.object = null;
  14554. this.z = null;
  14555. };
  14556. /**
  14557. * @author mrdoob / http://mrdoob.com/
  14558. */
  14559. THREE.RenderableParticle = function () {
  14560. this.object = null;
  14561. this.x = null;
  14562. this.y = null;
  14563. this.z = null;
  14564. this.rotation = null;
  14565. this.scale = new THREE.Vector2();
  14566. this.material = null;
  14567. };
  14568. /**
  14569. * @author mrdoob / http://mrdoob.com/
  14570. */
  14571. THREE.RenderableLine = function () {
  14572. this.z = null;
  14573. this.v1 = new THREE.RenderableVertex();
  14574. this.v2 = new THREE.RenderableVertex();
  14575. this.material = null;
  14576. };
  14577. /**
  14578. * @author alteredq / http://alteredqualia.com/
  14579. */
  14580. THREE.ColorUtils = {
  14581. adjustHSV : function ( color, h, s, v ) {
  14582. var hsv = THREE.ColorUtils.__hsv;
  14583. color.getHSV( hsv );
  14584. hsv.h = THREE.Math.clamp( hsv.h + h, 0, 1 );
  14585. hsv.s = THREE.Math.clamp( hsv.s + s, 0, 1 );
  14586. hsv.v = THREE.Math.clamp( hsv.v + v, 0, 1 );
  14587. color.setHSV( hsv.h, hsv.s, hsv.v );
  14588. }
  14589. };
  14590. THREE.ColorUtils.__hsv = { h: 0, s: 0, v: 0 };/**
  14591. * @author mrdoob / http://mrdoob.com/
  14592. * @author alteredq / http://alteredqualia.com/
  14593. */
  14594. THREE.GeometryUtils = {
  14595. // Merge two geometries or geometry and geometry from object (using object's transform)
  14596. merge: function ( geometry1, object2 /* mesh | geometry */ ) {
  14597. var matrix, normalMatrix,
  14598. vertexOffset = geometry1.vertices.length,
  14599. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  14600. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  14601. vertices1 = geometry1.vertices,
  14602. vertices2 = geometry2.vertices,
  14603. faces1 = geometry1.faces,
  14604. faces2 = geometry2.faces,
  14605. uvs1 = geometry1.faceVertexUvs[ 0 ],
  14606. uvs2 = geometry2.faceVertexUvs[ 0 ];
  14607. if ( object2 instanceof THREE.Mesh ) {
  14608. object2.matrixAutoUpdate && object2.updateMatrix();
  14609. matrix = object2.matrix;
  14610. normalMatrix = new THREE.Matrix3();
  14611. normalMatrix.getInverse( matrix );
  14612. normalMatrix.transpose();
  14613. }
  14614. // vertices
  14615. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  14616. var vertex = vertices2[ i ];
  14617. var vertexCopy = vertex.clone();
  14618. if ( matrix ) vertexCopy.applyMatrix4( matrix );
  14619. vertices1.push( vertexCopy );
  14620. }
  14621. // faces
  14622. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  14623. var face = faces2[ i ], faceCopy, normal, color,
  14624. faceVertexNormals = face.vertexNormals,
  14625. faceVertexColors = face.vertexColors;
  14626. if ( face instanceof THREE.Face3 ) {
  14627. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  14628. } else if ( face instanceof THREE.Face4 ) {
  14629. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  14630. }
  14631. faceCopy.normal.copy( face.normal );
  14632. if ( normalMatrix ) {
  14633. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  14634. }
  14635. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  14636. normal = faceVertexNormals[ j ].clone();
  14637. if ( normalMatrix ) {
  14638. normal.applyMatrix3( normalMatrix ).normalize();
  14639. }
  14640. faceCopy.vertexNormals.push( normal );
  14641. }
  14642. faceCopy.color.copy( face.color );
  14643. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  14644. color = faceVertexColors[ j ];
  14645. faceCopy.vertexColors.push( color.clone() );
  14646. }
  14647. faceCopy.materialIndex = face.materialIndex;
  14648. faceCopy.centroid.copy( face.centroid );
  14649. if ( matrix ) {
  14650. faceCopy.centroid.applyMatrix4( matrix );
  14651. }
  14652. faces1.push( faceCopy );
  14653. }
  14654. // uvs
  14655. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  14656. var uv = uvs2[ i ], uvCopy = [];
  14657. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  14658. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  14659. }
  14660. uvs1.push( uvCopy );
  14661. }
  14662. },
  14663. removeMaterials: function ( geometry, materialIndexArray ) {
  14664. var materialIndexMap = {};
  14665. for ( var i = 0, il = materialIndexArray.length; i < il; i ++ ) {
  14666. materialIndexMap[ materialIndexArray[i] ] = true;
  14667. }
  14668. var face, newFaces = [];
  14669. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14670. face = geometry.faces[ i ];
  14671. if ( ! ( face.materialIndex in materialIndexMap ) ) newFaces.push( face );
  14672. }
  14673. geometry.faces = newFaces;
  14674. },
  14675. // Get random point in triangle (via barycentric coordinates)
  14676. // (uniform distribution)
  14677. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  14678. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  14679. var a, b, c,
  14680. point = new THREE.Vector3(),
  14681. tmp = THREE.GeometryUtils.__v1;
  14682. a = THREE.GeometryUtils.random();
  14683. b = THREE.GeometryUtils.random();
  14684. if ( ( a + b ) > 1 ) {
  14685. a = 1 - a;
  14686. b = 1 - b;
  14687. }
  14688. c = 1 - a - b;
  14689. point.copy( vectorA );
  14690. point.multiplyScalar( a );
  14691. tmp.copy( vectorB );
  14692. tmp.multiplyScalar( b );
  14693. point.add( tmp );
  14694. tmp.copy( vectorC );
  14695. tmp.multiplyScalar( c );
  14696. point.add( tmp );
  14697. return point;
  14698. },
  14699. // Get random point in face (triangle / quad)
  14700. // (uniform distribution)
  14701. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  14702. var vA, vB, vC, vD;
  14703. if ( face instanceof THREE.Face3 ) {
  14704. vA = geometry.vertices[ face.a ];
  14705. vB = geometry.vertices[ face.b ];
  14706. vC = geometry.vertices[ face.c ];
  14707. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  14708. } else if ( face instanceof THREE.Face4 ) {
  14709. vA = geometry.vertices[ face.a ];
  14710. vB = geometry.vertices[ face.b ];
  14711. vC = geometry.vertices[ face.c ];
  14712. vD = geometry.vertices[ face.d ];
  14713. var area1, area2;
  14714. if ( useCachedAreas ) {
  14715. if ( face._area1 && face._area2 ) {
  14716. area1 = face._area1;
  14717. area2 = face._area2;
  14718. } else {
  14719. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  14720. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  14721. face._area1 = area1;
  14722. face._area2 = area2;
  14723. }
  14724. } else {
  14725. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  14726. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  14727. }
  14728. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  14729. if ( r < area1 ) {
  14730. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  14731. } else {
  14732. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  14733. }
  14734. }
  14735. },
  14736. // Get uniformly distributed random points in mesh
  14737. // - create array with cumulative sums of face areas
  14738. // - pick random number from 0 to total area
  14739. // - find corresponding place in area array by binary search
  14740. // - get random point in face
  14741. randomPointsInGeometry: function ( geometry, n ) {
  14742. var face, i,
  14743. faces = geometry.faces,
  14744. vertices = geometry.vertices,
  14745. il = faces.length,
  14746. totalArea = 0,
  14747. cumulativeAreas = [],
  14748. vA, vB, vC, vD;
  14749. // precompute face areas
  14750. for ( i = 0; i < il; i ++ ) {
  14751. face = faces[ i ];
  14752. if ( face instanceof THREE.Face3 ) {
  14753. vA = vertices[ face.a ];
  14754. vB = vertices[ face.b ];
  14755. vC = vertices[ face.c ];
  14756. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  14757. } else if ( face instanceof THREE.Face4 ) {
  14758. vA = vertices[ face.a ];
  14759. vB = vertices[ face.b ];
  14760. vC = vertices[ face.c ];
  14761. vD = vertices[ face.d ];
  14762. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  14763. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  14764. face._area = face._area1 + face._area2;
  14765. }
  14766. totalArea += face._area;
  14767. cumulativeAreas[ i ] = totalArea;
  14768. }
  14769. // binary search cumulative areas array
  14770. function binarySearchIndices( value ) {
  14771. function binarySearch( start, end ) {
  14772. // return closest larger index
  14773. // if exact number is not found
  14774. if ( end < start )
  14775. return start;
  14776. var mid = start + Math.floor( ( end - start ) / 2 );
  14777. if ( cumulativeAreas[ mid ] > value ) {
  14778. return binarySearch( start, mid - 1 );
  14779. } else if ( cumulativeAreas[ mid ] < value ) {
  14780. return binarySearch( mid + 1, end );
  14781. } else {
  14782. return mid;
  14783. }
  14784. }
  14785. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  14786. return result;
  14787. }
  14788. // pick random face weighted by face area
  14789. var r, index,
  14790. result = [];
  14791. var stats = {};
  14792. for ( i = 0; i < n; i ++ ) {
  14793. r = THREE.GeometryUtils.random() * totalArea;
  14794. index = binarySearchIndices( r );
  14795. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  14796. if ( ! stats[ index ] ) {
  14797. stats[ index ] = 1;
  14798. } else {
  14799. stats[ index ] += 1;
  14800. }
  14801. }
  14802. return result;
  14803. },
  14804. // Get triangle area (half of parallelogram)
  14805. // http://mathworld.wolfram.com/TriangleArea.html
  14806. triangleArea: function ( vectorA, vectorB, vectorC ) {
  14807. var tmp1 = THREE.GeometryUtils.__v1,
  14808. tmp2 = THREE.GeometryUtils.__v2;
  14809. tmp1.subVectors( vectorB, vectorA );
  14810. tmp2.subVectors( vectorC, vectorA );
  14811. tmp1.cross( tmp2 );
  14812. return 0.5 * tmp1.length();
  14813. },
  14814. // Center geometry so that 0,0,0 is in center of bounding box
  14815. center: function ( geometry ) {
  14816. geometry.computeBoundingBox();
  14817. var bb = geometry.boundingBox;
  14818. var offset = new THREE.Vector3();
  14819. offset.addVectors( bb.min, bb.max );
  14820. offset.multiplyScalar( -0.5 );
  14821. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset ) );
  14822. geometry.computeBoundingBox();
  14823. return offset;
  14824. },
  14825. // Normalize UVs to be from <0,1>
  14826. // (for now just the first set of UVs)
  14827. normalizeUVs: function ( geometry ) {
  14828. var uvSet = geometry.faceVertexUvs[ 0 ];
  14829. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  14830. var uvs = uvSet[ i ];
  14831. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  14832. // texture repeat
  14833. if( uvs[ j ].x !== 1.0 ) uvs[ j ].x = uvs[ j ].x - Math.floor( uvs[ j ].x );
  14834. if( uvs[ j ].y !== 1.0 ) uvs[ j ].y = uvs[ j ].y - Math.floor( uvs[ j ].y );
  14835. }
  14836. }
  14837. },
  14838. triangulateQuads: function ( geometry ) {
  14839. var i, il, j, jl;
  14840. var faces = [];
  14841. var faceUvs = [];
  14842. var faceVertexUvs = [];
  14843. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  14844. faceUvs[ i ] = [];
  14845. }
  14846. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  14847. faceVertexUvs[ i ] = [];
  14848. }
  14849. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14850. var face = geometry.faces[ i ];
  14851. if ( face instanceof THREE.Face4 ) {
  14852. var a = face.a;
  14853. var b = face.b;
  14854. var c = face.c;
  14855. var d = face.d;
  14856. var triA = new THREE.Face3();
  14857. var triB = new THREE.Face3();
  14858. triA.color.copy( face.color );
  14859. triB.color.copy( face.color );
  14860. triA.materialIndex = face.materialIndex;
  14861. triB.materialIndex = face.materialIndex;
  14862. triA.a = a;
  14863. triA.b = b;
  14864. triA.c = d;
  14865. triB.a = b;
  14866. triB.b = c;
  14867. triB.c = d;
  14868. if ( face.vertexColors.length === 4 ) {
  14869. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  14870. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  14871. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  14872. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  14873. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  14874. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  14875. }
  14876. faces.push( triA, triB );
  14877. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14878. if ( geometry.faceVertexUvs[ j ].length ) {
  14879. var uvs = geometry.faceVertexUvs[ j ][ i ];
  14880. var uvA = uvs[ 0 ];
  14881. var uvB = uvs[ 1 ];
  14882. var uvC = uvs[ 2 ];
  14883. var uvD = uvs[ 3 ];
  14884. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  14885. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  14886. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  14887. }
  14888. }
  14889. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  14890. if ( geometry.faceUvs[ j ].length ) {
  14891. var faceUv = geometry.faceUvs[ j ][ i ];
  14892. faceUvs[ j ].push( faceUv, faceUv );
  14893. }
  14894. }
  14895. } else {
  14896. faces.push( face );
  14897. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  14898. faceUvs[ j ].push( geometry.faceUvs[ j ][ i ] );
  14899. }
  14900. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14901. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  14902. }
  14903. }
  14904. }
  14905. geometry.faces = faces;
  14906. geometry.faceUvs = faceUvs;
  14907. geometry.faceVertexUvs = faceVertexUvs;
  14908. geometry.computeCentroids();
  14909. geometry.computeFaceNormals();
  14910. geometry.computeVertexNormals();
  14911. if ( geometry.hasTangents ) geometry.computeTangents();
  14912. },
  14913. setMaterialIndex: function ( geometry, index, startFace, endFace ){
  14914. var faces = geometry.faces;
  14915. var start = startFace || 0;
  14916. var end = endFace || faces.length - 1;
  14917. for ( var i = start; i <= end; i ++ ) {
  14918. faces[i].materialIndex = index;
  14919. }
  14920. }
  14921. };
  14922. THREE.GeometryUtils.random = THREE.Math.random16;
  14923. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  14924. THREE.GeometryUtils.__v2 = new THREE.Vector3();
  14925. /**
  14926. * @author alteredq / http://alteredqualia.com/
  14927. * @author mrdoob / http://mrdoob.com/
  14928. */
  14929. THREE.ImageUtils = {
  14930. crossOrigin: 'anonymous',
  14931. loadTexture: function ( url, mapping, onLoad, onError ) {
  14932. var image = new Image();
  14933. var texture = new THREE.Texture( image, mapping );
  14934. var loader = new THREE.ImageLoader();
  14935. loader.addEventListener( 'load', function ( event ) {
  14936. texture.image = event.content;
  14937. texture.needsUpdate = true;
  14938. if ( onLoad ) onLoad( texture );
  14939. } );
  14940. loader.addEventListener( 'error', function ( event ) {
  14941. if ( onError ) onError( event.message );
  14942. } );
  14943. loader.crossOrigin = this.crossOrigin;
  14944. loader.load( url, image );
  14945. texture.sourceFile = url;
  14946. return texture;
  14947. },
  14948. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  14949. var texture = new THREE.CompressedTexture();
  14950. texture.mapping = mapping;
  14951. var request = new XMLHttpRequest();
  14952. request.onload = function () {
  14953. var buffer = request.response;
  14954. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  14955. texture.format = dds.format;
  14956. texture.mipmaps = dds.mipmaps;
  14957. texture.image.width = dds.width;
  14958. texture.image.height = dds.height;
  14959. // gl.generateMipmap fails for compressed textures
  14960. // mipmaps must be embedded in the DDS file
  14961. // or texture filters must not use mipmapping
  14962. texture.generateMipmaps = false;
  14963. texture.needsUpdate = true;
  14964. if ( onLoad ) onLoad( texture );
  14965. }
  14966. request.onerror = onError;
  14967. request.open( 'GET', url, true );
  14968. request.responseType = "arraybuffer";
  14969. request.send( null );
  14970. return texture;
  14971. },
  14972. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  14973. var images = [];
  14974. images.loadCount = 0;
  14975. var texture = new THREE.Texture();
  14976. texture.image = images;
  14977. if ( mapping !== undefined ) texture.mapping = mapping;
  14978. // no flipping needed for cube textures
  14979. texture.flipY = false;
  14980. for ( var i = 0, il = array.length; i < il; ++ i ) {
  14981. var cubeImage = new Image();
  14982. images[ i ] = cubeImage;
  14983. cubeImage.onload = function () {
  14984. images.loadCount += 1;
  14985. if ( images.loadCount === 6 ) {
  14986. texture.needsUpdate = true;
  14987. if ( onLoad ) onLoad( texture );
  14988. }
  14989. };
  14990. cubeImage.onerror = onError;
  14991. cubeImage.crossOrigin = this.crossOrigin;
  14992. cubeImage.src = array[ i ];
  14993. }
  14994. return texture;
  14995. },
  14996. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  14997. var images = [];
  14998. images.loadCount = 0;
  14999. var texture = new THREE.CompressedTexture();
  15000. texture.image = images;
  15001. if ( mapping !== undefined ) texture.mapping = mapping;
  15002. // no flipping for cube textures
  15003. // (also flipping doesn't work for compressed textures )
  15004. texture.flipY = false;
  15005. // can't generate mipmaps for compressed textures
  15006. // mips must be embedded in DDS files
  15007. texture.generateMipmaps = false;
  15008. var generateCubeFaceCallback = function ( rq, img ) {
  15009. return function () {
  15010. var buffer = rq.response;
  15011. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15012. img.format = dds.format;
  15013. img.mipmaps = dds.mipmaps;
  15014. img.width = dds.width;
  15015. img.height = dds.height;
  15016. images.loadCount += 1;
  15017. if ( images.loadCount === 6 ) {
  15018. texture.format = dds.format;
  15019. texture.needsUpdate = true;
  15020. if ( onLoad ) onLoad( texture );
  15021. }
  15022. }
  15023. }
  15024. // compressed cubemap textures as 6 separate DDS files
  15025. if ( array instanceof Array ) {
  15026. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15027. var cubeImage = {};
  15028. images[ i ] = cubeImage;
  15029. var request = new XMLHttpRequest();
  15030. request.onload = generateCubeFaceCallback( request, cubeImage );
  15031. request.onerror = onError;
  15032. var url = array[ i ];
  15033. request.open( 'GET', url, true );
  15034. request.responseType = "arraybuffer";
  15035. request.send( null );
  15036. }
  15037. // compressed cubemap texture stored in a single DDS file
  15038. } else {
  15039. var url = array;
  15040. var request = new XMLHttpRequest();
  15041. request.onload = function( ) {
  15042. var buffer = request.response;
  15043. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15044. if ( dds.isCubemap ) {
  15045. var faces = dds.mipmaps.length / dds.mipmapCount;
  15046. for ( var f = 0; f < faces; f ++ ) {
  15047. images[ f ] = { mipmaps : [] };
  15048. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15049. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  15050. images[ f ].format = dds.format;
  15051. images[ f ].width = dds.width;
  15052. images[ f ].height = dds.height;
  15053. }
  15054. }
  15055. texture.format = dds.format;
  15056. texture.needsUpdate = true;
  15057. if ( onLoad ) onLoad( texture );
  15058. }
  15059. }
  15060. request.onerror = onError;
  15061. request.open( 'GET', url, true );
  15062. request.responseType = "arraybuffer";
  15063. request.send( null );
  15064. }
  15065. return texture;
  15066. },
  15067. parseDDS: function ( buffer, loadMipmaps ) {
  15068. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  15069. // Adapted from @toji's DDS utils
  15070. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  15071. // All values and structures referenced from:
  15072. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  15073. var DDS_MAGIC = 0x20534444;
  15074. var DDSD_CAPS = 0x1,
  15075. DDSD_HEIGHT = 0x2,
  15076. DDSD_WIDTH = 0x4,
  15077. DDSD_PITCH = 0x8,
  15078. DDSD_PIXELFORMAT = 0x1000,
  15079. DDSD_MIPMAPCOUNT = 0x20000,
  15080. DDSD_LINEARSIZE = 0x80000,
  15081. DDSD_DEPTH = 0x800000;
  15082. var DDSCAPS_COMPLEX = 0x8,
  15083. DDSCAPS_MIPMAP = 0x400000,
  15084. DDSCAPS_TEXTURE = 0x1000;
  15085. var DDSCAPS2_CUBEMAP = 0x200,
  15086. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  15087. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  15088. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  15089. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  15090. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  15091. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  15092. DDSCAPS2_VOLUME = 0x200000;
  15093. var DDPF_ALPHAPIXELS = 0x1,
  15094. DDPF_ALPHA = 0x2,
  15095. DDPF_FOURCC = 0x4,
  15096. DDPF_RGB = 0x40,
  15097. DDPF_YUV = 0x200,
  15098. DDPF_LUMINANCE = 0x20000;
  15099. function fourCCToInt32( value ) {
  15100. return value.charCodeAt(0) +
  15101. (value.charCodeAt(1) << 8) +
  15102. (value.charCodeAt(2) << 16) +
  15103. (value.charCodeAt(3) << 24);
  15104. }
  15105. function int32ToFourCC( value ) {
  15106. return String.fromCharCode(
  15107. value & 0xff,
  15108. (value >> 8) & 0xff,
  15109. (value >> 16) & 0xff,
  15110. (value >> 24) & 0xff
  15111. );
  15112. }
  15113. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  15114. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  15115. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  15116. var headerLengthInt = 31; // The header length in 32 bit ints
  15117. // Offsets into the header array
  15118. var off_magic = 0;
  15119. var off_size = 1;
  15120. var off_flags = 2;
  15121. var off_height = 3;
  15122. var off_width = 4;
  15123. var off_mipmapCount = 7;
  15124. var off_pfFlags = 20;
  15125. var off_pfFourCC = 21;
  15126. var off_caps = 27;
  15127. var off_caps2 = 28;
  15128. var off_caps3 = 29;
  15129. var off_caps4 = 30;
  15130. // Parse header
  15131. var header = new Int32Array( buffer, 0, headerLengthInt );
  15132. if ( header[ off_magic ] !== DDS_MAGIC ) {
  15133. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  15134. return dds;
  15135. }
  15136. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  15137. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  15138. return dds;
  15139. }
  15140. var blockBytes;
  15141. var fourCC = header[ off_pfFourCC ];
  15142. switch ( fourCC ) {
  15143. case FOURCC_DXT1:
  15144. blockBytes = 8;
  15145. dds.format = THREE.RGB_S3TC_DXT1_Format;
  15146. break;
  15147. case FOURCC_DXT3:
  15148. blockBytes = 16;
  15149. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  15150. break;
  15151. case FOURCC_DXT5:
  15152. blockBytes = 16;
  15153. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  15154. break;
  15155. default:
  15156. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  15157. return dds;
  15158. }
  15159. dds.mipmapCount = 1;
  15160. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  15161. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  15162. }
  15163. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  15164. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  15165. dds.width = header[ off_width ];
  15166. dds.height = header[ off_height ];
  15167. var dataOffset = header[ off_size ] + 4;
  15168. // Extract mipmaps buffers
  15169. var width = dds.width;
  15170. var height = dds.height;
  15171. var faces = dds.isCubemap ? 6 : 1;
  15172. for ( var face = 0; face < faces; face ++ ) {
  15173. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15174. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  15175. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  15176. var mipmap = { "data": byteArray, "width": width, "height": height };
  15177. dds.mipmaps.push( mipmap );
  15178. dataOffset += dataLength;
  15179. width = Math.max( width * 0.5, 1 );
  15180. height = Math.max( height * 0.5, 1 );
  15181. }
  15182. width = dds.width;
  15183. height = dds.height;
  15184. }
  15185. return dds;
  15186. },
  15187. getNormalMap: function ( image, depth ) {
  15188. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  15189. var cross = function ( a, b ) {
  15190. 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 ] ];
  15191. }
  15192. var subtract = function ( a, b ) {
  15193. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  15194. }
  15195. var normalize = function ( a ) {
  15196. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  15197. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  15198. }
  15199. depth = depth | 1;
  15200. var width = image.width;
  15201. var height = image.height;
  15202. var canvas = document.createElement( 'canvas' );
  15203. canvas.width = width;
  15204. canvas.height = height;
  15205. var context = canvas.getContext( '2d' );
  15206. context.drawImage( image, 0, 0 );
  15207. var data = context.getImageData( 0, 0, width, height ).data;
  15208. var imageData = context.createImageData( width, height );
  15209. var output = imageData.data;
  15210. for ( var x = 0; x < width; x ++ ) {
  15211. for ( var y = 0; y < height; y ++ ) {
  15212. var ly = y - 1 < 0 ? 0 : y - 1;
  15213. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  15214. var lx = x - 1 < 0 ? 0 : x - 1;
  15215. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  15216. var points = [];
  15217. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  15218. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  15219. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  15220. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  15221. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  15222. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  15223. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  15224. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  15225. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  15226. var normals = [];
  15227. var num_points = points.length;
  15228. for ( var i = 0; i < num_points; i ++ ) {
  15229. var v1 = points[ i ];
  15230. var v2 = points[ ( i + 1 ) % num_points ];
  15231. v1 = subtract( v1, origin );
  15232. v2 = subtract( v2, origin );
  15233. normals.push( normalize( cross( v1, v2 ) ) );
  15234. }
  15235. var normal = [ 0, 0, 0 ];
  15236. for ( var i = 0; i < normals.length; i ++ ) {
  15237. normal[ 0 ] += normals[ i ][ 0 ];
  15238. normal[ 1 ] += normals[ i ][ 1 ];
  15239. normal[ 2 ] += normals[ i ][ 2 ];
  15240. }
  15241. normal[ 0 ] /= normals.length;
  15242. normal[ 1 ] /= normals.length;
  15243. normal[ 2 ] /= normals.length;
  15244. var idx = ( y * width + x ) * 4;
  15245. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15246. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15247. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  15248. output[ idx + 3 ] = 255;
  15249. }
  15250. }
  15251. context.putImageData( imageData, 0, 0 );
  15252. return canvas;
  15253. },
  15254. generateDataTexture: function ( width, height, color ) {
  15255. var size = width * height;
  15256. var data = new Uint8Array( 3 * size );
  15257. var r = Math.floor( color.r * 255 );
  15258. var g = Math.floor( color.g * 255 );
  15259. var b = Math.floor( color.b * 255 );
  15260. for ( var i = 0; i < size; i ++ ) {
  15261. data[ i * 3 ] = r;
  15262. data[ i * 3 + 1 ] = g;
  15263. data[ i * 3 + 2 ] = b;
  15264. }
  15265. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  15266. texture.needsUpdate = true;
  15267. return texture;
  15268. }
  15269. };
  15270. /**
  15271. * @author alteredq / http://alteredqualia.com/
  15272. */
  15273. THREE.SceneUtils = {
  15274. createMultiMaterialObject: function ( geometry, materials ) {
  15275. var group = new THREE.Object3D();
  15276. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  15277. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  15278. }
  15279. return group;
  15280. },
  15281. detach : function ( child, parent, scene ) {
  15282. child.applyMatrix( parent.matrixWorld );
  15283. parent.remove( child );
  15284. scene.add( child );
  15285. },
  15286. attach: function ( child, scene, parent ) {
  15287. var matrixWorldInverse = new THREE.Matrix4();
  15288. matrixWorldInverse.getInverse( parent.matrixWorld );
  15289. child.applyMatrix( matrixWorldInverse );
  15290. scene.remove( child );
  15291. parent.add( child );
  15292. }
  15293. };
  15294. /**
  15295. * @author alteredq / http://alteredqualia.com/
  15296. * @author mrdoob / http://mrdoob.com/
  15297. *
  15298. * ShaderUtils currently contains:
  15299. *
  15300. * fresnel
  15301. * normal
  15302. * cube
  15303. *
  15304. */
  15305. THREE.ShaderUtils = {
  15306. lib: {
  15307. /* -------------------------------------------------------------------------
  15308. // Fresnel shader
  15309. // - based on Nvidia Cg tutorial
  15310. ------------------------------------------------------------------------- */
  15311. 'fresnel': {
  15312. uniforms: {
  15313. "mRefractionRatio": { type: "f", value: 1.02 },
  15314. "mFresnelBias": { type: "f", value: 0.1 },
  15315. "mFresnelPower": { type: "f", value: 2.0 },
  15316. "mFresnelScale": { type: "f", value: 1.0 },
  15317. "tCube": { type: "t", value: null }
  15318. },
  15319. fragmentShader: [
  15320. "uniform samplerCube tCube;",
  15321. "varying vec3 vReflect;",
  15322. "varying vec3 vRefract[3];",
  15323. "varying float vReflectionFactor;",
  15324. "void main() {",
  15325. "vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  15326. "vec4 refractedColor = vec4( 1.0 );",
  15327. "refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;",
  15328. "refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;",
  15329. "refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;",
  15330. "gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );",
  15331. "}"
  15332. ].join("\n"),
  15333. vertexShader: [
  15334. "uniform float mRefractionRatio;",
  15335. "uniform float mFresnelBias;",
  15336. "uniform float mFresnelScale;",
  15337. "uniform float mFresnelPower;",
  15338. "varying vec3 vReflect;",
  15339. "varying vec3 vRefract[3];",
  15340. "varying float vReflectionFactor;",
  15341. "void main() {",
  15342. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  15343. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  15344. "vec3 worldNormal = normalize( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );",
  15345. "vec3 I = worldPosition.xyz - cameraPosition;",
  15346. "vReflect = reflect( I, worldNormal );",
  15347. "vRefract[0] = refract( normalize( I ), worldNormal, mRefractionRatio );",
  15348. "vRefract[1] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.99 );",
  15349. "vRefract[2] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.98 );",
  15350. "vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), worldNormal ), mFresnelPower );",
  15351. "gl_Position = projectionMatrix * mvPosition;",
  15352. "}"
  15353. ].join("\n")
  15354. },
  15355. /* -------------------------------------------------------------------------
  15356. // Normal map shader
  15357. // - Blinn-Phong
  15358. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  15359. // - point and directional lights (use with "lights: true" material option)
  15360. ------------------------------------------------------------------------- */
  15361. 'normal' : {
  15362. uniforms: THREE.UniformsUtils.merge( [
  15363. THREE.UniformsLib[ "fog" ],
  15364. THREE.UniformsLib[ "lights" ],
  15365. THREE.UniformsLib[ "shadowmap" ],
  15366. {
  15367. "enableAO" : { type: "i", value: 0 },
  15368. "enableDiffuse" : { type: "i", value: 0 },
  15369. "enableSpecular" : { type: "i", value: 0 },
  15370. "enableReflection": { type: "i", value: 0 },
  15371. "enableDisplacement": { type: "i", value: 0 },
  15372. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  15373. "tDiffuse" : { type: "t", value: null },
  15374. "tCube" : { type: "t", value: null },
  15375. "tNormal" : { type: "t", value: null },
  15376. "tSpecular" : { type: "t", value: null },
  15377. "tAO" : { type: "t", value: null },
  15378. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  15379. "uDisplacementBias": { type: "f", value: 0.0 },
  15380. "uDisplacementScale": { type: "f", value: 1.0 },
  15381. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  15382. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  15383. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  15384. "uShininess": { type: "f", value: 30 },
  15385. "uOpacity": { type: "f", value: 1 },
  15386. "useRefract": { type: "i", value: 0 },
  15387. "uRefractionRatio": { type: "f", value: 0.98 },
  15388. "uReflectivity": { type: "f", value: 0.5 },
  15389. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  15390. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  15391. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  15392. }
  15393. ] ),
  15394. fragmentShader: [
  15395. "uniform vec3 uAmbientColor;",
  15396. "uniform vec3 uDiffuseColor;",
  15397. "uniform vec3 uSpecularColor;",
  15398. "uniform float uShininess;",
  15399. "uniform float uOpacity;",
  15400. "uniform bool enableDiffuse;",
  15401. "uniform bool enableSpecular;",
  15402. "uniform bool enableAO;",
  15403. "uniform bool enableReflection;",
  15404. "uniform sampler2D tDiffuse;",
  15405. "uniform sampler2D tNormal;",
  15406. "uniform sampler2D tSpecular;",
  15407. "uniform sampler2D tAO;",
  15408. "uniform samplerCube tCube;",
  15409. "uniform vec2 uNormalScale;",
  15410. "uniform bool useRefract;",
  15411. "uniform float uRefractionRatio;",
  15412. "uniform float uReflectivity;",
  15413. "varying vec3 vTangent;",
  15414. "varying vec3 vBinormal;",
  15415. "varying vec3 vNormal;",
  15416. "varying vec2 vUv;",
  15417. "uniform vec3 ambientLightColor;",
  15418. "#if MAX_DIR_LIGHTS > 0",
  15419. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  15420. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  15421. "#endif",
  15422. "#if MAX_HEMI_LIGHTS > 0",
  15423. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  15424. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  15425. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  15426. "#endif",
  15427. "#if MAX_POINT_LIGHTS > 0",
  15428. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  15429. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  15430. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  15431. "#endif",
  15432. "#if MAX_SPOT_LIGHTS > 0",
  15433. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  15434. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  15435. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  15436. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  15437. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  15438. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  15439. "#endif",
  15440. "#ifdef WRAP_AROUND",
  15441. "uniform vec3 wrapRGB;",
  15442. "#endif",
  15443. "varying vec3 vWorldPosition;",
  15444. "varying vec3 vViewPosition;",
  15445. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  15446. THREE.ShaderChunk[ "fog_pars_fragment" ],
  15447. "void main() {",
  15448. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  15449. "vec3 specularTex = vec3( 1.0 );",
  15450. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  15451. "normalTex.xy *= uNormalScale;",
  15452. "normalTex = normalize( normalTex );",
  15453. "if( enableDiffuse ) {",
  15454. "#ifdef GAMMA_INPUT",
  15455. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  15456. "texelColor.xyz *= texelColor.xyz;",
  15457. "gl_FragColor = gl_FragColor * texelColor;",
  15458. "#else",
  15459. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  15460. "#endif",
  15461. "}",
  15462. "if( enableAO ) {",
  15463. "#ifdef GAMMA_INPUT",
  15464. "vec4 aoColor = texture2D( tAO, vUv );",
  15465. "aoColor.xyz *= aoColor.xyz;",
  15466. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  15467. "#else",
  15468. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  15469. "#endif",
  15470. "}",
  15471. "if( enableSpecular )",
  15472. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  15473. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  15474. "vec3 finalNormal = tsb * normalTex;",
  15475. "#ifdef FLIP_SIDED",
  15476. "finalNormal = -finalNormal;",
  15477. "#endif",
  15478. "vec3 normal = normalize( finalNormal );",
  15479. "vec3 viewPosition = normalize( vViewPosition );",
  15480. // point lights
  15481. "#if MAX_POINT_LIGHTS > 0",
  15482. "vec3 pointDiffuse = vec3( 0.0 );",
  15483. "vec3 pointSpecular = vec3( 0.0 );",
  15484. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  15485. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  15486. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  15487. "float pointDistance = 1.0;",
  15488. "if ( pointLightDistance[ i ] > 0.0 )",
  15489. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  15490. "pointVector = normalize( pointVector );",
  15491. // diffuse
  15492. "#ifdef WRAP_AROUND",
  15493. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  15494. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  15495. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  15496. "#else",
  15497. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  15498. "#endif",
  15499. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  15500. // specular
  15501. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  15502. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  15503. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  15504. "#ifdef PHYSICALLY_BASED_SHADING",
  15505. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15506. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15507. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  15508. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  15509. "#else",
  15510. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  15511. "#endif",
  15512. "}",
  15513. "#endif",
  15514. // spot lights
  15515. "#if MAX_SPOT_LIGHTS > 0",
  15516. "vec3 spotDiffuse = vec3( 0.0 );",
  15517. "vec3 spotSpecular = vec3( 0.0 );",
  15518. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  15519. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  15520. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  15521. "float spotDistance = 1.0;",
  15522. "if ( spotLightDistance[ i ] > 0.0 )",
  15523. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  15524. "spotVector = normalize( spotVector );",
  15525. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  15526. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  15527. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  15528. // diffuse
  15529. "#ifdef WRAP_AROUND",
  15530. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  15531. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  15532. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  15533. "#else",
  15534. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  15535. "#endif",
  15536. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  15537. // specular
  15538. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  15539. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  15540. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  15541. "#ifdef PHYSICALLY_BASED_SHADING",
  15542. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15543. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15544. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  15545. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  15546. "#else",
  15547. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  15548. "#endif",
  15549. "}",
  15550. "}",
  15551. "#endif",
  15552. // directional lights
  15553. "#if MAX_DIR_LIGHTS > 0",
  15554. "vec3 dirDiffuse = vec3( 0.0 );",
  15555. "vec3 dirSpecular = vec3( 0.0 );",
  15556. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  15557. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  15558. "vec3 dirVector = normalize( lDirection.xyz );",
  15559. // diffuse
  15560. "#ifdef WRAP_AROUND",
  15561. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  15562. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  15563. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  15564. "#else",
  15565. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  15566. "#endif",
  15567. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  15568. // specular
  15569. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  15570. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  15571. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  15572. "#ifdef PHYSICALLY_BASED_SHADING",
  15573. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15574. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15575. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  15576. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  15577. "#else",
  15578. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  15579. "#endif",
  15580. "}",
  15581. "#endif",
  15582. // hemisphere lights
  15583. "#if MAX_HEMI_LIGHTS > 0",
  15584. "vec3 hemiDiffuse = vec3( 0.0 );",
  15585. "vec3 hemiSpecular = vec3( 0.0 );" ,
  15586. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  15587. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  15588. "vec3 lVector = normalize( lDirection.xyz );",
  15589. // diffuse
  15590. "float dotProduct = dot( normal, lVector );",
  15591. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  15592. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  15593. "hemiDiffuse += uDiffuseColor * hemiColor;",
  15594. // specular (sky light)
  15595. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  15596. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  15597. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  15598. // specular (ground light)
  15599. "vec3 lVectorGround = -lVector;",
  15600. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  15601. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  15602. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  15603. "#ifdef PHYSICALLY_BASED_SHADING",
  15604. "float dotProductGround = dot( normal, lVectorGround );",
  15605. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15606. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15607. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  15608. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  15609. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  15610. "#else",
  15611. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  15612. "#endif",
  15613. "}",
  15614. "#endif",
  15615. // all lights contribution summation
  15616. "vec3 totalDiffuse = vec3( 0.0 );",
  15617. "vec3 totalSpecular = vec3( 0.0 );",
  15618. "#if MAX_DIR_LIGHTS > 0",
  15619. "totalDiffuse += dirDiffuse;",
  15620. "totalSpecular += dirSpecular;",
  15621. "#endif",
  15622. "#if MAX_HEMI_LIGHTS > 0",
  15623. "totalDiffuse += hemiDiffuse;",
  15624. "totalSpecular += hemiSpecular;",
  15625. "#endif",
  15626. "#if MAX_POINT_LIGHTS > 0",
  15627. "totalDiffuse += pointDiffuse;",
  15628. "totalSpecular += pointSpecular;",
  15629. "#endif",
  15630. "#if MAX_SPOT_LIGHTS > 0",
  15631. "totalDiffuse += spotDiffuse;",
  15632. "totalSpecular += spotSpecular;",
  15633. "#endif",
  15634. "#ifdef METAL",
  15635. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  15636. "#else",
  15637. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  15638. "#endif",
  15639. "if ( enableReflection ) {",
  15640. "vec3 vReflect;",
  15641. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  15642. "if ( useRefract ) {",
  15643. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  15644. "} else {",
  15645. "vReflect = reflect( cameraToVertex, normal );",
  15646. "}",
  15647. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  15648. "#ifdef GAMMA_INPUT",
  15649. "cubeColor.xyz *= cubeColor.xyz;",
  15650. "#endif",
  15651. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  15652. "}",
  15653. THREE.ShaderChunk[ "shadowmap_fragment" ],
  15654. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  15655. THREE.ShaderChunk[ "fog_fragment" ],
  15656. "}"
  15657. ].join("\n"),
  15658. vertexShader: [
  15659. "attribute vec4 tangent;",
  15660. "uniform vec2 uOffset;",
  15661. "uniform vec2 uRepeat;",
  15662. "uniform bool enableDisplacement;",
  15663. "#ifdef VERTEX_TEXTURES",
  15664. "uniform sampler2D tDisplacement;",
  15665. "uniform float uDisplacementScale;",
  15666. "uniform float uDisplacementBias;",
  15667. "#endif",
  15668. "varying vec3 vTangent;",
  15669. "varying vec3 vBinormal;",
  15670. "varying vec3 vNormal;",
  15671. "varying vec2 vUv;",
  15672. "varying vec3 vWorldPosition;",
  15673. "varying vec3 vViewPosition;",
  15674. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  15675. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  15676. "void main() {",
  15677. THREE.ShaderChunk[ "skinbase_vertex" ],
  15678. THREE.ShaderChunk[ "skinnormal_vertex" ],
  15679. // normal, tangent and binormal vectors
  15680. "#ifdef USE_SKINNING",
  15681. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  15682. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  15683. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  15684. "#else",
  15685. "vNormal = normalize( normalMatrix * normal );",
  15686. "vTangent = normalize( normalMatrix * tangent.xyz );",
  15687. "#endif",
  15688. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  15689. "vUv = uv * uRepeat + uOffset;",
  15690. // displacement mapping
  15691. "vec3 displacedPosition;",
  15692. "#ifdef VERTEX_TEXTURES",
  15693. "if ( enableDisplacement ) {",
  15694. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  15695. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  15696. "displacedPosition = position + normalize( normal ) * df;",
  15697. "} else {",
  15698. "#ifdef USE_SKINNING",
  15699. "vec4 skinVertex = vec4( position, 1.0 );",
  15700. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  15701. "skinned += boneMatY * skinVertex * skinWeight.y;",
  15702. "displacedPosition = skinned.xyz;",
  15703. "#else",
  15704. "displacedPosition = position;",
  15705. "#endif",
  15706. "}",
  15707. "#else",
  15708. "#ifdef USE_SKINNING",
  15709. "vec4 skinVertex = vec4( position, 1.0 );",
  15710. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  15711. "skinned += boneMatY * skinVertex * skinWeight.y;",
  15712. "displacedPosition = skinned.xyz;",
  15713. "#else",
  15714. "displacedPosition = position;",
  15715. "#endif",
  15716. "#endif",
  15717. //
  15718. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  15719. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  15720. "gl_Position = projectionMatrix * mvPosition;",
  15721. //
  15722. "vWorldPosition = worldPosition.xyz;",
  15723. "vViewPosition = -mvPosition.xyz;",
  15724. // shadows
  15725. "#ifdef USE_SHADOWMAP",
  15726. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  15727. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  15728. "}",
  15729. "#endif",
  15730. "}"
  15731. ].join("\n")
  15732. },
  15733. /* -------------------------------------------------------------------------
  15734. // Cube map shader
  15735. ------------------------------------------------------------------------- */
  15736. 'cube': {
  15737. uniforms: { "tCube": { type: "t", value: null },
  15738. "tFlip": { type: "f", value: -1 } },
  15739. vertexShader: [
  15740. "varying vec3 vWorldPosition;",
  15741. "void main() {",
  15742. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  15743. "vWorldPosition = worldPosition.xyz;",
  15744. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  15745. "}"
  15746. ].join("\n"),
  15747. fragmentShader: [
  15748. "uniform samplerCube tCube;",
  15749. "uniform float tFlip;",
  15750. "varying vec3 vWorldPosition;",
  15751. "void main() {",
  15752. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  15753. "}"
  15754. ].join("\n")
  15755. }
  15756. }
  15757. };
  15758. /**
  15759. * @author zz85 / http://www.lab4games.net/zz85/blog
  15760. * @author alteredq / http://alteredqualia.com/
  15761. *
  15762. * For Text operations in three.js (See TextGeometry)
  15763. *
  15764. * It uses techniques used in:
  15765. *
  15766. * typeface.js and canvastext
  15767. * For converting fonts and rendering with javascript
  15768. * http://typeface.neocracy.org
  15769. *
  15770. * Triangulation ported from AS3
  15771. * Simple Polygon Triangulation
  15772. * http://actionsnippet.com/?p=1462
  15773. *
  15774. * A Method to triangulate shapes with holes
  15775. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  15776. *
  15777. */
  15778. THREE.FontUtils = {
  15779. faces : {},
  15780. // Just for now. face[weight][style]
  15781. face : "helvetiker",
  15782. weight: "normal",
  15783. style : "normal",
  15784. size : 150,
  15785. divisions : 10,
  15786. getFace : function() {
  15787. return this.faces[ this.face ][ this.weight ][ this.style ];
  15788. },
  15789. loadFace : function( data ) {
  15790. var family = data.familyName.toLowerCase();
  15791. var ThreeFont = this;
  15792. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  15793. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  15794. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15795. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15796. return data;
  15797. },
  15798. drawText : function( text ) {
  15799. var characterPts = [], allPts = [];
  15800. // RenderText
  15801. var i, p,
  15802. face = this.getFace(),
  15803. scale = this.size / face.resolution,
  15804. offset = 0,
  15805. chars = String( text ).split( '' ),
  15806. length = chars.length;
  15807. var fontPaths = [];
  15808. for ( i = 0; i < length; i ++ ) {
  15809. var path = new THREE.Path();
  15810. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  15811. offset += ret.offset;
  15812. fontPaths.push( ret.path );
  15813. }
  15814. // get the width
  15815. var width = offset / 2;
  15816. //
  15817. // for ( p = 0; p < allPts.length; p++ ) {
  15818. //
  15819. // allPts[ p ].x -= width;
  15820. //
  15821. // }
  15822. //var extract = this.extractPoints( allPts, characterPts );
  15823. //extract.contour = allPts;
  15824. //extract.paths = fontPaths;
  15825. //extract.offset = width;
  15826. return { paths : fontPaths, offset : width };
  15827. },
  15828. extractGlyphPoints : function( c, face, scale, offset, path ) {
  15829. var pts = [];
  15830. var i, i2, divisions,
  15831. outline, action, length,
  15832. scaleX, scaleY,
  15833. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  15834. laste,
  15835. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  15836. if ( !glyph ) return;
  15837. if ( glyph.o ) {
  15838. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  15839. length = outline.length;
  15840. scaleX = scale;
  15841. scaleY = scale;
  15842. for ( i = 0; i < length; ) {
  15843. action = outline[ i ++ ];
  15844. //console.log( action );
  15845. switch( action ) {
  15846. case 'm':
  15847. // Move To
  15848. x = outline[ i++ ] * scaleX + offset;
  15849. y = outline[ i++ ] * scaleY;
  15850. path.moveTo( x, y );
  15851. break;
  15852. case 'l':
  15853. // Line To
  15854. x = outline[ i++ ] * scaleX + offset;
  15855. y = outline[ i++ ] * scaleY;
  15856. path.lineTo(x,y);
  15857. break;
  15858. case 'q':
  15859. // QuadraticCurveTo
  15860. cpx = outline[ i++ ] * scaleX + offset;
  15861. cpy = outline[ i++ ] * scaleY;
  15862. cpx1 = outline[ i++ ] * scaleX + offset;
  15863. cpy1 = outline[ i++ ] * scaleY;
  15864. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  15865. laste = pts[ pts.length - 1 ];
  15866. if ( laste ) {
  15867. cpx0 = laste.x;
  15868. cpy0 = laste.y;
  15869. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15870. var t = i2 / divisions;
  15871. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  15872. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  15873. }
  15874. }
  15875. break;
  15876. case 'b':
  15877. // Cubic Bezier Curve
  15878. cpx = outline[ i++ ] * scaleX + offset;
  15879. cpy = outline[ i++ ] * scaleY;
  15880. cpx1 = outline[ i++ ] * scaleX + offset;
  15881. cpy1 = outline[ i++ ] * -scaleY;
  15882. cpx2 = outline[ i++ ] * scaleX + offset;
  15883. cpy2 = outline[ i++ ] * -scaleY;
  15884. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  15885. laste = pts[ pts.length - 1 ];
  15886. if ( laste ) {
  15887. cpx0 = laste.x;
  15888. cpy0 = laste.y;
  15889. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15890. var t = i2 / divisions;
  15891. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  15892. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  15893. }
  15894. }
  15895. break;
  15896. }
  15897. }
  15898. }
  15899. return { offset: glyph.ha*scale, path:path};
  15900. }
  15901. };
  15902. THREE.FontUtils.generateShapes = function( text, parameters ) {
  15903. // Parameters
  15904. parameters = parameters || {};
  15905. var size = parameters.size !== undefined ? parameters.size : 100;
  15906. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  15907. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  15908. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  15909. var style = parameters.style !== undefined ? parameters.style : "normal";
  15910. THREE.FontUtils.size = size;
  15911. THREE.FontUtils.divisions = curveSegments;
  15912. THREE.FontUtils.face = font;
  15913. THREE.FontUtils.weight = weight;
  15914. THREE.FontUtils.style = style;
  15915. // Get a Font data json object
  15916. var data = THREE.FontUtils.drawText( text );
  15917. var paths = data.paths;
  15918. var shapes = [];
  15919. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  15920. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  15921. }
  15922. return shapes;
  15923. };
  15924. /**
  15925. * This code is a quick port of code written in C++ which was submitted to
  15926. * flipcode.com by John W. Ratcliff // July 22, 2000
  15927. * See original code and more information here:
  15928. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  15929. *
  15930. * ported to actionscript by Zevan Rosser
  15931. * www.actionsnippet.com
  15932. *
  15933. * ported to javascript by Joshua Koo
  15934. * http://www.lab4games.net/zz85/blog
  15935. *
  15936. */
  15937. ( function( namespace ) {
  15938. var EPSILON = 0.0000000001;
  15939. // takes in an contour array and returns
  15940. var process = function( contour, indices ) {
  15941. var n = contour.length;
  15942. if ( n < 3 ) return null;
  15943. var result = [],
  15944. verts = [],
  15945. vertIndices = [];
  15946. /* we want a counter-clockwise polygon in verts */
  15947. var u, v, w;
  15948. if ( area( contour ) > 0.0 ) {
  15949. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  15950. } else {
  15951. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  15952. }
  15953. var nv = n;
  15954. /* remove nv - 2 vertices, creating 1 triangle every time */
  15955. var count = 2 * nv; /* error detection */
  15956. for( v = nv - 1; nv > 2; ) {
  15957. /* if we loop, it is probably a non-simple polygon */
  15958. if ( ( count-- ) <= 0 ) {
  15959. //** Triangulate: ERROR - probable bad polygon!
  15960. //throw ( "Warning, unable to triangulate polygon!" );
  15961. //return null;
  15962. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  15963. console.log( "Warning, unable to triangulate polygon!" );
  15964. if ( indices ) return vertIndices;
  15965. return result;
  15966. }
  15967. /* three consecutive vertices in current polygon, <u,v,w> */
  15968. u = v; if ( nv <= u ) u = 0; /* previous */
  15969. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  15970. w = v + 1; if ( nv <= w ) w = 0; /* next */
  15971. if ( snip( contour, u, v, w, nv, verts ) ) {
  15972. var a, b, c, s, t;
  15973. /* true names of the vertices */
  15974. a = verts[ u ];
  15975. b = verts[ v ];
  15976. c = verts[ w ];
  15977. /* output Triangle */
  15978. result.push( [ contour[ a ],
  15979. contour[ b ],
  15980. contour[ c ] ] );
  15981. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  15982. /* remove v from the remaining polygon */
  15983. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  15984. verts[ s ] = verts[ t ];
  15985. }
  15986. nv--;
  15987. /* reset error detection counter */
  15988. count = 2 * nv;
  15989. }
  15990. }
  15991. if ( indices ) return vertIndices;
  15992. return result;
  15993. };
  15994. // calculate area of the contour polygon
  15995. var area = function ( contour ) {
  15996. var n = contour.length;
  15997. var a = 0.0;
  15998. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  15999. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16000. }
  16001. return a * 0.5;
  16002. };
  16003. var snip = function ( contour, u, v, w, n, verts ) {
  16004. var p;
  16005. var ax, ay, bx, by;
  16006. var cx, cy, px, py;
  16007. ax = contour[ verts[ u ] ].x;
  16008. ay = contour[ verts[ u ] ].y;
  16009. bx = contour[ verts[ v ] ].x;
  16010. by = contour[ verts[ v ] ].y;
  16011. cx = contour[ verts[ w ] ].x;
  16012. cy = contour[ verts[ w ] ].y;
  16013. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16014. var aX, aY, bX, bY, cX, cY;
  16015. var apx, apy, bpx, bpy, cpx, cpy;
  16016. var cCROSSap, bCROSScp, aCROSSbp;
  16017. aX = cx - bx; aY = cy - by;
  16018. bX = ax - cx; bY = ay - cy;
  16019. cX = bx - ax; cY = by - ay;
  16020. for ( p = 0; p < n; p++ ) {
  16021. if( (p === u) || (p === v) || (p === w) ) continue;
  16022. px = contour[ verts[ p ] ].x
  16023. py = contour[ verts[ p ] ].y
  16024. apx = px - ax; apy = py - ay;
  16025. bpx = px - bx; bpy = py - by;
  16026. cpx = px - cx; cpy = py - cy;
  16027. // see if p is inside triangle abc
  16028. aCROSSbp = aX*bpy - aY*bpx;
  16029. cCROSSap = cX*apy - cY*apx;
  16030. bCROSScp = bX*cpy - bY*cpx;
  16031. if ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) ) return false;
  16032. }
  16033. return true;
  16034. };
  16035. namespace.Triangulate = process;
  16036. namespace.Triangulate.area = area;
  16037. return namespace;
  16038. })(THREE.FontUtils);
  16039. // To use the typeface.js face files, hook up the API
  16040. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };/**
  16041. * @author zz85 / http://www.lab4games.net/zz85/blog
  16042. * Extensible curve object
  16043. *
  16044. * Some common of Curve methods
  16045. * .getPoint(t), getTangent(t)
  16046. * .getPointAt(u), getTagentAt(u)
  16047. * .getPoints(), .getSpacedPoints()
  16048. * .getLength()
  16049. * .updateArcLengths()
  16050. *
  16051. * This file contains following classes:
  16052. *
  16053. * -- 2d classes --
  16054. * THREE.Curve
  16055. * THREE.LineCurve
  16056. * THREE.QuadraticBezierCurve
  16057. * THREE.CubicBezierCurve
  16058. * THREE.SplineCurve
  16059. * THREE.ArcCurve
  16060. * THREE.EllipseCurve
  16061. *
  16062. * -- 3d classes --
  16063. * THREE.LineCurve3
  16064. * THREE.QuadraticBezierCurve3
  16065. * THREE.CubicBezierCurve3
  16066. * THREE.SplineCurve3
  16067. * THREE.ClosedSplineCurve3
  16068. *
  16069. * A series of curves can be represented as a THREE.CurvePath
  16070. *
  16071. **/
  16072. /**************************************************************
  16073. * Abstract Curve base class
  16074. **************************************************************/
  16075. THREE.Curve = function () {
  16076. };
  16077. // Virtual base class method to overwrite and implement in subclasses
  16078. // - t [0 .. 1]
  16079. THREE.Curve.prototype.getPoint = function ( t ) {
  16080. console.log( "Warning, getPoint() not implemented!" );
  16081. return null;
  16082. };
  16083. // Get point at relative position in curve according to arc length
  16084. // - u [0 .. 1]
  16085. THREE.Curve.prototype.getPointAt = function ( u ) {
  16086. var t = this.getUtoTmapping( u );
  16087. return this.getPoint( t );
  16088. };
  16089. // Get sequence of points using getPoint( t )
  16090. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16091. if ( !divisions ) divisions = 5;
  16092. var d, pts = [];
  16093. for ( d = 0; d <= divisions; d ++ ) {
  16094. pts.push( this.getPoint( d / divisions ) );
  16095. }
  16096. return pts;
  16097. };
  16098. // Get sequence of points using getPointAt( u )
  16099. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16100. if ( !divisions ) divisions = 5;
  16101. var d, pts = [];
  16102. for ( d = 0; d <= divisions; d ++ ) {
  16103. pts.push( this.getPointAt( d / divisions ) );
  16104. }
  16105. return pts;
  16106. };
  16107. // Get total curve arc length
  16108. THREE.Curve.prototype.getLength = function () {
  16109. var lengths = this.getLengths();
  16110. return lengths[ lengths.length - 1 ];
  16111. };
  16112. // Get list of cumulative segment lengths
  16113. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16114. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16115. if ( this.cacheArcLengths
  16116. && ( this.cacheArcLengths.length == divisions + 1 )
  16117. && !this.needsUpdate) {
  16118. //console.log( "cached", this.cacheArcLengths );
  16119. return this.cacheArcLengths;
  16120. }
  16121. this.needsUpdate = false;
  16122. var cache = [];
  16123. var current, last = this.getPoint( 0 );
  16124. var p, sum = 0;
  16125. cache.push( 0 );
  16126. for ( p = 1; p <= divisions; p ++ ) {
  16127. current = this.getPoint ( p / divisions );
  16128. sum += current.distanceTo( last );
  16129. cache.push( sum );
  16130. last = current;
  16131. }
  16132. this.cacheArcLengths = cache;
  16133. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16134. };
  16135. THREE.Curve.prototype.updateArcLengths = function() {
  16136. this.needsUpdate = true;
  16137. this.getLengths();
  16138. };
  16139. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16140. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16141. var arcLengths = this.getLengths();
  16142. var i = 0, il = arcLengths.length;
  16143. var targetArcLength; // The targeted u distance value to get
  16144. if ( distance ) {
  16145. targetArcLength = distance;
  16146. } else {
  16147. targetArcLength = u * arcLengths[ il - 1 ];
  16148. }
  16149. //var time = Date.now();
  16150. // binary search for the index with largest value smaller than target u distance
  16151. var low = 0, high = il - 1, comparison;
  16152. while ( low <= high ) {
  16153. 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
  16154. comparison = arcLengths[ i ] - targetArcLength;
  16155. if ( comparison < 0 ) {
  16156. low = i + 1;
  16157. continue;
  16158. } else if ( comparison > 0 ) {
  16159. high = i - 1;
  16160. continue;
  16161. } else {
  16162. high = i;
  16163. break;
  16164. // DONE
  16165. }
  16166. }
  16167. i = high;
  16168. //console.log('b' , i, low, high, Date.now()- time);
  16169. if ( arcLengths[ i ] == targetArcLength ) {
  16170. var t = i / ( il - 1 );
  16171. return t;
  16172. }
  16173. // we could get finer grain at lengths, or use simple interpolatation between two points
  16174. var lengthBefore = arcLengths[ i ];
  16175. var lengthAfter = arcLengths[ i + 1 ];
  16176. var segmentLength = lengthAfter - lengthBefore;
  16177. // determine where we are between the 'before' and 'after' points
  16178. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16179. // add that fractional amount to t
  16180. var t = ( i + segmentFraction ) / ( il -1 );
  16181. return t;
  16182. };
  16183. // Returns a unit vector tangent at t
  16184. // In case any sub curve does not implement its tangent derivation,
  16185. // 2 points a small delta apart will be used to find its gradient
  16186. // which seems to give a reasonable approximation
  16187. THREE.Curve.prototype.getTangent = function( t ) {
  16188. var delta = 0.0001;
  16189. var t1 = t - delta;
  16190. var t2 = t + delta;
  16191. // Capping in case of danger
  16192. if ( t1 < 0 ) t1 = 0;
  16193. if ( t2 > 1 ) t2 = 1;
  16194. var pt1 = this.getPoint( t1 );
  16195. var pt2 = this.getPoint( t2 );
  16196. var vec = pt2.clone().sub(pt1);
  16197. return vec.normalize();
  16198. };
  16199. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16200. var t = this.getUtoTmapping( u );
  16201. return this.getTangent( t );
  16202. };
  16203. /**************************************************************
  16204. * Line
  16205. **************************************************************/
  16206. THREE.LineCurve = function ( v1, v2 ) {
  16207. this.v1 = v1;
  16208. this.v2 = v2;
  16209. };
  16210. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  16211. THREE.LineCurve.prototype.getPoint = function ( t ) {
  16212. var point = this.v2.clone().sub(this.v1);
  16213. point.multiplyScalar( t ).add( this.v1 );
  16214. return point;
  16215. };
  16216. // Line curve is linear, so we can overwrite default getPointAt
  16217. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  16218. return this.getPoint( u );
  16219. };
  16220. THREE.LineCurve.prototype.getTangent = function( t ) {
  16221. var tangent = this.v2.clone().sub(this.v1);
  16222. return tangent.normalize();
  16223. };
  16224. /**************************************************************
  16225. * Quadratic Bezier curve
  16226. **************************************************************/
  16227. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  16228. this.v0 = v0;
  16229. this.v1 = v1;
  16230. this.v2 = v2;
  16231. };
  16232. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  16233. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  16234. var tx, ty;
  16235. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  16236. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  16237. return new THREE.Vector2( tx, ty );
  16238. };
  16239. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  16240. var tx, ty;
  16241. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  16242. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  16243. // returns unit vector
  16244. var tangent = new THREE.Vector2( tx, ty );
  16245. tangent.normalize();
  16246. return tangent;
  16247. };
  16248. /**************************************************************
  16249. * Cubic Bezier curve
  16250. **************************************************************/
  16251. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  16252. this.v0 = v0;
  16253. this.v1 = v1;
  16254. this.v2 = v2;
  16255. this.v3 = v3;
  16256. };
  16257. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  16258. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  16259. var tx, ty;
  16260. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16261. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16262. return new THREE.Vector2( tx, ty );
  16263. };
  16264. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  16265. var tx, ty;
  16266. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16267. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16268. var tangent = new THREE.Vector2( tx, ty );
  16269. tangent.normalize();
  16270. return tangent;
  16271. };
  16272. /**************************************************************
  16273. * Spline curve
  16274. **************************************************************/
  16275. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  16276. this.points = (points == undefined) ? [] : points;
  16277. };
  16278. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  16279. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  16280. var v = new THREE.Vector2();
  16281. var c = [];
  16282. var points = this.points, point, intPoint, weight;
  16283. point = ( points.length - 1 ) * t;
  16284. intPoint = Math.floor( point );
  16285. weight = point - intPoint;
  16286. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16287. c[ 1 ] = intPoint;
  16288. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  16289. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  16290. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16291. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16292. return v;
  16293. };
  16294. /**************************************************************
  16295. * Ellipse curve
  16296. **************************************************************/
  16297. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  16298. aStartAngle, aEndAngle,
  16299. aClockwise ) {
  16300. this.aX = aX;
  16301. this.aY = aY;
  16302. this.xRadius = xRadius;
  16303. this.yRadius = yRadius;
  16304. this.aStartAngle = aStartAngle;
  16305. this.aEndAngle = aEndAngle;
  16306. this.aClockwise = aClockwise;
  16307. };
  16308. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  16309. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  16310. var deltaAngle = this.aEndAngle - this.aStartAngle;
  16311. if ( !this.aClockwise ) {
  16312. t = 1 - t;
  16313. }
  16314. var angle = this.aStartAngle + t * deltaAngle;
  16315. var tx = this.aX + this.xRadius * Math.cos( angle );
  16316. var ty = this.aY + this.yRadius * Math.sin( angle );
  16317. return new THREE.Vector2( tx, ty );
  16318. };
  16319. /**************************************************************
  16320. * Arc curve
  16321. **************************************************************/
  16322. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  16323. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  16324. };
  16325. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  16326. /**************************************************************
  16327. * Utils
  16328. **************************************************************/
  16329. THREE.Curve.Utils = {
  16330. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16331. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16332. },
  16333. // Puay Bing, thanks for helping with this derivative!
  16334. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16335. return -3 * p0 * (1 - t) * (1 - t) +
  16336. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  16337. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  16338. 3 * t * t * p3;
  16339. },
  16340. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16341. // To check if my formulas are correct
  16342. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16343. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16344. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  16345. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16346. return h00 + h10 + h01 + h11;
  16347. },
  16348. // Catmull-Rom
  16349. interpolate: function( p0, p1, p2, p3, t ) {
  16350. var v0 = ( p2 - p0 ) * 0.5;
  16351. var v1 = ( p3 - p1 ) * 0.5;
  16352. var t2 = t * t;
  16353. var t3 = t * t2;
  16354. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16355. }
  16356. };
  16357. // TODO: Transformation for Curves?
  16358. /**************************************************************
  16359. * 3D Curves
  16360. **************************************************************/
  16361. // A Factory method for creating new curve subclasses
  16362. THREE.Curve.create = function ( constructor, getPointFunc ) {
  16363. constructor.prototype = Object.create( THREE.Curve.prototype );
  16364. constructor.prototype.getPoint = getPointFunc;
  16365. return constructor;
  16366. };
  16367. /**************************************************************
  16368. * Line3D
  16369. **************************************************************/
  16370. THREE.LineCurve3 = THREE.Curve.create(
  16371. function ( v1, v2 ) {
  16372. this.v1 = v1;
  16373. this.v2 = v2;
  16374. },
  16375. function ( t ) {
  16376. var r = new THREE.Vector3();
  16377. r.subVectors( this.v2, this.v1 ); // diff
  16378. r.multiplyScalar( t );
  16379. r.add( this.v1 );
  16380. return r;
  16381. }
  16382. );
  16383. /**************************************************************
  16384. * Quadratic Bezier 3D curve
  16385. **************************************************************/
  16386. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  16387. function ( v0, v1, v2 ) {
  16388. this.v0 = v0;
  16389. this.v1 = v1;
  16390. this.v2 = v2;
  16391. },
  16392. function ( t ) {
  16393. var tx, ty, tz;
  16394. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  16395. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  16396. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  16397. return new THREE.Vector3( tx, ty, tz );
  16398. }
  16399. );
  16400. /**************************************************************
  16401. * Cubic Bezier 3D curve
  16402. **************************************************************/
  16403. THREE.CubicBezierCurve3 = THREE.Curve.create(
  16404. function ( v0, v1, v2, v3 ) {
  16405. this.v0 = v0;
  16406. this.v1 = v1;
  16407. this.v2 = v2;
  16408. this.v3 = v3;
  16409. },
  16410. function ( t ) {
  16411. var tx, ty, tz;
  16412. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16413. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16414. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  16415. return new THREE.Vector3( tx, ty, tz );
  16416. }
  16417. );
  16418. /**************************************************************
  16419. * Spline 3D curve
  16420. **************************************************************/
  16421. THREE.SplineCurve3 = THREE.Curve.create(
  16422. function ( points /* array of Vector3 */) {
  16423. this.points = (points == undefined) ? [] : points;
  16424. },
  16425. function ( t ) {
  16426. var v = new THREE.Vector3();
  16427. var c = [];
  16428. var points = this.points, point, intPoint, weight;
  16429. point = ( points.length - 1 ) * t;
  16430. intPoint = Math.floor( point );
  16431. weight = point - intPoint;
  16432. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16433. c[ 1 ] = intPoint;
  16434. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16435. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16436. var pt0 = points[ c[0] ],
  16437. pt1 = points[ c[1] ],
  16438. pt2 = points[ c[2] ],
  16439. pt3 = points[ c[3] ];
  16440. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  16441. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  16442. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  16443. return v;
  16444. }
  16445. );
  16446. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  16447. // var v = new THREE.Vector3();
  16448. // var c = [];
  16449. // var points = this.points, point, intPoint, weight;
  16450. // point = ( points.length - 1 ) * t;
  16451. // intPoint = Math.floor( point );
  16452. // weight = point - intPoint;
  16453. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16454. // c[ 1 ] = intPoint;
  16455. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16456. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16457. // var pt0 = points[ c[0] ],
  16458. // pt1 = points[ c[1] ],
  16459. // pt2 = points[ c[2] ],
  16460. // pt3 = points[ c[3] ];
  16461. // // t = weight;
  16462. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  16463. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  16464. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  16465. // return v;
  16466. // }
  16467. /**************************************************************
  16468. * Closed Spline 3D curve
  16469. **************************************************************/
  16470. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  16471. function ( points /* array of Vector3 */) {
  16472. this.points = (points == undefined) ? [] : points;
  16473. },
  16474. function ( t ) {
  16475. var v = new THREE.Vector3();
  16476. var c = [];
  16477. var points = this.points, point, intPoint, weight;
  16478. point = ( points.length - 0 ) * t;
  16479. // This needs to be from 0-length +1
  16480. intPoint = Math.floor( point );
  16481. weight = point - intPoint;
  16482. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  16483. c[ 0 ] = ( intPoint - 1 ) % points.length;
  16484. c[ 1 ] = ( intPoint ) % points.length;
  16485. c[ 2 ] = ( intPoint + 1 ) % points.length;
  16486. c[ 3 ] = ( intPoint + 2 ) % points.length;
  16487. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16488. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16489. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  16490. return v;
  16491. }
  16492. );
  16493. /**
  16494. * @author zz85 / http://www.lab4games.net/zz85/blog
  16495. *
  16496. **/
  16497. /**************************************************************
  16498. * Curved Path - a curve path is simply a array of connected
  16499. * curves, but retains the api of a curve
  16500. **************************************************************/
  16501. THREE.CurvePath = function () {
  16502. this.curves = [];
  16503. this.bends = [];
  16504. this.autoClose = false; // Automatically closes the path
  16505. };
  16506. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16507. THREE.CurvePath.prototype.add = function ( curve ) {
  16508. this.curves.push( curve );
  16509. };
  16510. THREE.CurvePath.prototype.checkConnection = function() {
  16511. // TODO
  16512. // If the ending of curve is not connected to the starting
  16513. // or the next curve, then, this is not a real path
  16514. };
  16515. THREE.CurvePath.prototype.closePath = function() {
  16516. // TODO Test
  16517. // and verify for vector3 (needs to implement equals)
  16518. // Add a line curve if start and end of lines are not connected
  16519. var startPoint = this.curves[0].getPoint(0);
  16520. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  16521. if (!startPoint.equals(endPoint)) {
  16522. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16523. }
  16524. };
  16525. // To get accurate point with reference to
  16526. // entire path distance at time t,
  16527. // following has to be done:
  16528. // 1. Length of each sub path have to be known
  16529. // 2. Locate and identify type of curve
  16530. // 3. Get t for the curve
  16531. // 4. Return curve.getPointAt(t')
  16532. THREE.CurvePath.prototype.getPoint = function( t ) {
  16533. var d = t * this.getLength();
  16534. var curveLengths = this.getCurveLengths();
  16535. var i = 0, diff, curve;
  16536. // To think about boundaries points.
  16537. while ( i < curveLengths.length ) {
  16538. if ( curveLengths[ i ] >= d ) {
  16539. diff = curveLengths[ i ] - d;
  16540. curve = this.curves[ i ];
  16541. var u = 1 - diff / curve.getLength();
  16542. return curve.getPointAt( u );
  16543. break;
  16544. }
  16545. i ++;
  16546. }
  16547. return null;
  16548. // loop where sum != 0, sum > d , sum+1 <d
  16549. };
  16550. /*
  16551. THREE.CurvePath.prototype.getTangent = function( t ) {
  16552. };*/
  16553. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16554. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16555. // getPoint() depends on getLength
  16556. THREE.CurvePath.prototype.getLength = function() {
  16557. var lens = this.getCurveLengths();
  16558. return lens[ lens.length - 1 ];
  16559. };
  16560. // Compute lengths and cache them
  16561. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16562. THREE.CurvePath.prototype.getCurveLengths = function() {
  16563. // We use cache values if curves and cache array are same length
  16564. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16565. return this.cacheLengths;
  16566. };
  16567. // Get length of subsurve
  16568. // Push sums into cached array
  16569. var lengths = [], sums = 0;
  16570. var i, il = this.curves.length;
  16571. for ( i = 0; i < il; i ++ ) {
  16572. sums += this.curves[ i ].getLength();
  16573. lengths.push( sums );
  16574. }
  16575. this.cacheLengths = lengths;
  16576. return lengths;
  16577. };
  16578. // Returns min and max coordinates, as well as centroid
  16579. THREE.CurvePath.prototype.getBoundingBox = function () {
  16580. var points = this.getPoints();
  16581. var maxX, maxY, maxZ;
  16582. var minX, minY, minZ;
  16583. maxX = maxY = Number.NEGATIVE_INFINITY;
  16584. minX = minY = Number.POSITIVE_INFINITY;
  16585. var p, i, il, sum;
  16586. var v3 = points[0] instanceof THREE.Vector3;
  16587. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16588. for ( i = 0, il = points.length; i < il; i ++ ) {
  16589. p = points[ i ];
  16590. if ( p.x > maxX ) maxX = p.x;
  16591. else if ( p.x < minX ) minX = p.x;
  16592. if ( p.y > maxY ) maxY = p.y;
  16593. else if ( p.y < minY ) minY = p.y;
  16594. if ( v3 ) {
  16595. if ( p.z > maxZ ) maxZ = p.z;
  16596. else if ( p.z < minZ ) minZ = p.z;
  16597. }
  16598. sum.add( p );
  16599. }
  16600. var ret = {
  16601. minX: minX,
  16602. minY: minY,
  16603. maxX: maxX,
  16604. maxY: maxY,
  16605. centroid: sum.divideScalar( il )
  16606. };
  16607. if ( v3 ) {
  16608. ret.maxZ = maxZ;
  16609. ret.minZ = minZ;
  16610. }
  16611. return ret;
  16612. };
  16613. /**************************************************************
  16614. * Create Geometries Helpers
  16615. **************************************************************/
  16616. /// Generate geometry from path points (for Line or ParticleSystem objects)
  16617. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16618. var pts = this.getPoints( divisions, true );
  16619. return this.createGeometry( pts );
  16620. };
  16621. // Generate geometry from equidistance sampling along the path
  16622. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16623. var pts = this.getSpacedPoints( divisions, true );
  16624. return this.createGeometry( pts );
  16625. };
  16626. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16627. var geometry = new THREE.Geometry();
  16628. for ( var i = 0; i < points.length; i ++ ) {
  16629. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16630. }
  16631. return geometry;
  16632. };
  16633. /**************************************************************
  16634. * Bend / Wrap Helper Methods
  16635. **************************************************************/
  16636. // Wrap path / Bend modifiers?
  16637. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16638. this.bends.push( bendpath );
  16639. };
  16640. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  16641. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  16642. var i, il;
  16643. if ( !bends ) {
  16644. bends = this.bends;
  16645. }
  16646. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16647. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16648. }
  16649. return oldPts;
  16650. };
  16651. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  16652. var oldPts = this.getSpacedPoints( segments );
  16653. var i, il;
  16654. if ( !bends ) {
  16655. bends = this.bends;
  16656. }
  16657. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16658. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16659. }
  16660. return oldPts;
  16661. };
  16662. // This returns getPoints() bend/wrapped around the contour of a path.
  16663. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  16664. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  16665. var bounds = this.getBoundingBox();
  16666. var i, il, p, oldX, oldY, xNorm;
  16667. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  16668. p = oldPts[ i ];
  16669. oldX = p.x;
  16670. oldY = p.y;
  16671. xNorm = oldX / bounds.maxX;
  16672. // If using actual distance, for length > path, requires line extrusions
  16673. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  16674. xNorm = path.getUtoTmapping( xNorm, oldX );
  16675. // check for out of bounds?
  16676. var pathPt = path.getPoint( xNorm );
  16677. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  16678. p.x = pathPt.x + normal.x;
  16679. p.y = pathPt.y + normal.y;
  16680. }
  16681. return oldPts;
  16682. };
  16683. /**
  16684. * @author alteredq / http://alteredqualia.com/
  16685. */
  16686. THREE.Gyroscope = function () {
  16687. THREE.Object3D.call( this );
  16688. };
  16689. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  16690. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  16691. this.matrixAutoUpdate && this.updateMatrix();
  16692. // update matrixWorld
  16693. if ( this.matrixWorldNeedsUpdate || force ) {
  16694. if ( this.parent ) {
  16695. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  16696. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  16697. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  16698. this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
  16699. } else {
  16700. this.matrixWorld.copy( this.matrix );
  16701. }
  16702. this.matrixWorldNeedsUpdate = false;
  16703. force = true;
  16704. }
  16705. // update children
  16706. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  16707. this.children[ i ].updateMatrixWorld( force );
  16708. }
  16709. };
  16710. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  16711. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  16712. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  16713. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  16714. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  16715. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  16716. /**
  16717. * @author zz85 / http://www.lab4games.net/zz85/blog
  16718. * Creates free form 2d path using series of points, lines or curves.
  16719. *
  16720. **/
  16721. THREE.Path = function ( points ) {
  16722. THREE.CurvePath.call(this);
  16723. this.actions = [];
  16724. if ( points ) {
  16725. this.fromPoints( points );
  16726. }
  16727. };
  16728. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16729. THREE.PathActions = {
  16730. MOVE_TO: 'moveTo',
  16731. LINE_TO: 'lineTo',
  16732. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  16733. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  16734. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  16735. ARC: 'arc', // Circle
  16736. ELLIPSE: 'ellipse'
  16737. };
  16738. // TODO Clean up PATH API
  16739. // Create path using straight lines to connect all points
  16740. // - vectors: array of Vector2
  16741. THREE.Path.prototype.fromPoints = function ( vectors ) {
  16742. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  16743. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  16744. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  16745. };
  16746. };
  16747. // startPath() endPath()?
  16748. THREE.Path.prototype.moveTo = function ( x, y ) {
  16749. var args = Array.prototype.slice.call( arguments );
  16750. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  16751. };
  16752. THREE.Path.prototype.lineTo = function ( x, y ) {
  16753. var args = Array.prototype.slice.call( arguments );
  16754. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16755. var x0 = lastargs[ lastargs.length - 2 ];
  16756. var y0 = lastargs[ lastargs.length - 1 ];
  16757. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  16758. this.curves.push( curve );
  16759. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  16760. };
  16761. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  16762. var args = Array.prototype.slice.call( arguments );
  16763. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16764. var x0 = lastargs[ lastargs.length - 2 ];
  16765. var y0 = lastargs[ lastargs.length - 1 ];
  16766. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  16767. new THREE.Vector2( aCPx, aCPy ),
  16768. new THREE.Vector2( aX, aY ) );
  16769. this.curves.push( curve );
  16770. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  16771. };
  16772. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  16773. aCP2x, aCP2y,
  16774. aX, aY ) {
  16775. var args = Array.prototype.slice.call( arguments );
  16776. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16777. var x0 = lastargs[ lastargs.length - 2 ];
  16778. var y0 = lastargs[ lastargs.length - 1 ];
  16779. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  16780. new THREE.Vector2( aCP1x, aCP1y ),
  16781. new THREE.Vector2( aCP2x, aCP2y ),
  16782. new THREE.Vector2( aX, aY ) );
  16783. this.curves.push( curve );
  16784. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  16785. };
  16786. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  16787. var args = Array.prototype.slice.call( arguments );
  16788. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16789. var x0 = lastargs[ lastargs.length - 2 ];
  16790. var y0 = lastargs[ lastargs.length - 1 ];
  16791. //---
  16792. var npts = [ new THREE.Vector2( x0, y0 ) ];
  16793. Array.prototype.push.apply( npts, pts );
  16794. var curve = new THREE.SplineCurve( npts );
  16795. this.curves.push( curve );
  16796. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  16797. };
  16798. // FUTURE: Change the API or follow canvas API?
  16799. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  16800. aStartAngle, aEndAngle, aClockwise ) {
  16801. var lastargs = this.actions[ this.actions.length - 1].args;
  16802. var x0 = lastargs[ lastargs.length - 2 ];
  16803. var y0 = lastargs[ lastargs.length - 1 ];
  16804. this.absarc(aX + x0, aY + y0, aRadius,
  16805. aStartAngle, aEndAngle, aClockwise );
  16806. };
  16807. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  16808. aStartAngle, aEndAngle, aClockwise ) {
  16809. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  16810. };
  16811. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  16812. aStartAngle, aEndAngle, aClockwise ) {
  16813. var lastargs = this.actions[ this.actions.length - 1].args;
  16814. var x0 = lastargs[ lastargs.length - 2 ];
  16815. var y0 = lastargs[ lastargs.length - 1 ];
  16816. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  16817. aStartAngle, aEndAngle, aClockwise );
  16818. };
  16819. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  16820. aStartAngle, aEndAngle, aClockwise ) {
  16821. var args = Array.prototype.slice.call( arguments );
  16822. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  16823. aStartAngle, aEndAngle, aClockwise );
  16824. this.curves.push( curve );
  16825. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  16826. args.push(lastPoint.x);
  16827. args.push(lastPoint.y);
  16828. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  16829. };
  16830. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  16831. if ( ! divisions ) divisions = 40;
  16832. var points = [];
  16833. for ( var i = 0; i < divisions; i ++ ) {
  16834. points.push( this.getPoint( i / divisions ) );
  16835. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  16836. }
  16837. // if ( closedPath ) {
  16838. //
  16839. // points.push( points[ 0 ] );
  16840. //
  16841. // }
  16842. return points;
  16843. };
  16844. /* Return an array of vectors based on contour of the path */
  16845. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  16846. if (this.useSpacedPoints) {
  16847. console.log('tata');
  16848. return this.getSpacedPoints( divisions, closedPath );
  16849. }
  16850. divisions = divisions || 12;
  16851. var points = [];
  16852. var i, il, item, action, args;
  16853. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  16854. laste, j,
  16855. t, tx, ty;
  16856. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16857. item = this.actions[ i ];
  16858. action = item.action;
  16859. args = item.args;
  16860. switch( action ) {
  16861. case THREE.PathActions.MOVE_TO:
  16862. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16863. break;
  16864. case THREE.PathActions.LINE_TO:
  16865. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16866. break;
  16867. case THREE.PathActions.QUADRATIC_CURVE_TO:
  16868. cpx = args[ 2 ];
  16869. cpy = args[ 3 ];
  16870. cpx1 = args[ 0 ];
  16871. cpy1 = args[ 1 ];
  16872. if ( points.length > 0 ) {
  16873. laste = points[ points.length - 1 ];
  16874. cpx0 = laste.x;
  16875. cpy0 = laste.y;
  16876. } else {
  16877. laste = this.actions[ i - 1 ].args;
  16878. cpx0 = laste[ laste.length - 2 ];
  16879. cpy0 = laste[ laste.length - 1 ];
  16880. }
  16881. for ( j = 1; j <= divisions; j ++ ) {
  16882. t = j / divisions;
  16883. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16884. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16885. points.push( new THREE.Vector2( tx, ty ) );
  16886. }
  16887. break;
  16888. case THREE.PathActions.BEZIER_CURVE_TO:
  16889. cpx = args[ 4 ];
  16890. cpy = args[ 5 ];
  16891. cpx1 = args[ 0 ];
  16892. cpy1 = args[ 1 ];
  16893. cpx2 = args[ 2 ];
  16894. cpy2 = args[ 3 ];
  16895. if ( points.length > 0 ) {
  16896. laste = points[ points.length - 1 ];
  16897. cpx0 = laste.x;
  16898. cpy0 = laste.y;
  16899. } else {
  16900. laste = this.actions[ i - 1 ].args;
  16901. cpx0 = laste[ laste.length - 2 ];
  16902. cpy0 = laste[ laste.length - 1 ];
  16903. }
  16904. for ( j = 1; j <= divisions; j ++ ) {
  16905. t = j / divisions;
  16906. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16907. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16908. points.push( new THREE.Vector2( tx, ty ) );
  16909. }
  16910. break;
  16911. case THREE.PathActions.CSPLINE_THRU:
  16912. laste = this.actions[ i - 1 ].args;
  16913. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  16914. var spts = [ last ];
  16915. var n = divisions * args[ 0 ].length;
  16916. spts = spts.concat( args[ 0 ] );
  16917. var spline = new THREE.SplineCurve( spts );
  16918. for ( j = 1; j <= n; j ++ ) {
  16919. points.push( spline.getPointAt( j / n ) ) ;
  16920. }
  16921. break;
  16922. case THREE.PathActions.ARC:
  16923. var aX = args[ 0 ], aY = args[ 1 ],
  16924. aRadius = args[ 2 ],
  16925. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  16926. aClockwise = !!args[ 5 ];
  16927. var deltaAngle = aEndAngle - aStartAngle;
  16928. var angle;
  16929. var tdivisions = divisions * 2;
  16930. for ( j = 1; j <= tdivisions; j ++ ) {
  16931. t = j / tdivisions;
  16932. if ( ! aClockwise ) {
  16933. t = 1 - t;
  16934. }
  16935. angle = aStartAngle + t * deltaAngle;
  16936. tx = aX + aRadius * Math.cos( angle );
  16937. ty = aY + aRadius * Math.sin( angle );
  16938. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16939. points.push( new THREE.Vector2( tx, ty ) );
  16940. }
  16941. //console.log(points);
  16942. break;
  16943. case THREE.PathActions.ELLIPSE:
  16944. var aX = args[ 0 ], aY = args[ 1 ],
  16945. xRadius = args[ 2 ],
  16946. yRadius = args[ 3 ],
  16947. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  16948. aClockwise = !!args[ 6 ];
  16949. var deltaAngle = aEndAngle - aStartAngle;
  16950. var angle;
  16951. var tdivisions = divisions * 2;
  16952. for ( j = 1; j <= tdivisions; j ++ ) {
  16953. t = j / tdivisions;
  16954. if ( ! aClockwise ) {
  16955. t = 1 - t;
  16956. }
  16957. angle = aStartAngle + t * deltaAngle;
  16958. tx = aX + xRadius * Math.cos( angle );
  16959. ty = aY + yRadius * Math.sin( angle );
  16960. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16961. points.push( new THREE.Vector2( tx, ty ) );
  16962. }
  16963. //console.log(points);
  16964. break;
  16965. } // end switch
  16966. }
  16967. // Normalize to remove the closing point by default.
  16968. var lastPoint = points[ points.length - 1];
  16969. var EPSILON = 0.0000000001;
  16970. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  16971. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  16972. points.splice( points.length - 1, 1);
  16973. if ( closedPath ) {
  16974. points.push( points[ 0 ] );
  16975. }
  16976. return points;
  16977. };
  16978. // Breaks path into shapes
  16979. THREE.Path.prototype.toShapes = function() {
  16980. var i, il, item, action, args;
  16981. var subPaths = [], lastPath = new THREE.Path();
  16982. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16983. item = this.actions[ i ];
  16984. args = item.args;
  16985. action = item.action;
  16986. if ( action == THREE.PathActions.MOVE_TO ) {
  16987. if ( lastPath.actions.length != 0 ) {
  16988. subPaths.push( lastPath );
  16989. lastPath = new THREE.Path();
  16990. }
  16991. }
  16992. lastPath[ action ].apply( lastPath, args );
  16993. }
  16994. if ( lastPath.actions.length != 0 ) {
  16995. subPaths.push( lastPath );
  16996. }
  16997. // console.log(subPaths);
  16998. if ( subPaths.length == 0 ) return [];
  16999. var tmpPath, tmpShape, shapes = [];
  17000. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17001. // console.log("Holes first", holesFirst);
  17002. if ( subPaths.length == 1) {
  17003. tmpPath = subPaths[0];
  17004. tmpShape = new THREE.Shape();
  17005. tmpShape.actions = tmpPath.actions;
  17006. tmpShape.curves = tmpPath.curves;
  17007. shapes.push( tmpShape );
  17008. return shapes;
  17009. };
  17010. if ( holesFirst ) {
  17011. tmpShape = new THREE.Shape();
  17012. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17013. tmpPath = subPaths[ i ];
  17014. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17015. tmpShape.actions = tmpPath.actions;
  17016. tmpShape.curves = tmpPath.curves;
  17017. shapes.push( tmpShape );
  17018. tmpShape = new THREE.Shape();
  17019. //console.log('cw', i);
  17020. } else {
  17021. tmpShape.holes.push( tmpPath );
  17022. //console.log('ccw', i);
  17023. }
  17024. }
  17025. } else {
  17026. // Shapes first
  17027. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17028. tmpPath = subPaths[ i ];
  17029. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17030. if ( tmpShape ) shapes.push( tmpShape );
  17031. tmpShape = new THREE.Shape();
  17032. tmpShape.actions = tmpPath.actions;
  17033. tmpShape.curves = tmpPath.curves;
  17034. } else {
  17035. tmpShape.holes.push( tmpPath );
  17036. }
  17037. }
  17038. shapes.push( tmpShape );
  17039. }
  17040. //console.log("shape", shapes);
  17041. return shapes;
  17042. };
  17043. /**
  17044. * @author zz85 / http://www.lab4games.net/zz85/blog
  17045. * Defines a 2d shape plane using paths.
  17046. **/
  17047. // STEP 1 Create a path.
  17048. // STEP 2 Turn path into shape.
  17049. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17050. // STEP 3a - Extract points from each shape, turn to vertices
  17051. // STEP 3b - Triangulate each shape, add faces.
  17052. THREE.Shape = function ( ) {
  17053. THREE.Path.apply( this, arguments );
  17054. this.holes = [];
  17055. };
  17056. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17057. // Convenience method to return ExtrudeGeometry
  17058. THREE.Shape.prototype.extrude = function ( options ) {
  17059. var extruded = new THREE.ExtrudeGeometry( this, options );
  17060. return extruded;
  17061. };
  17062. // Convenience method to return ShapeGeometry
  17063. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17064. var geometry = new THREE.ShapeGeometry( this, options );
  17065. return geometry;
  17066. };
  17067. // Get points of holes
  17068. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17069. var i, il = this.holes.length, holesPts = [];
  17070. for ( i = 0; i < il; i ++ ) {
  17071. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17072. }
  17073. return holesPts;
  17074. };
  17075. // Get points of holes (spaced by regular distance)
  17076. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17077. var i, il = this.holes.length, holesPts = [];
  17078. for ( i = 0; i < il; i ++ ) {
  17079. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17080. }
  17081. return holesPts;
  17082. };
  17083. // Get points of shape and holes (keypoints based on segments parameter)
  17084. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17085. return {
  17086. shape: this.getTransformedPoints( divisions ),
  17087. holes: this.getPointsHoles( divisions )
  17088. };
  17089. };
  17090. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17091. if (this.useSpacedPoints) {
  17092. return this.extractAllSpacedPoints(divisions);
  17093. }
  17094. return this.extractAllPoints(divisions);
  17095. };
  17096. //
  17097. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17098. //
  17099. // return {
  17100. //
  17101. // shape: this.transform( bend, divisions ),
  17102. // holes: this.getPointsHoles( divisions, bend )
  17103. //
  17104. // };
  17105. //
  17106. // };
  17107. // Get points of shape and holes (spaced by regular distance)
  17108. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17109. return {
  17110. shape: this.getTransformedSpacedPoints( divisions ),
  17111. holes: this.getSpacedPointsHoles( divisions )
  17112. };
  17113. };
  17114. /**************************************************************
  17115. * Utils
  17116. **************************************************************/
  17117. THREE.Shape.Utils = {
  17118. /*
  17119. contour - array of vector2 for contour
  17120. holes - array of array of vector2
  17121. */
  17122. removeHoles: function ( contour, holes ) {
  17123. var shape = contour.concat(); // work on this shape
  17124. var allpoints = shape.concat();
  17125. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  17126. var prevShapeVert, nextShapeVert,
  17127. prevHoleVert, nextHoleVert,
  17128. holeIndex, shapeIndex,
  17129. shapeId, shapeGroup,
  17130. h, h2,
  17131. hole, shortest, d,
  17132. p, pts1, pts2,
  17133. tmpShape1, tmpShape2,
  17134. tmpHole1, tmpHole2,
  17135. verts = [];
  17136. for ( h = 0; h < holes.length; h ++ ) {
  17137. hole = holes[ h ];
  17138. /*
  17139. shapeholes[ h ].concat(); // preserves original
  17140. holes.push( hole );
  17141. */
  17142. Array.prototype.push.apply( allpoints, hole );
  17143. shortest = Number.POSITIVE_INFINITY;
  17144. // Find the shortest pair of pts between shape and hole
  17145. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  17146. // Using distanceToSquared() intead of distanceTo() should speed a little
  17147. // since running square roots operations are reduced.
  17148. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  17149. pts1 = hole[ h2 ];
  17150. var dist = [];
  17151. for ( p = 0; p < shape.length; p++ ) {
  17152. pts2 = shape[ p ];
  17153. d = pts1.distanceToSquared( pts2 );
  17154. dist.push( d );
  17155. if ( d < shortest ) {
  17156. shortest = d;
  17157. holeIndex = h2;
  17158. shapeIndex = p;
  17159. }
  17160. }
  17161. }
  17162. //console.log("shortest", shortest, dist);
  17163. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17164. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17165. var areaapts = [
  17166. hole[ holeIndex ],
  17167. shape[ shapeIndex ],
  17168. shape[ prevShapeVert ]
  17169. ];
  17170. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  17171. var areabpts = [
  17172. hole[ holeIndex ],
  17173. hole[ prevHoleVert ],
  17174. shape[ shapeIndex ]
  17175. ];
  17176. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  17177. var shapeOffset = 1;
  17178. var holeOffset = -1;
  17179. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  17180. shapeIndex += shapeOffset;
  17181. holeIndex += holeOffset;
  17182. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17183. shapeIndex %= shape.length;
  17184. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17185. holeIndex %= hole.length;
  17186. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17187. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17188. areaapts = [
  17189. hole[ holeIndex ],
  17190. shape[ shapeIndex ],
  17191. shape[ prevShapeVert ]
  17192. ];
  17193. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  17194. areabpts = [
  17195. hole[ holeIndex ],
  17196. hole[ prevHoleVert ],
  17197. shape[ shapeIndex ]
  17198. ];
  17199. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  17200. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  17201. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  17202. // In case areas are not correct.
  17203. //console.log("USE THIS");
  17204. shapeIndex = oldShapeIndex;
  17205. holeIndex = oldHoleIndex ;
  17206. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17207. shapeIndex %= shape.length;
  17208. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17209. holeIndex %= hole.length;
  17210. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17211. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17212. } else {
  17213. //console.log("USE THAT ")
  17214. }
  17215. tmpShape1 = shape.slice( 0, shapeIndex );
  17216. tmpShape2 = shape.slice( shapeIndex );
  17217. tmpHole1 = hole.slice( holeIndex );
  17218. tmpHole2 = hole.slice( 0, holeIndex );
  17219. // Should check orders here again?
  17220. var trianglea = [
  17221. hole[ holeIndex ],
  17222. shape[ shapeIndex ],
  17223. shape[ prevShapeVert ]
  17224. ];
  17225. var triangleb = [
  17226. hole[ holeIndex ] ,
  17227. hole[ prevHoleVert ],
  17228. shape[ shapeIndex ]
  17229. ];
  17230. verts.push( trianglea );
  17231. verts.push( triangleb );
  17232. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17233. }
  17234. return {
  17235. shape:shape, /* shape with no holes */
  17236. isolatedPts: verts, /* isolated faces */
  17237. allpoints: allpoints
  17238. }
  17239. },
  17240. triangulateShape: function ( contour, holes ) {
  17241. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  17242. var shape = shapeWithoutHoles.shape,
  17243. allpoints = shapeWithoutHoles.allpoints,
  17244. isolatedPts = shapeWithoutHoles.isolatedPts;
  17245. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  17246. // 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.
  17247. //console.log( "triangles",triangles, triangles.length );
  17248. //console.log( "allpoints",allpoints, allpoints.length );
  17249. var i, il, f, face,
  17250. key, index,
  17251. allPointsMap = {},
  17252. isolatedPointsMap = {};
  17253. // prepare all points map
  17254. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17255. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17256. if ( allPointsMap[ key ] !== undefined ) {
  17257. console.log( "Duplicate point", key );
  17258. }
  17259. allPointsMap[ key ] = i;
  17260. }
  17261. // check all face vertices against all points map
  17262. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17263. face = triangles[ i ];
  17264. for ( f = 0; f < 3; f ++ ) {
  17265. key = face[ f ].x + ":" + face[ f ].y;
  17266. index = allPointsMap[ key ];
  17267. if ( index !== undefined ) {
  17268. face[ f ] = index;
  17269. }
  17270. }
  17271. }
  17272. // check isolated points vertices against all points map
  17273. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  17274. face = isolatedPts[ i ];
  17275. for ( f = 0; f < 3; f ++ ) {
  17276. key = face[ f ].x + ":" + face[ f ].y;
  17277. index = allPointsMap[ key ];
  17278. if ( index !== undefined ) {
  17279. face[ f ] = index;
  17280. }
  17281. }
  17282. }
  17283. return triangles.concat( isolatedPts );
  17284. }, // end triangulate shapes
  17285. /*
  17286. triangulate2 : function( pts, holes ) {
  17287. // For use with Poly2Tri.js
  17288. var allpts = pts.concat();
  17289. var shape = [];
  17290. for (var p in pts) {
  17291. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  17292. }
  17293. var swctx = new js.poly2tri.SweepContext(shape);
  17294. for (var h in holes) {
  17295. var aHole = holes[h];
  17296. var newHole = []
  17297. for (i in aHole) {
  17298. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  17299. allpts.push(aHole[i]);
  17300. }
  17301. swctx.AddHole(newHole);
  17302. }
  17303. var find;
  17304. var findIndexForPt = function (pt) {
  17305. find = new THREE.Vector2(pt.x, pt.y);
  17306. var p;
  17307. for (p=0, pl = allpts.length; p<pl; p++) {
  17308. if (allpts[p].equals(find)) return p;
  17309. }
  17310. return -1;
  17311. };
  17312. // triangulate
  17313. js.poly2tri.sweep.Triangulate(swctx);
  17314. var triangles = swctx.GetTriangles();
  17315. var tr ;
  17316. var facesPts = [];
  17317. for (var t in triangles) {
  17318. tr = triangles[t];
  17319. facesPts.push([
  17320. findIndexForPt(tr.GetPoint(0)),
  17321. findIndexForPt(tr.GetPoint(1)),
  17322. findIndexForPt(tr.GetPoint(2))
  17323. ]);
  17324. }
  17325. // console.log(facesPts);
  17326. // console.log("triangles", triangles.length, triangles);
  17327. // Returns array of faces with 3 element each
  17328. return facesPts;
  17329. },
  17330. */
  17331. isClockWise: function ( pts ) {
  17332. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17333. },
  17334. // Bezier Curves formulas obtained from
  17335. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17336. // Quad Bezier Functions
  17337. b2p0: function ( t, p ) {
  17338. var k = 1 - t;
  17339. return k * k * p;
  17340. },
  17341. b2p1: function ( t, p ) {
  17342. return 2 * ( 1 - t ) * t * p;
  17343. },
  17344. b2p2: function ( t, p ) {
  17345. return t * t * p;
  17346. },
  17347. b2: function ( t, p0, p1, p2 ) {
  17348. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17349. },
  17350. // Cubic Bezier Functions
  17351. b3p0: function ( t, p ) {
  17352. var k = 1 - t;
  17353. return k * k * k * p;
  17354. },
  17355. b3p1: function ( t, p ) {
  17356. var k = 1 - t;
  17357. return 3 * k * k * t * p;
  17358. },
  17359. b3p2: function ( t, p ) {
  17360. var k = 1 - t;
  17361. return 3 * k * t * t * p;
  17362. },
  17363. b3p3: function ( t, p ) {
  17364. return t * t * t * p;
  17365. },
  17366. b3: function ( t, p0, p1, p2, p3 ) {
  17367. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17368. }
  17369. };
  17370. /**
  17371. * @author mikael emtinger / http://gomo.se/
  17372. */
  17373. THREE.AnimationHandler = (function() {
  17374. var playing = [];
  17375. var library = {};
  17376. var that = {};
  17377. //--- update ---
  17378. that.update = function( deltaTimeMS ) {
  17379. for( var i = 0; i < playing.length; i ++ )
  17380. playing[ i ].update( deltaTimeMS );
  17381. };
  17382. //--- add ---
  17383. that.addToUpdate = function( animation ) {
  17384. if ( playing.indexOf( animation ) === -1 )
  17385. playing.push( animation );
  17386. };
  17387. //--- remove ---
  17388. that.removeFromUpdate = function( animation ) {
  17389. var index = playing.indexOf( animation );
  17390. if( index !== -1 )
  17391. playing.splice( index, 1 );
  17392. };
  17393. //--- add ---
  17394. that.add = function( data ) {
  17395. if ( library[ data.name ] !== undefined )
  17396. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  17397. library[ data.name ] = data;
  17398. initData( data );
  17399. };
  17400. //--- get ---
  17401. that.get = function( name ) {
  17402. if ( typeof name === "string" ) {
  17403. if ( library[ name ] ) {
  17404. return library[ name ];
  17405. } else {
  17406. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  17407. return null;
  17408. }
  17409. } else {
  17410. // todo: add simple tween library
  17411. }
  17412. };
  17413. //--- parse ---
  17414. that.parse = function( root ) {
  17415. // setup hierarchy
  17416. var hierarchy = [];
  17417. if ( root instanceof THREE.SkinnedMesh ) {
  17418. for( var b = 0; b < root.bones.length; b++ ) {
  17419. hierarchy.push( root.bones[ b ] );
  17420. }
  17421. } else {
  17422. parseRecurseHierarchy( root, hierarchy );
  17423. }
  17424. return hierarchy;
  17425. };
  17426. var parseRecurseHierarchy = function( root, hierarchy ) {
  17427. hierarchy.push( root );
  17428. for( var c = 0; c < root.children.length; c++ )
  17429. parseRecurseHierarchy( root.children[ c ], hierarchy );
  17430. }
  17431. //--- init data ---
  17432. var initData = function( data ) {
  17433. if( data.initialized === true )
  17434. return;
  17435. // loop through all keys
  17436. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  17437. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17438. // remove minus times
  17439. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  17440. data.hierarchy[ h ].keys[ k ].time = 0;
  17441. // create quaternions
  17442. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  17443. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  17444. var quat = data.hierarchy[ h ].keys[ k ].rot;
  17445. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  17446. }
  17447. }
  17448. // prepare morph target keys
  17449. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  17450. // get all used
  17451. var usedMorphTargets = {};
  17452. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17453. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17454. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  17455. usedMorphTargets[ morphTargetName ] = -1;
  17456. }
  17457. }
  17458. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  17459. // set all used on all frames
  17460. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17461. var influences = {};
  17462. for ( var morphTargetName in usedMorphTargets ) {
  17463. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17464. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  17465. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  17466. break;
  17467. }
  17468. }
  17469. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  17470. influences[ morphTargetName ] = 0;
  17471. }
  17472. }
  17473. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  17474. }
  17475. }
  17476. // remove all keys that are on the same time
  17477. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17478. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  17479. data.hierarchy[ h ].keys.splice( k, 1 );
  17480. k --;
  17481. }
  17482. }
  17483. // set index
  17484. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17485. data.hierarchy[ h ].keys[ k ].index = k;
  17486. }
  17487. }
  17488. // JIT
  17489. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  17490. data.JIT = {};
  17491. data.JIT.hierarchy = [];
  17492. for( var h = 0; h < data.hierarchy.length; h ++ )
  17493. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  17494. // done
  17495. data.initialized = true;
  17496. };
  17497. // interpolation types
  17498. that.LINEAR = 0;
  17499. that.CATMULLROM = 1;
  17500. that.CATMULLROM_FORWARD = 2;
  17501. return that;
  17502. }());
  17503. /**
  17504. * @author mikael emtinger / http://gomo.se/
  17505. * @author mrdoob / http://mrdoob.com/
  17506. * @author alteredq / http://alteredqualia.com/
  17507. */
  17508. THREE.Animation = function ( root, name, interpolationType ) {
  17509. this.root = root;
  17510. this.data = THREE.AnimationHandler.get( name );
  17511. this.hierarchy = THREE.AnimationHandler.parse( root );
  17512. this.currentTime = 0;
  17513. this.timeScale = 1;
  17514. this.isPlaying = false;
  17515. this.isPaused = true;
  17516. this.loop = true;
  17517. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  17518. this.points = [];
  17519. this.target = new THREE.Vector3();
  17520. };
  17521. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  17522. if ( this.isPlaying === false ) {
  17523. this.isPlaying = true;
  17524. this.loop = loop !== undefined ? loop : true;
  17525. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17526. // reset key cache
  17527. var h, hl = this.hierarchy.length,
  17528. object;
  17529. for ( h = 0; h < hl; h ++ ) {
  17530. object = this.hierarchy[ h ];
  17531. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17532. object.useQuaternion = true;
  17533. }
  17534. object.matrixAutoUpdate = true;
  17535. if ( object.animationCache === undefined ) {
  17536. object.animationCache = {};
  17537. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  17538. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  17539. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17540. }
  17541. var prevKey = object.animationCache.prevKey;
  17542. var nextKey = object.animationCache.nextKey;
  17543. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  17544. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  17545. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  17546. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  17547. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  17548. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  17549. }
  17550. this.update( 0 );
  17551. }
  17552. this.isPaused = false;
  17553. THREE.AnimationHandler.addToUpdate( this );
  17554. };
  17555. THREE.Animation.prototype.pause = function() {
  17556. if ( this.isPaused === true ) {
  17557. THREE.AnimationHandler.addToUpdate( this );
  17558. } else {
  17559. THREE.AnimationHandler.removeFromUpdate( this );
  17560. }
  17561. this.isPaused = !this.isPaused;
  17562. };
  17563. THREE.Animation.prototype.stop = function() {
  17564. this.isPlaying = false;
  17565. this.isPaused = false;
  17566. THREE.AnimationHandler.removeFromUpdate( this );
  17567. };
  17568. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  17569. // early out
  17570. if ( this.isPlaying === false ) return;
  17571. // vars
  17572. var types = [ "pos", "rot", "scl" ];
  17573. var type;
  17574. var scale;
  17575. var vector;
  17576. var prevXYZ, nextXYZ;
  17577. var prevKey, nextKey;
  17578. var object;
  17579. var animationCache;
  17580. var frame;
  17581. var JIThierarchy = this.data.JIT.hierarchy;
  17582. var currentTime, unloopedCurrentTime;
  17583. var currentPoint, forwardPoint, angle;
  17584. this.currentTime += deltaTimeMS * this.timeScale;
  17585. unloopedCurrentTime = this.currentTime;
  17586. currentTime = this.currentTime = this.currentTime % this.data.length;
  17587. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17588. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17589. object = this.hierarchy[ h ];
  17590. animationCache = object.animationCache;
  17591. // loop through pos/rot/scl
  17592. for ( var t = 0; t < 3; t ++ ) {
  17593. // get keys
  17594. type = types[ t ];
  17595. prevKey = animationCache.prevKey[ type ];
  17596. nextKey = animationCache.nextKey[ type ];
  17597. // switch keys?
  17598. if ( nextKey.time <= unloopedCurrentTime ) {
  17599. // did we loop?
  17600. if ( currentTime < unloopedCurrentTime ) {
  17601. if ( this.loop ) {
  17602. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  17603. nextKey = this.getNextKeyWith( type, h, 1 );
  17604. while( nextKey.time < currentTime ) {
  17605. prevKey = nextKey;
  17606. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17607. }
  17608. } else {
  17609. this.stop();
  17610. return;
  17611. }
  17612. } else {
  17613. do {
  17614. prevKey = nextKey;
  17615. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17616. } while( nextKey.time < currentTime )
  17617. }
  17618. animationCache.prevKey[ type ] = prevKey;
  17619. animationCache.nextKey[ type ] = nextKey;
  17620. }
  17621. object.matrixAutoUpdate = true;
  17622. object.matrixWorldNeedsUpdate = true;
  17623. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  17624. prevXYZ = prevKey[ type ];
  17625. nextXYZ = nextKey[ type ];
  17626. // check scale error
  17627. if ( scale < 0 || scale > 1 ) {
  17628. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  17629. scale = scale < 0 ? 0 : 1;
  17630. }
  17631. // interpolate
  17632. if ( type === "pos" ) {
  17633. vector = object.position;
  17634. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  17635. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17636. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17637. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17638. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17639. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17640. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  17641. this.points[ 1 ] = prevXYZ;
  17642. this.points[ 2 ] = nextXYZ;
  17643. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  17644. scale = scale * 0.33 + 0.33;
  17645. currentPoint = this.interpolateCatmullRom( this.points, scale );
  17646. vector.x = currentPoint[ 0 ];
  17647. vector.y = currentPoint[ 1 ];
  17648. vector.z = currentPoint[ 2 ];
  17649. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17650. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  17651. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  17652. this.target.sub( vector );
  17653. this.target.y = 0;
  17654. this.target.normalize();
  17655. angle = Math.atan2( this.target.x, this.target.z );
  17656. object.rotation.set( 0, angle, 0 );
  17657. }
  17658. }
  17659. } else if ( type === "rot" ) {
  17660. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  17661. } else if ( type === "scl" ) {
  17662. vector = object.scale;
  17663. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17664. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17665. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17666. }
  17667. }
  17668. }
  17669. };
  17670. // Catmull-Rom spline
  17671. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  17672. var c = [], v3 = [],
  17673. point, intPoint, weight, w2, w3,
  17674. pa, pb, pc, pd;
  17675. point = ( points.length - 1 ) * scale;
  17676. intPoint = Math.floor( point );
  17677. weight = point - intPoint;
  17678. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  17679. c[ 1 ] = intPoint;
  17680. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  17681. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  17682. pa = points[ c[ 0 ] ];
  17683. pb = points[ c[ 1 ] ];
  17684. pc = points[ c[ 2 ] ];
  17685. pd = points[ c[ 3 ] ];
  17686. w2 = weight * weight;
  17687. w3 = weight * w2;
  17688. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  17689. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  17690. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  17691. return v3;
  17692. };
  17693. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  17694. var v0 = ( p2 - p0 ) * 0.5,
  17695. v1 = ( p3 - p1 ) * 0.5;
  17696. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17697. };
  17698. // Get next key with
  17699. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  17700. var keys = this.data.hierarchy[ h ].keys;
  17701. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17702. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17703. key = key < keys.length - 1 ? key : keys.length - 1;
  17704. } else {
  17705. key = key % keys.length;
  17706. }
  17707. for ( ; key < keys.length; key++ ) {
  17708. if ( keys[ key ][ type ] !== undefined ) {
  17709. return keys[ key ];
  17710. }
  17711. }
  17712. return this.data.hierarchy[ h ].keys[ 0 ];
  17713. };
  17714. // Get previous key with
  17715. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  17716. var keys = this.data.hierarchy[ h ].keys;
  17717. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17718. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17719. key = key > 0 ? key : 0;
  17720. } else {
  17721. key = key >= 0 ? key : key + keys.length;
  17722. }
  17723. for ( ; key >= 0; key -- ) {
  17724. if ( keys[ key ][ type ] !== undefined ) {
  17725. return keys[ key ];
  17726. }
  17727. }
  17728. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  17729. };
  17730. /**
  17731. * @author mikael emtinger / http://gomo.se/
  17732. * @author mrdoob / http://mrdoob.com/
  17733. * @author alteredq / http://alteredqualia.com/
  17734. * @author khang duong
  17735. * @author erik kitson
  17736. */
  17737. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  17738. this.root = root;
  17739. this.data = THREE.AnimationHandler.get( data );
  17740. this.hierarchy = THREE.AnimationHandler.parse( root );
  17741. this.currentTime = 0;
  17742. this.timeScale = 0.001;
  17743. this.isPlaying = false;
  17744. this.isPaused = true;
  17745. this.loop = true;
  17746. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  17747. // initialize to first keyframes
  17748. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17749. var keys = this.data.hierarchy[h].keys,
  17750. sids = this.data.hierarchy[h].sids,
  17751. obj = this.hierarchy[h];
  17752. if ( keys.length && sids ) {
  17753. for ( var s = 0; s < sids.length; s++ ) {
  17754. var sid = sids[ s ],
  17755. next = this.getNextKeyWith( sid, h, 0 );
  17756. if ( next ) {
  17757. next.apply( sid );
  17758. }
  17759. }
  17760. obj.matrixAutoUpdate = false;
  17761. this.data.hierarchy[h].node.updateMatrix();
  17762. obj.matrixWorldNeedsUpdate = true;
  17763. }
  17764. }
  17765. };
  17766. // Play
  17767. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  17768. if( !this.isPlaying ) {
  17769. this.isPlaying = true;
  17770. this.loop = loop !== undefined ? loop : true;
  17771. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17772. this.startTimeMs = startTimeMS;
  17773. this.startTime = 10000000;
  17774. this.endTime = -this.startTime;
  17775. // reset key cache
  17776. var h, hl = this.hierarchy.length,
  17777. object,
  17778. node;
  17779. for ( h = 0; h < hl; h++ ) {
  17780. object = this.hierarchy[ h ];
  17781. node = this.data.hierarchy[ h ];
  17782. object.useQuaternion = true;
  17783. if ( node.animationCache === undefined ) {
  17784. node.animationCache = {};
  17785. node.animationCache.prevKey = null;
  17786. node.animationCache.nextKey = null;
  17787. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17788. }
  17789. var keys = this.data.hierarchy[h].keys;
  17790. if (keys.length) {
  17791. node.animationCache.prevKey = keys[ 0 ];
  17792. node.animationCache.nextKey = keys[ 1 ];
  17793. this.startTime = Math.min( keys[0].time, this.startTime );
  17794. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  17795. }
  17796. }
  17797. this.update( 0 );
  17798. }
  17799. this.isPaused = false;
  17800. THREE.AnimationHandler.addToUpdate( this );
  17801. };
  17802. // Pause
  17803. THREE.KeyFrameAnimation.prototype.pause = function() {
  17804. if( this.isPaused ) {
  17805. THREE.AnimationHandler.addToUpdate( this );
  17806. } else {
  17807. THREE.AnimationHandler.removeFromUpdate( this );
  17808. }
  17809. this.isPaused = !this.isPaused;
  17810. };
  17811. // Stop
  17812. THREE.KeyFrameAnimation.prototype.stop = function() {
  17813. this.isPlaying = false;
  17814. this.isPaused = false;
  17815. THREE.AnimationHandler.removeFromUpdate( this );
  17816. // reset JIT matrix and remove cache
  17817. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  17818. var obj = this.hierarchy[ h ];
  17819. var node = this.data.hierarchy[ h ];
  17820. if ( node.animationCache !== undefined ) {
  17821. var original = node.animationCache.originalMatrix;
  17822. if( obj instanceof THREE.Bone ) {
  17823. original.copy( obj.skinMatrix );
  17824. obj.skinMatrix = original;
  17825. } else {
  17826. original.copy( obj.matrix );
  17827. obj.matrix = original;
  17828. }
  17829. delete node.animationCache;
  17830. }
  17831. }
  17832. };
  17833. // Update
  17834. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  17835. // early out
  17836. if( !this.isPlaying ) return;
  17837. // vars
  17838. var prevKey, nextKey;
  17839. var object;
  17840. var node;
  17841. var frame;
  17842. var JIThierarchy = this.data.JIT.hierarchy;
  17843. var currentTime, unloopedCurrentTime;
  17844. var looped;
  17845. // update
  17846. this.currentTime += deltaTimeMS * this.timeScale;
  17847. unloopedCurrentTime = this.currentTime;
  17848. currentTime = this.currentTime = this.currentTime % this.data.length;
  17849. // if looped around, the current time should be based on the startTime
  17850. if ( currentTime < this.startTimeMs ) {
  17851. currentTime = this.currentTime = this.startTimeMs + currentTime;
  17852. }
  17853. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17854. looped = currentTime < unloopedCurrentTime;
  17855. if ( looped && !this.loop ) {
  17856. // Set the animation to the last keyframes and stop
  17857. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17858. var keys = this.data.hierarchy[h].keys,
  17859. sids = this.data.hierarchy[h].sids,
  17860. end = keys.length-1,
  17861. obj = this.hierarchy[h];
  17862. if ( keys.length ) {
  17863. for ( var s = 0; s < sids.length; s++ ) {
  17864. var sid = sids[ s ],
  17865. prev = this.getPrevKeyWith( sid, h, end );
  17866. if ( prev ) {
  17867. prev.apply( sid );
  17868. }
  17869. }
  17870. this.data.hierarchy[h].node.updateMatrix();
  17871. obj.matrixWorldNeedsUpdate = true;
  17872. }
  17873. }
  17874. this.stop();
  17875. return;
  17876. }
  17877. // check pre-infinity
  17878. if ( currentTime < this.startTime ) {
  17879. return;
  17880. }
  17881. // update
  17882. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17883. object = this.hierarchy[ h ];
  17884. node = this.data.hierarchy[ h ];
  17885. var keys = node.keys,
  17886. animationCache = node.animationCache;
  17887. // use JIT?
  17888. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  17889. if( object instanceof THREE.Bone ) {
  17890. object.skinMatrix = JIThierarchy[ h ][ frame ];
  17891. object.matrixWorldNeedsUpdate = false;
  17892. } else {
  17893. object.matrix = JIThierarchy[ h ][ frame ];
  17894. object.matrixWorldNeedsUpdate = true;
  17895. }
  17896. // use interpolation
  17897. } else if ( keys.length ) {
  17898. // make sure so original matrix and not JIT matrix is set
  17899. if ( this.JITCompile && animationCache ) {
  17900. if( object instanceof THREE.Bone ) {
  17901. object.skinMatrix = animationCache.originalMatrix;
  17902. } else {
  17903. object.matrix = animationCache.originalMatrix;
  17904. }
  17905. }
  17906. prevKey = animationCache.prevKey;
  17907. nextKey = animationCache.nextKey;
  17908. if ( prevKey && nextKey ) {
  17909. // switch keys?
  17910. if ( nextKey.time <= unloopedCurrentTime ) {
  17911. // did we loop?
  17912. if ( looped && this.loop ) {
  17913. prevKey = keys[ 0 ];
  17914. nextKey = keys[ 1 ];
  17915. while ( nextKey.time < currentTime ) {
  17916. prevKey = nextKey;
  17917. nextKey = keys[ prevKey.index + 1 ];
  17918. }
  17919. } else if ( !looped ) {
  17920. var lastIndex = keys.length - 1;
  17921. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  17922. prevKey = nextKey;
  17923. nextKey = keys[ prevKey.index + 1 ];
  17924. }
  17925. }
  17926. animationCache.prevKey = prevKey;
  17927. animationCache.nextKey = nextKey;
  17928. }
  17929. if(nextKey.time >= currentTime)
  17930. prevKey.interpolate( nextKey, currentTime );
  17931. else
  17932. prevKey.interpolate( nextKey, nextKey.time);
  17933. }
  17934. this.data.hierarchy[h].node.updateMatrix();
  17935. object.matrixWorldNeedsUpdate = true;
  17936. }
  17937. }
  17938. // update JIT?
  17939. if ( this.JITCompile ) {
  17940. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  17941. this.hierarchy[ 0 ].updateMatrixWorld( true );
  17942. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  17943. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  17944. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  17945. } else {
  17946. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  17947. }
  17948. }
  17949. }
  17950. }
  17951. };
  17952. // Get next key with
  17953. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  17954. var keys = this.data.hierarchy[ h ].keys;
  17955. key = key % keys.length;
  17956. for ( ; key < keys.length; key++ ) {
  17957. if ( keys[ key ].hasTarget( sid ) ) {
  17958. return keys[ key ];
  17959. }
  17960. }
  17961. return keys[ 0 ];
  17962. };
  17963. // Get previous key with
  17964. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  17965. var keys = this.data.hierarchy[ h ].keys;
  17966. key = key >= 0 ? key : key + keys.length;
  17967. for ( ; key >= 0; key-- ) {
  17968. if ( keys[ key ].hasTarget( sid ) ) {
  17969. return keys[ key ];
  17970. }
  17971. }
  17972. return keys[ keys.length - 1 ];
  17973. };
  17974. /**
  17975. * Camera for rendering cube maps
  17976. * - renders scene into axis-aligned cube
  17977. *
  17978. * @author alteredq / http://alteredqualia.com/
  17979. */
  17980. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  17981. THREE.Object3D.call( this );
  17982. var fov = 90, aspect = 1;
  17983. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17984. cameraPX.up.set( 0, -1, 0 );
  17985. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  17986. this.add( cameraPX );
  17987. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17988. cameraNX.up.set( 0, -1, 0 );
  17989. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  17990. this.add( cameraNX );
  17991. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17992. cameraPY.up.set( 0, 0, 1 );
  17993. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  17994. this.add( cameraPY );
  17995. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17996. cameraNY.up.set( 0, 0, -1 );
  17997. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  17998. this.add( cameraNY );
  17999. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18000. cameraPZ.up.set( 0, -1, 0 );
  18001. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  18002. this.add( cameraPZ );
  18003. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18004. cameraNZ.up.set( 0, -1, 0 );
  18005. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  18006. this.add( cameraNZ );
  18007. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  18008. this.updateCubeMap = function ( renderer, scene ) {
  18009. var renderTarget = this.renderTarget;
  18010. var generateMipmaps = renderTarget.generateMipmaps;
  18011. renderTarget.generateMipmaps = false;
  18012. renderTarget.activeCubeFace = 0;
  18013. renderer.render( scene, cameraPX, renderTarget );
  18014. renderTarget.activeCubeFace = 1;
  18015. renderer.render( scene, cameraNX, renderTarget );
  18016. renderTarget.activeCubeFace = 2;
  18017. renderer.render( scene, cameraPY, renderTarget );
  18018. renderTarget.activeCubeFace = 3;
  18019. renderer.render( scene, cameraNY, renderTarget );
  18020. renderTarget.activeCubeFace = 4;
  18021. renderer.render( scene, cameraPZ, renderTarget );
  18022. renderTarget.generateMipmaps = generateMipmaps;
  18023. renderTarget.activeCubeFace = 5;
  18024. renderer.render( scene, cameraNZ, renderTarget );
  18025. };
  18026. };
  18027. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  18028. /*
  18029. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  18030. *
  18031. * A general perpose camera, for setting FOV, Lens Focal Length,
  18032. * and switching between perspective and orthographic views easily.
  18033. * Use this only if you do not wish to manage
  18034. * both a Orthographic and Perspective Camera
  18035. *
  18036. */
  18037. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  18038. THREE.Camera.call( this );
  18039. this.fov = fov;
  18040. this.left = -width / 2;
  18041. this.right = width / 2
  18042. this.top = height / 2;
  18043. this.bottom = -height / 2;
  18044. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  18045. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  18046. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  18047. this.zoom = 1;
  18048. this.toPerspective();
  18049. var aspect = width/height;
  18050. };
  18051. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  18052. THREE.CombinedCamera.prototype.toPerspective = function () {
  18053. // Switches to the Perspective Camera
  18054. this.near = this.cameraP.near;
  18055. this.far = this.cameraP.far;
  18056. this.cameraP.fov = this.fov / this.zoom ;
  18057. this.cameraP.updateProjectionMatrix();
  18058. this.projectionMatrix = this.cameraP.projectionMatrix;
  18059. this.inPerspectiveMode = true;
  18060. this.inOrthographicMode = false;
  18061. };
  18062. THREE.CombinedCamera.prototype.toOrthographic = function () {
  18063. // Switches to the Orthographic camera estimating viewport from Perspective
  18064. var fov = this.fov;
  18065. var aspect = this.cameraP.aspect;
  18066. var near = this.cameraP.near;
  18067. var far = this.cameraP.far;
  18068. // The size that we set is the mid plane of the viewing frustum
  18069. var hyperfocus = ( near + far ) / 2;
  18070. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  18071. var planeHeight = 2 * halfHeight;
  18072. var planeWidth = planeHeight * aspect;
  18073. var halfWidth = planeWidth / 2;
  18074. halfHeight /= this.zoom;
  18075. halfWidth /= this.zoom;
  18076. this.cameraO.left = -halfWidth;
  18077. this.cameraO.right = halfWidth;
  18078. this.cameraO.top = halfHeight;
  18079. this.cameraO.bottom = -halfHeight;
  18080. // this.cameraO.left = -farHalfWidth;
  18081. // this.cameraO.right = farHalfWidth;
  18082. // this.cameraO.top = farHalfHeight;
  18083. // this.cameraO.bottom = -farHalfHeight;
  18084. // this.cameraO.left = this.left / this.zoom;
  18085. // this.cameraO.right = this.right / this.zoom;
  18086. // this.cameraO.top = this.top / this.zoom;
  18087. // this.cameraO.bottom = this.bottom / this.zoom;
  18088. this.cameraO.updateProjectionMatrix();
  18089. this.near = this.cameraO.near;
  18090. this.far = this.cameraO.far;
  18091. this.projectionMatrix = this.cameraO.projectionMatrix;
  18092. this.inPerspectiveMode = false;
  18093. this.inOrthographicMode = true;
  18094. };
  18095. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  18096. this.cameraP.aspect = width / height;
  18097. this.left = -width / 2;
  18098. this.right = width / 2
  18099. this.top = height / 2;
  18100. this.bottom = -height / 2;
  18101. };
  18102. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  18103. this.fov = fov;
  18104. if ( this.inPerspectiveMode ) {
  18105. this.toPerspective();
  18106. } else {
  18107. this.toOrthographic();
  18108. }
  18109. };
  18110. // For mantaining similar API with PerspectiveCamera
  18111. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  18112. if ( this.inPerspectiveMode ) {
  18113. this.toPerspective();
  18114. } else {
  18115. this.toPerspective();
  18116. this.toOrthographic();
  18117. }
  18118. };
  18119. /*
  18120. * Uses Focal Length (in mm) to estimate and set FOV
  18121. * 35mm (fullframe) camera is used if frame size is not specified;
  18122. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  18123. */
  18124. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  18125. if ( frameHeight === undefined ) frameHeight = 24;
  18126. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  18127. this.setFov( fov );
  18128. return fov;
  18129. };
  18130. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  18131. this.zoom = zoom;
  18132. if ( this.inPerspectiveMode ) {
  18133. this.toPerspective();
  18134. } else {
  18135. this.toOrthographic();
  18136. }
  18137. };
  18138. THREE.CombinedCamera.prototype.toFrontView = function() {
  18139. this.rotation.x = 0;
  18140. this.rotation.y = 0;
  18141. this.rotation.z = 0;
  18142. // should we be modifing the matrix instead?
  18143. this.rotationAutoUpdate = false;
  18144. };
  18145. THREE.CombinedCamera.prototype.toBackView = function() {
  18146. this.rotation.x = 0;
  18147. this.rotation.y = Math.PI;
  18148. this.rotation.z = 0;
  18149. this.rotationAutoUpdate = false;
  18150. };
  18151. THREE.CombinedCamera.prototype.toLeftView = function() {
  18152. this.rotation.x = 0;
  18153. this.rotation.y = - Math.PI / 2;
  18154. this.rotation.z = 0;
  18155. this.rotationAutoUpdate = false;
  18156. };
  18157. THREE.CombinedCamera.prototype.toRightView = function() {
  18158. this.rotation.x = 0;
  18159. this.rotation.y = Math.PI / 2;
  18160. this.rotation.z = 0;
  18161. this.rotationAutoUpdate = false;
  18162. };
  18163. THREE.CombinedCamera.prototype.toTopView = function() {
  18164. this.rotation.x = - Math.PI / 2;
  18165. this.rotation.y = 0;
  18166. this.rotation.z = 0;
  18167. this.rotationAutoUpdate = false;
  18168. };
  18169. THREE.CombinedCamera.prototype.toBottomView = function() {
  18170. this.rotation.x = Math.PI / 2;
  18171. this.rotation.y = 0;
  18172. this.rotation.z = 0;
  18173. this.rotationAutoUpdate = false;
  18174. };
  18175. /**
  18176. * @author alteredq / http://alteredqualia.com/
  18177. *
  18178. * - 3d asterisk shape (for line pieces THREE.Line)
  18179. */
  18180. THREE.AsteriskGeometry = function ( innerRadius, outerRadius ) {
  18181. THREE.Geometry.call( this );
  18182. var sd = innerRadius;
  18183. var ed = outerRadius;
  18184. var sd2 = 0.707 * sd;
  18185. var ed2 = 0.707 * ed;
  18186. var rays = [ [ sd, 0, 0 ], [ ed, 0, 0 ], [ -sd, 0, 0 ], [ -ed, 0, 0 ],
  18187. [ 0, sd, 0 ], [ 0, ed, 0 ], [ 0, -sd, 0 ], [ 0, -ed, 0 ],
  18188. [ 0, 0, sd ], [ 0, 0, ed ], [ 0, 0, -sd ], [ 0, 0, -ed ],
  18189. [ sd2, sd2, 0 ], [ ed2, ed2, 0 ], [ -sd2, -sd2, 0 ], [ -ed2, -ed2, 0 ],
  18190. [ sd2, -sd2, 0 ], [ ed2, -ed2, 0 ], [ -sd2, sd2, 0 ], [ -ed2, ed2, 0 ],
  18191. [ sd2, 0, sd2 ], [ ed2, 0, ed2 ], [ -sd2, 0, -sd2 ], [ -ed2, 0, -ed2 ],
  18192. [ sd2, 0, -sd2 ], [ ed2, 0, -ed2 ], [ -sd2, 0, sd2 ], [ -ed2, 0, ed2 ],
  18193. [ 0, sd2, sd2 ], [ 0, ed2, ed2 ], [ 0, -sd2, -sd2 ], [ 0, -ed2, -ed2 ],
  18194. [ 0, sd2, -sd2 ], [ 0, ed2, -ed2 ], [ 0, -sd2, sd2 ], [ 0, -ed2, ed2 ]
  18195. ];
  18196. for ( var i = 0, il = rays.length; i < il; i ++ ) {
  18197. var x = rays[ i ][ 0 ];
  18198. var y = rays[ i ][ 1 ];
  18199. var z = rays[ i ][ 2 ];
  18200. this.vertices.push( new THREE.Vector3( x, y, z ) );
  18201. }
  18202. };
  18203. THREE.AsteriskGeometry.prototype = Object.create( THREE.Geometry.prototype );/**
  18204. * @author hughes
  18205. */
  18206. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18207. THREE.Geometry.call( this );
  18208. radius = radius || 50;
  18209. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18210. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18211. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18212. var i, uvs = [],
  18213. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18214. this.vertices.push(center);
  18215. uvs.push( centerUV );
  18216. for ( i = 0; i <= segments; i ++ ) {
  18217. var vertex = new THREE.Vector3();
  18218. vertex.x = radius * Math.cos( thetaStart + i / segments * thetaLength );
  18219. vertex.y = radius * Math.sin( thetaStart + i / segments * thetaLength );
  18220. this.vertices.push( vertex );
  18221. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  18222. }
  18223. var n = new THREE.Vector3( 0, 0, -1 );
  18224. for ( i = 1; i <= segments; i ++ ) {
  18225. var v1 = i;
  18226. var v2 = i + 1 ;
  18227. var v3 = 0;
  18228. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  18229. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  18230. }
  18231. this.computeCentroids();
  18232. this.computeFaceNormals();
  18233. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18234. };
  18235. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18236. /**
  18237. * @author mrdoob / http://mrdoob.com/
  18238. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18239. */
  18240. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18241. THREE.Geometry.call( this );
  18242. var scope = this;
  18243. this.width = width;
  18244. this.height = height;
  18245. this.depth = depth;
  18246. this.widthSegments = widthSegments || 1;
  18247. this.heightSegments = heightSegments || 1;
  18248. this.depthSegments = depthSegments || 1;
  18249. var width_half = this.width / 2;
  18250. var height_half = this.height / 2;
  18251. var depth_half = this.depth / 2;
  18252. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  18253. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  18254. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  18255. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  18256. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  18257. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  18258. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18259. var w, ix, iy,
  18260. gridX = scope.widthSegments,
  18261. gridY = scope.heightSegments,
  18262. width_half = width / 2,
  18263. height_half = height / 2,
  18264. offset = scope.vertices.length;
  18265. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18266. w = 'z';
  18267. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18268. w = 'y';
  18269. gridY = scope.depthSegments;
  18270. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18271. w = 'x';
  18272. gridX = scope.depthSegments;
  18273. }
  18274. var gridX1 = gridX + 1,
  18275. gridY1 = gridY + 1,
  18276. segment_width = width / gridX,
  18277. segment_height = height / gridY,
  18278. normal = new THREE.Vector3();
  18279. normal[ w ] = depth > 0 ? 1 : - 1;
  18280. for ( iy = 0; iy < gridY1; iy ++ ) {
  18281. for ( ix = 0; ix < gridX1; ix ++ ) {
  18282. var vector = new THREE.Vector3();
  18283. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18284. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18285. vector[ w ] = depth;
  18286. scope.vertices.push( vector );
  18287. }
  18288. }
  18289. for ( iy = 0; iy < gridY; iy++ ) {
  18290. for ( ix = 0; ix < gridX; ix++ ) {
  18291. var a = ix + gridX1 * iy;
  18292. var b = ix + gridX1 * ( iy + 1 );
  18293. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18294. var d = ( ix + 1 ) + gridX1 * iy;
  18295. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  18296. face.normal.copy( normal );
  18297. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  18298. face.materialIndex = materialIndex;
  18299. scope.faces.push( face );
  18300. scope.faceVertexUvs[ 0 ].push( [
  18301. new THREE.Vector2( ix / gridX, 1 - iy / gridY ),
  18302. new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  18303. new THREE.Vector2( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  18304. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY )
  18305. ] );
  18306. }
  18307. }
  18308. }
  18309. this.computeCentroids();
  18310. this.mergeVertices();
  18311. };
  18312. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18313. /**
  18314. * @author mrdoob / http://mrdoob.com/
  18315. */
  18316. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radiusSegments, heightSegments, openEnded ) {
  18317. THREE.Geometry.call( this );
  18318. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18319. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18320. height = height !== undefined ? height : 100;
  18321. var heightHalf = height / 2;
  18322. var segmentsX = radiusSegments || 8;
  18323. var segmentsY = heightSegments || 1;
  18324. var x, y, vertices = [], uvs = [];
  18325. for ( y = 0; y <= segmentsY; y ++ ) {
  18326. var verticesRow = [];
  18327. var uvsRow = [];
  18328. var v = y / segmentsY;
  18329. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18330. for ( x = 0; x <= segmentsX; x ++ ) {
  18331. var u = x / segmentsX;
  18332. var vertex = new THREE.Vector3();
  18333. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  18334. vertex.y = - v * height + heightHalf;
  18335. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  18336. this.vertices.push( vertex );
  18337. verticesRow.push( this.vertices.length - 1 );
  18338. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  18339. }
  18340. vertices.push( verticesRow );
  18341. uvs.push( uvsRow );
  18342. }
  18343. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18344. var na, nb;
  18345. for ( x = 0; x < segmentsX; x ++ ) {
  18346. if ( radiusTop !== 0 ) {
  18347. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18348. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18349. } else {
  18350. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18351. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18352. }
  18353. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18354. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18355. for ( y = 0; y < segmentsY; y ++ ) {
  18356. var v1 = vertices[ y ][ x ];
  18357. var v2 = vertices[ y + 1 ][ x ];
  18358. var v3 = vertices[ y + 1 ][ x + 1 ];
  18359. var v4 = vertices[ y ][ x + 1 ];
  18360. var n1 = na.clone();
  18361. var n2 = na.clone();
  18362. var n3 = nb.clone();
  18363. var n4 = nb.clone();
  18364. var uv1 = uvs[ y ][ x ].clone();
  18365. var uv2 = uvs[ y + 1 ][ x ].clone();
  18366. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18367. var uv4 = uvs[ y ][ x + 1 ].clone();
  18368. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  18369. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  18370. }
  18371. }
  18372. // top cap
  18373. if ( !openEnded && radiusTop > 0 ) {
  18374. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18375. for ( x = 0; x < segmentsX; x ++ ) {
  18376. var v1 = vertices[ 0 ][ x ];
  18377. var v2 = vertices[ 0 ][ x + 1 ];
  18378. var v3 = this.vertices.length - 1;
  18379. var n1 = new THREE.Vector3( 0, 1, 0 );
  18380. var n2 = new THREE.Vector3( 0, 1, 0 );
  18381. var n3 = new THREE.Vector3( 0, 1, 0 );
  18382. var uv1 = uvs[ 0 ][ x ].clone();
  18383. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18384. var uv3 = new THREE.Vector2( uv2.u, 0 );
  18385. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18386. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18387. }
  18388. }
  18389. // bottom cap
  18390. if ( !openEnded && radiusBottom > 0 ) {
  18391. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18392. for ( x = 0; x < segmentsX; x ++ ) {
  18393. var v1 = vertices[ y ][ x + 1 ];
  18394. var v2 = vertices[ y ][ x ];
  18395. var v3 = this.vertices.length - 1;
  18396. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18397. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18398. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18399. var uv1 = uvs[ y ][ x + 1 ].clone();
  18400. var uv2 = uvs[ y ][ x ].clone();
  18401. var uv3 = new THREE.Vector2( uv2.u, 1 );
  18402. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18403. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18404. }
  18405. }
  18406. this.computeCentroids();
  18407. this.computeFaceNormals();
  18408. }
  18409. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18410. /**
  18411. * @author zz85 / http://www.lab4games.net/zz85/blog
  18412. *
  18413. * Creates extruded geometry from a path shape.
  18414. *
  18415. * parameters = {
  18416. *
  18417. * size: <float>, // size of the text
  18418. * height: <float>, // thickness to extrude text
  18419. * curveSegments: <int>, // number of points on the curves
  18420. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18421. * amount: <int>, // Amount
  18422. *
  18423. * bevelEnabled: <bool>, // turn on bevel
  18424. * bevelThickness: <float>, // how deep into text bevel goes
  18425. * bevelSize: <float>, // how far from text outline is bevel
  18426. * bevelSegments: <int>, // number of bevel layers
  18427. *
  18428. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18429. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18430. *
  18431. * material: <int> // material index for front and back faces
  18432. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18433. * uvGenerator: <Object> // object that provides UV generator functions
  18434. *
  18435. * }
  18436. **/
  18437. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18438. if ( typeof( shapes ) === "undefined" ) {
  18439. shapes = [];
  18440. return;
  18441. }
  18442. THREE.Geometry.call( this );
  18443. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18444. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18445. this.addShapeList( shapes, options );
  18446. this.computeCentroids();
  18447. this.computeFaceNormals();
  18448. // can't really use automatic vertex normals
  18449. // as then front and back sides get smoothed too
  18450. // should do separate smoothing just for sides
  18451. //this.computeVertexNormals();
  18452. //console.log( "took", ( Date.now() - startTime ) );
  18453. };
  18454. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18455. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18456. var sl = shapes.length;
  18457. for ( var s = 0; s < sl; s ++ ) {
  18458. var shape = shapes[ s ];
  18459. this.addShape( shape, options );
  18460. }
  18461. };
  18462. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18463. var amount = options.amount !== undefined ? options.amount : 100;
  18464. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18465. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18466. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18467. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18468. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18469. var steps = options.steps !== undefined ? options.steps : 1;
  18470. var extrudePath = options.extrudePath;
  18471. var extrudePts, extrudeByPath = false;
  18472. var material = options.material;
  18473. var extrudeMaterial = options.extrudeMaterial;
  18474. // Use default WorldUVGenerator if no UV generators are specified.
  18475. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18476. var shapebb = this.shapebb;
  18477. //shapebb = shape.getBoundingBox();
  18478. var splineTube, binormal, normal, position2;
  18479. if ( extrudePath ) {
  18480. extrudePts = extrudePath.getSpacedPoints( steps );
  18481. extrudeByPath = true;
  18482. bevelEnabled = false; // bevels not supported for path extrusion
  18483. // SETUP TNB variables
  18484. // Reuse TNB from TubeGeomtry for now.
  18485. // TODO1 - have a .isClosed in spline?
  18486. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18487. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18488. binormal = new THREE.Vector3();
  18489. normal = new THREE.Vector3();
  18490. position2 = new THREE.Vector3();
  18491. }
  18492. // Safeguards if bevels are not enabled
  18493. if ( ! bevelEnabled ) {
  18494. bevelSegments = 0;
  18495. bevelThickness = 0;
  18496. bevelSize = 0;
  18497. }
  18498. // Variables initalization
  18499. var ahole, h, hl; // looping of holes
  18500. var scope = this;
  18501. var bevelPoints = [];
  18502. var shapesOffset = this.vertices.length;
  18503. var shapePoints = shape.extractPoints( curveSegments );
  18504. var vertices = shapePoints.shape;
  18505. var holes = shapePoints.holes;
  18506. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  18507. if ( reverse ) {
  18508. vertices = vertices.reverse();
  18509. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18510. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18511. ahole = holes[ h ];
  18512. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18513. holes[ h ] = ahole.reverse();
  18514. }
  18515. }
  18516. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18517. }
  18518. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18519. /* Vertices */
  18520. var contour = vertices; // vertices has all points but contour has only points of circumference
  18521. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18522. ahole = holes[ h ];
  18523. vertices = vertices.concat( ahole );
  18524. }
  18525. function scalePt2 ( pt, vec, size ) {
  18526. if ( !vec ) console.log( "die" );
  18527. return vec.clone().multiplyScalar( size ).add( pt );
  18528. }
  18529. var b, bs, t, z,
  18530. vert, vlen = vertices.length,
  18531. face, flen = faces.length,
  18532. cont, clen = contour.length;
  18533. // Find directions for point movement
  18534. var RAD_TO_DEGREES = 180 / Math.PI;
  18535. function getBevelVec( pt_i, pt_j, pt_k ) {
  18536. // Algorithm 2
  18537. return getBevelVec2( pt_i, pt_j, pt_k );
  18538. }
  18539. function getBevelVec1( pt_i, pt_j, pt_k ) {
  18540. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  18541. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  18542. if ( anglea > angleb ) {
  18543. angleb += Math.PI * 2;
  18544. }
  18545. var anglec = ( anglea + angleb ) / 2;
  18546. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  18547. var x = - Math.cos( anglec );
  18548. var y = - Math.sin( anglec );
  18549. var vec = new THREE.Vector2( x, y ); //.normalize();
  18550. return vec;
  18551. }
  18552. function getBevelVec2( pt_i, pt_j, pt_k ) {
  18553. var a = THREE.ExtrudeGeometry.__v1,
  18554. b = THREE.ExtrudeGeometry.__v2,
  18555. v_hat = THREE.ExtrudeGeometry.__v3,
  18556. w_hat = THREE.ExtrudeGeometry.__v4,
  18557. p = THREE.ExtrudeGeometry.__v5,
  18558. q = THREE.ExtrudeGeometry.__v6,
  18559. v, w,
  18560. v_dot_w_hat, q_sub_p_dot_w_hat,
  18561. s, intersection;
  18562. // good reading for line-line intersection
  18563. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  18564. // define a as vector j->i
  18565. // define b as vectot k->i
  18566. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  18567. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  18568. // get unit vectors
  18569. v = a.normalize();
  18570. w = b.normalize();
  18571. // normals from pt i
  18572. v_hat.set( -v.y, v.x );
  18573. w_hat.set( w.y, -w.x );
  18574. // pts from i
  18575. p.copy( pt_i ).add( v_hat );
  18576. q.copy( pt_i ).add( w_hat );
  18577. if ( p.equals( q ) ) {
  18578. //console.log("Warning: lines are straight");
  18579. return w_hat.clone();
  18580. }
  18581. // Points from j, k. helps prevents points cross overover most of the time
  18582. p.copy( pt_j ).add( v_hat );
  18583. q.copy( pt_k ).add( w_hat );
  18584. v_dot_w_hat = v.dot( w_hat );
  18585. q_sub_p_dot_w_hat = q.sub( p ).dot( w_hat );
  18586. // We should not reach these conditions
  18587. if ( v_dot_w_hat === 0 ) {
  18588. console.log( "Either infinite or no solutions!" );
  18589. if ( q_sub_p_dot_w_hat === 0 ) {
  18590. console.log( "Its finite solutions." );
  18591. } else {
  18592. console.log( "Too bad, no solutions." );
  18593. }
  18594. }
  18595. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  18596. if ( s < 0 ) {
  18597. // in case of emergecy, revert to algorithm 1.
  18598. return getBevelVec1( pt_i, pt_j, pt_k );
  18599. }
  18600. intersection = v.multiplyScalar( s ).add( p );
  18601. return intersection.sub( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  18602. }
  18603. var contourMovements = [];
  18604. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18605. if ( j === il ) j = 0;
  18606. if ( k === il ) k = 0;
  18607. // (j)---(i)---(k)
  18608. // console.log('i,j,k', i, j , k)
  18609. var pt_i = contour[ i ];
  18610. var pt_j = contour[ j ];
  18611. var pt_k = contour[ k ];
  18612. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18613. }
  18614. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18615. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18616. ahole = holes[ h ];
  18617. oneHoleMovements = [];
  18618. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18619. if ( j === il ) j = 0;
  18620. if ( k === il ) k = 0;
  18621. // (j)---(i)---(k)
  18622. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18623. }
  18624. holesMovements.push( oneHoleMovements );
  18625. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18626. }
  18627. // Loop bevelSegments, 1 for the front, 1 for the back
  18628. for ( b = 0; b < bevelSegments; b ++ ) {
  18629. //for ( b = bevelSegments; b > 0; b -- ) {
  18630. t = b / bevelSegments;
  18631. z = bevelThickness * ( 1 - t );
  18632. //z = bevelThickness * t;
  18633. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  18634. //bs = bevelSize * t ; // linear
  18635. // contract shape
  18636. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18637. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18638. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  18639. v( vert.x, vert.y, - z );
  18640. }
  18641. // expand holes
  18642. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  18643. ahole = holes[ h ];
  18644. oneHoleMovements = holesMovements[ h ];
  18645. for ( i = 0, il = ahole.length; i < il; i++ ) {
  18646. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18647. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  18648. v( vert.x, vert.y, -z );
  18649. }
  18650. }
  18651. }
  18652. bs = bevelSize;
  18653. // Back facing vertices
  18654. for ( i = 0; i < vlen; i ++ ) {
  18655. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18656. if ( !extrudeByPath ) {
  18657. v( vert.x, vert.y, 0 );
  18658. } else {
  18659. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18660. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  18661. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  18662. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  18663. v( position2.x, position2.y, position2.z );
  18664. }
  18665. }
  18666. // Add stepped vertices...
  18667. // Including front facing vertices
  18668. var s;
  18669. for ( s = 1; s <= steps; s ++ ) {
  18670. for ( i = 0; i < vlen; i ++ ) {
  18671. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18672. if ( !extrudeByPath ) {
  18673. v( vert.x, vert.y, amount / steps * s );
  18674. } else {
  18675. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18676. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  18677. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  18678. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  18679. v( position2.x, position2.y, position2.z );
  18680. }
  18681. }
  18682. }
  18683. // Add bevel segments planes
  18684. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18685. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  18686. t = b / bevelSegments;
  18687. z = bevelThickness * ( 1 - t );
  18688. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  18689. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  18690. // contract shape
  18691. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18692. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18693. v( vert.x, vert.y, amount + z );
  18694. }
  18695. // expand holes
  18696. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18697. ahole = holes[ h ];
  18698. oneHoleMovements = holesMovements[ h ];
  18699. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18700. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18701. if ( !extrudeByPath ) {
  18702. v( vert.x, vert.y, amount + z );
  18703. } else {
  18704. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  18705. }
  18706. }
  18707. }
  18708. }
  18709. /* Faces */
  18710. // Top and bottom faces
  18711. buildLidFaces();
  18712. // Sides faces
  18713. buildSideFaces();
  18714. ///// Internal functions
  18715. function buildLidFaces() {
  18716. if ( bevelEnabled ) {
  18717. var layer = 0 ; // steps + 1
  18718. var offset = vlen * layer;
  18719. // Bottom faces
  18720. for ( i = 0; i < flen; i ++ ) {
  18721. face = faces[ i ];
  18722. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  18723. }
  18724. layer = steps + bevelSegments * 2;
  18725. offset = vlen * layer;
  18726. // Top faces
  18727. for ( i = 0; i < flen; i ++ ) {
  18728. face = faces[ i ];
  18729. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  18730. }
  18731. } else {
  18732. // Bottom faces
  18733. for ( i = 0; i < flen; i++ ) {
  18734. face = faces[ i ];
  18735. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  18736. }
  18737. // Top faces
  18738. for ( i = 0; i < flen; i ++ ) {
  18739. face = faces[ i ];
  18740. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  18741. }
  18742. }
  18743. }
  18744. // Create faces for the z-sides of the shape
  18745. function buildSideFaces() {
  18746. var layeroffset = 0;
  18747. sidewalls( contour, layeroffset );
  18748. layeroffset += contour.length;
  18749. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18750. ahole = holes[ h ];
  18751. sidewalls( ahole, layeroffset );
  18752. //, true
  18753. layeroffset += ahole.length;
  18754. }
  18755. }
  18756. function sidewalls( contour, layeroffset ) {
  18757. var j, k;
  18758. i = contour.length;
  18759. while ( --i >= 0 ) {
  18760. j = i;
  18761. k = i - 1;
  18762. if ( k < 0 ) k = contour.length - 1;
  18763. //console.log('b', i,j, i-1, k,vertices.length);
  18764. var s = 0, sl = steps + bevelSegments * 2;
  18765. for ( s = 0; s < sl; s ++ ) {
  18766. var slen1 = vlen * s;
  18767. var slen2 = vlen * ( s + 1 );
  18768. var a = layeroffset + j + slen1,
  18769. b = layeroffset + k + slen1,
  18770. c = layeroffset + k + slen2,
  18771. d = layeroffset + j + slen2;
  18772. f4( a, b, c, d, contour, s, sl, j, k );
  18773. }
  18774. }
  18775. }
  18776. function v( x, y, z ) {
  18777. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  18778. }
  18779. function f3( a, b, c, isBottom ) {
  18780. a += shapesOffset;
  18781. b += shapesOffset;
  18782. c += shapesOffset;
  18783. // normal, color, material
  18784. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18785. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  18786. scope.faceVertexUvs[ 0 ].push( uvs );
  18787. }
  18788. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  18789. a += shapesOffset;
  18790. b += shapesOffset;
  18791. c += shapesOffset;
  18792. d += shapesOffset;
  18793. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  18794. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  18795. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  18796. scope.faceVertexUvs[ 0 ].push( uvs );
  18797. }
  18798. };
  18799. THREE.ExtrudeGeometry.WorldUVGenerator = {
  18800. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18801. var ax = geometry.vertices[ indexA ].x,
  18802. ay = geometry.vertices[ indexA ].y,
  18803. bx = geometry.vertices[ indexB ].x,
  18804. by = geometry.vertices[ indexB ].y,
  18805. cx = geometry.vertices[ indexC ].x,
  18806. cy = geometry.vertices[ indexC ].y;
  18807. return [
  18808. new THREE.Vector2( ax, ay ),
  18809. new THREE.Vector2( bx, by ),
  18810. new THREE.Vector2( cx, cy )
  18811. ];
  18812. },
  18813. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18814. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  18815. },
  18816. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  18817. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  18818. contourIndex1, contourIndex2 ) {
  18819. var ax = geometry.vertices[ indexA ].x,
  18820. ay = geometry.vertices[ indexA ].y,
  18821. az = geometry.vertices[ indexA ].z,
  18822. bx = geometry.vertices[ indexB ].x,
  18823. by = geometry.vertices[ indexB ].y,
  18824. bz = geometry.vertices[ indexB ].z,
  18825. cx = geometry.vertices[ indexC ].x,
  18826. cy = geometry.vertices[ indexC ].y,
  18827. cz = geometry.vertices[ indexC ].z,
  18828. dx = geometry.vertices[ indexD ].x,
  18829. dy = geometry.vertices[ indexD ].y,
  18830. dz = geometry.vertices[ indexD ].z;
  18831. if ( Math.abs( ay - by ) < 0.01 ) {
  18832. return [
  18833. new THREE.Vector2( ax, 1 - az ),
  18834. new THREE.Vector2( bx, 1 - bz ),
  18835. new THREE.Vector2( cx, 1 - cz ),
  18836. new THREE.Vector2( dx, 1 - dz )
  18837. ];
  18838. } else {
  18839. return [
  18840. new THREE.Vector2( ay, 1 - az ),
  18841. new THREE.Vector2( by, 1 - bz ),
  18842. new THREE.Vector2( cy, 1 - cz ),
  18843. new THREE.Vector2( dy, 1 - dz )
  18844. ];
  18845. }
  18846. }
  18847. };
  18848. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  18849. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  18850. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  18851. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  18852. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  18853. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  18854. /**
  18855. * @author jonobr1 / http://jonobr1.com
  18856. *
  18857. * Creates a one-sided polygonal geometry from a path shape. Similar to
  18858. * ExtrudeGeometry.
  18859. *
  18860. * parameters = {
  18861. *
  18862. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  18863. *
  18864. * material: <int> // material index for front and back faces
  18865. * uvGenerator: <Object> // object that provides UV generator functions
  18866. *
  18867. * }
  18868. **/
  18869. THREE.ShapeGeometry = function ( shapes, options ) {
  18870. THREE.Geometry.call( this );
  18871. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  18872. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18873. this.addShapeList( shapes, options );
  18874. this.computeCentroids();
  18875. this.computeFaceNormals();
  18876. };
  18877. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18878. /**
  18879. * Add an array of shapes to THREE.ShapeGeometry.
  18880. */
  18881. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18882. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  18883. this.addShape( shapes[ i ], options );
  18884. }
  18885. return this;
  18886. };
  18887. /**
  18888. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  18889. */
  18890. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  18891. if ( options === undefined ) options = {};
  18892. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18893. var material = options.material;
  18894. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  18895. var shapebb = this.shapebb;
  18896. //
  18897. var i, l, hole, s;
  18898. var shapesOffset = this.vertices.length;
  18899. var shapePoints = shape.extractPoints( curveSegments );
  18900. var vertices = shapePoints.shape;
  18901. var holes = shapePoints.holes;
  18902. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  18903. if ( reverse ) {
  18904. vertices = vertices.reverse();
  18905. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  18906. for ( i = 0, l = holes.length; i < l; i++ ) {
  18907. hole = holes[ i ];
  18908. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  18909. holes[ i ] = hole.reverse();
  18910. }
  18911. }
  18912. reverse = false;
  18913. }
  18914. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  18915. // Vertices
  18916. var contour = vertices;
  18917. for ( i = 0, l = holes.length; i < l; i++ ) {
  18918. hole = holes[ i ];
  18919. vertices = vertices.concat( hole );
  18920. }
  18921. //
  18922. var vert, vlen = vertices.length;
  18923. var face, flen = faces.length;
  18924. var cont, clen = contour.length;
  18925. for ( i = 0; i < vlen; i++ ) {
  18926. vert = vertices[ i ];
  18927. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  18928. }
  18929. for ( i = 0; i < flen; i++ ) {
  18930. face = faces[ i ];
  18931. var a = face[ 0 ] + shapesOffset;
  18932. var b = face[ 1 ] + shapesOffset;
  18933. var c = face[ 2 ] + shapesOffset;
  18934. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18935. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  18936. }
  18937. };
  18938. /**
  18939. * @author astrodud / http://astrodud.isgreat.org/
  18940. * @author zz85 / https://github.com/zz85
  18941. * @author bhouston / http://exocortex.com
  18942. */
  18943. // points - to create a closed torus, one must use a set of points
  18944. // like so: [ a, b, c, d, a ], see first is the same as last.
  18945. // segments - the number of circumference segments to create
  18946. // phiStart - the starting radian
  18947. // phiLength - the radian (0 to 2*PI) range of the lathed section
  18948. // 2*pi is a closed lathe, less than 2PI is a portion.
  18949. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  18950. THREE.Geometry.call( this );
  18951. segments = segments || 12;
  18952. phiStart = phiStart || 0;
  18953. phiLength = phiLength || 2 * Math.PI;
  18954. var inversePointLength = 1.0 / ( points.length - 1 );
  18955. var inverseSegments = 1.0 / segments;
  18956. for ( var i = 0, il = segments; i <= il; i ++ ) {
  18957. var phi = phiStart + i * inverseSegments * phiLength;
  18958. var c = Math.cos( phi ),
  18959. s = Math.sin( phi );
  18960. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  18961. var pt = points[ j ];
  18962. var vertex = new THREE.Vector3();
  18963. vertex.x = c * pt.x - s * pt.y;
  18964. vertex.y = s * pt.x + c * pt.y;
  18965. vertex.z = pt.z;
  18966. this.vertices.push( vertex );
  18967. }
  18968. }
  18969. var np = points.length;
  18970. for ( var i = 0, il = segments; i < il; i ++ ) {
  18971. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  18972. var base = j + np * i;
  18973. var a = base;
  18974. var b = base + np;
  18975. var c = base + 1 + np;
  18976. var d = base + 1;
  18977. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18978. var u0 = i * inverseSegments;
  18979. var v0 = j * inversePointLength;
  18980. var u1 = u0 + inverseSegments;
  18981. var v1 = v0 + inversePointLength;
  18982. this.faceVertexUvs[ 0 ].push( [
  18983. new THREE.Vector2( u0, v0 ),
  18984. new THREE.Vector2( u1, v0 ),
  18985. new THREE.Vector2( u1, v1 ),
  18986. new THREE.Vector2( u0, v1 )
  18987. ] );
  18988. }
  18989. }
  18990. this.mergeVertices();
  18991. this.computeCentroids();
  18992. this.computeFaceNormals();
  18993. this.computeVertexNormals();
  18994. };
  18995. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18996. /**
  18997. * @author mrdoob / http://mrdoob.com/
  18998. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  18999. */
  19000. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19001. THREE.Geometry.call( this );
  19002. this.width = width;
  19003. this.height = height;
  19004. this.widthSegments = widthSegments || 1;
  19005. this.heightSegments = heightSegments || 1;
  19006. var ix, iz;
  19007. var width_half = width / 2;
  19008. var height_half = height / 2;
  19009. var gridX = this.widthSegments;
  19010. var gridZ = this.heightSegments;
  19011. var gridX1 = gridX + 1;
  19012. var gridZ1 = gridZ + 1;
  19013. var segment_width = this.width / gridX;
  19014. var segment_height = this.height / gridZ;
  19015. var normal = new THREE.Vector3( 0, 0, 1 );
  19016. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19017. for ( ix = 0; ix < gridX1; ix ++ ) {
  19018. var x = ix * segment_width - width_half;
  19019. var y = iz * segment_height - height_half;
  19020. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19021. }
  19022. }
  19023. for ( iz = 0; iz < gridZ; iz ++ ) {
  19024. for ( ix = 0; ix < gridX; ix ++ ) {
  19025. var a = ix + gridX1 * iz;
  19026. var b = ix + gridX1 * ( iz + 1 );
  19027. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19028. var d = ( ix + 1 ) + gridX1 * iz;
  19029. var face = new THREE.Face4( a, b, c, d );
  19030. face.normal.copy( normal );
  19031. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  19032. this.faces.push( face );
  19033. this.faceVertexUvs[ 0 ].push( [
  19034. new THREE.Vector2( ix / gridX, 1 - iz / gridZ ),
  19035. new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  19036. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  19037. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  19038. ] );
  19039. }
  19040. }
  19041. this.computeCentroids();
  19042. };
  19043. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19044. /**
  19045. * @author mrdoob / http://mrdoob.com/
  19046. */
  19047. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19048. THREE.Geometry.call( this );
  19049. this.radius = radius || 50;
  19050. this.widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19051. this.heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19052. phiStart = phiStart !== undefined ? phiStart : 0;
  19053. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19054. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19055. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19056. var x, y, vertices = [], uvs = [];
  19057. for ( y = 0; y <= this.heightSegments; y ++ ) {
  19058. var verticesRow = [];
  19059. var uvsRow = [];
  19060. for ( x = 0; x <= this.widthSegments; x ++ ) {
  19061. var u = x / this.widthSegments;
  19062. var v = y / this.heightSegments;
  19063. var vertex = new THREE.Vector3();
  19064. vertex.x = - this.radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19065. vertex.y = this.radius * Math.cos( thetaStart + v * thetaLength );
  19066. vertex.z = this.radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19067. this.vertices.push( vertex );
  19068. verticesRow.push( this.vertices.length - 1 );
  19069. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19070. }
  19071. vertices.push( verticesRow );
  19072. uvs.push( uvsRow );
  19073. }
  19074. for ( y = 0; y < this.heightSegments; y ++ ) {
  19075. for ( x = 0; x < this.widthSegments; x ++ ) {
  19076. var v1 = vertices[ y ][ x + 1 ];
  19077. var v2 = vertices[ y ][ x ];
  19078. var v3 = vertices[ y + 1 ][ x ];
  19079. var v4 = vertices[ y + 1 ][ x + 1 ];
  19080. var n1 = this.vertices[ v1 ].clone().normalize();
  19081. var n2 = this.vertices[ v2 ].clone().normalize();
  19082. var n3 = this.vertices[ v3 ].clone().normalize();
  19083. var n4 = this.vertices[ v4 ].clone().normalize();
  19084. var uv1 = uvs[ y ][ x + 1 ].clone();
  19085. var uv2 = uvs[ y ][ x ].clone();
  19086. var uv3 = uvs[ y + 1 ][ x ].clone();
  19087. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19088. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  19089. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19090. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19091. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  19092. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19093. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19094. } else {
  19095. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  19096. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  19097. }
  19098. }
  19099. }
  19100. this.computeCentroids();
  19101. this.computeFaceNormals();
  19102. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19103. };
  19104. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19105. /**
  19106. * @author zz85 / http://www.lab4games.net/zz85/blog
  19107. * @author alteredq / http://alteredqualia.com/
  19108. *
  19109. * For creating 3D text geometry in three.js
  19110. *
  19111. * Text = 3D Text
  19112. *
  19113. * parameters = {
  19114. * size: <float>, // size of the text
  19115. * height: <float>, // thickness to extrude text
  19116. * curveSegments: <int>, // number of points on the curves
  19117. *
  19118. * font: <string>, // font name
  19119. * weight: <string>, // font weight (normal, bold)
  19120. * style: <string>, // font style (normal, italics)
  19121. *
  19122. * bevelEnabled: <bool>, // turn on bevel
  19123. * bevelThickness: <float>, // how deep into text bevel goes
  19124. * bevelSize: <float>, // how far from text outline is bevel
  19125. * }
  19126. *
  19127. */
  19128. /* Usage Examples
  19129. // TextGeometry wrapper
  19130. var text3d = new TextGeometry( text, options );
  19131. // Complete manner
  19132. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19133. var text3d = new ExtrudeGeometry( textShapes, options );
  19134. */
  19135. THREE.TextGeometry = function ( text, parameters ) {
  19136. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19137. // translate parameters to ExtrudeGeometry API
  19138. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19139. // defaults
  19140. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19141. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19142. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19143. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19144. };
  19145. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19146. /**
  19147. * @author oosmoxiecode
  19148. * @author mrdoob / http://mrdoob.com/
  19149. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19150. */
  19151. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19152. THREE.Geometry.call( this );
  19153. var scope = this;
  19154. this.radius = radius || 100;
  19155. this.tube = tube || 40;
  19156. this.radialSegments = radialSegments || 8;
  19157. this.tubularSegments = tubularSegments || 6;
  19158. this.arc = arc || Math.PI * 2;
  19159. var center = new THREE.Vector3(), uvs = [], normals = [];
  19160. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  19161. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  19162. var u = i / this.tubularSegments * this.arc;
  19163. var v = j / this.radialSegments * Math.PI * 2;
  19164. center.x = this.radius * Math.cos( u );
  19165. center.y = this.radius * Math.sin( u );
  19166. var vertex = new THREE.Vector3();
  19167. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  19168. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  19169. vertex.z = this.tube * Math.sin( v );
  19170. this.vertices.push( vertex );
  19171. uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
  19172. normals.push( vertex.clone().sub( center ).normalize() );
  19173. }
  19174. }
  19175. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  19176. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  19177. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  19178. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19179. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  19180. var d = ( this.tubularSegments + 1 ) * j + i;
  19181. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  19182. face.normal.add( normals[ a ] );
  19183. face.normal.add( normals[ b ] );
  19184. face.normal.add( normals[ c ] );
  19185. face.normal.add( normals[ d ] );
  19186. face.normal.normalize();
  19187. this.faces.push( face );
  19188. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19189. }
  19190. }
  19191. this.computeCentroids();
  19192. };
  19193. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19194. /**
  19195. * @author oosmoxiecode
  19196. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19197. */
  19198. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19199. THREE.Geometry.call( this );
  19200. var scope = this;
  19201. this.radius = radius || 100;
  19202. this.tube = tube || 40;
  19203. this.radialSegments = radialSegments || 64;
  19204. this.tubularSegments = tubularSegments || 8;
  19205. this.p = p || 2;
  19206. this.q = q || 3;
  19207. this.heightScale = heightScale || 1;
  19208. this.grid = new Array( this.radialSegments );
  19209. var tang = new THREE.Vector3();
  19210. var n = new THREE.Vector3();
  19211. var bitan = new THREE.Vector3();
  19212. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19213. this.grid[ i ] = new Array( this.tubularSegments );
  19214. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19215. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  19216. var v = j / this.tubularSegments * 2 * Math.PI;
  19217. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  19218. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  19219. var cx, cy;
  19220. tang.subVectors( p2, p1 );
  19221. n.addVectors( p2, p1 );
  19222. bitan.crossVectors( tang, n );
  19223. n.crossVectors( bitan, tang );
  19224. bitan.normalize();
  19225. n.normalize();
  19226. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19227. cy = this.tube * Math.sin( v );
  19228. p1.x += cx * n.x + cy * bitan.x;
  19229. p1.y += cx * n.y + cy * bitan.y;
  19230. p1.z += cx * n.z + cy * bitan.z;
  19231. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  19232. }
  19233. }
  19234. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19235. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19236. var ip = ( i + 1 ) % this.radialSegments;
  19237. var jp = ( j + 1 ) % this.tubularSegments;
  19238. var a = this.grid[ i ][ j ];
  19239. var b = this.grid[ ip ][ j ];
  19240. var c = this.grid[ ip ][ jp ];
  19241. var d = this.grid[ i ][ jp ];
  19242. var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
  19243. var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  19244. var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19245. var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19246. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19247. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  19248. }
  19249. }
  19250. this.computeCentroids();
  19251. this.computeFaceNormals();
  19252. this.computeVertexNormals();
  19253. function vert( x, y, z ) {
  19254. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19255. }
  19256. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  19257. var cu = Math.cos( u );
  19258. var cv = Math.cos( v );
  19259. var su = Math.sin( u );
  19260. var quOverP = in_q / in_p * u;
  19261. var cs = Math.cos( quOverP );
  19262. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19263. var ty = radius * ( 2 + cs ) * su * 0.5;
  19264. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19265. return new THREE.Vector3( tx, ty, tz );
  19266. }
  19267. };
  19268. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19269. /**
  19270. * @author WestLangley / https://github.com/WestLangley
  19271. * @author zz85 / https://github.com/zz85
  19272. * @author miningold / https://github.com/miningold
  19273. *
  19274. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19275. *
  19276. * Creates a tube which extrudes along a 3d spline
  19277. *
  19278. * Uses parallel transport frames as described in
  19279. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19280. */
  19281. THREE.TubeGeometry = function( path, segments, radius, radiusSegments, closed, debug ) {
  19282. THREE.Geometry.call( this );
  19283. this.path = path;
  19284. this.segments = segments || 64;
  19285. this.radius = radius || 1;
  19286. this.radiusSegments = radiusSegments || 8;
  19287. this.closed = closed || false;
  19288. if ( debug ) this.debug = new THREE.Object3D();
  19289. this.grid = [];
  19290. var scope = this,
  19291. tangent,
  19292. normal,
  19293. binormal,
  19294. numpoints = this.segments + 1,
  19295. x, y, z,
  19296. tx, ty, tz,
  19297. u, v,
  19298. cx, cy,
  19299. pos, pos2 = new THREE.Vector3(),
  19300. i, j,
  19301. ip, jp,
  19302. a, b, c, d,
  19303. uva, uvb, uvc, uvd;
  19304. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  19305. tangents = frames.tangents,
  19306. normals = frames.normals,
  19307. binormals = frames.binormals;
  19308. // proxy internals
  19309. this.tangents = tangents;
  19310. this.normals = normals;
  19311. this.binormals = binormals;
  19312. function vert( x, y, z ) {
  19313. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19314. }
  19315. // consruct the grid
  19316. for ( i = 0; i < numpoints; i++ ) {
  19317. this.grid[ i ] = [];
  19318. u = i / ( numpoints - 1 );
  19319. pos = path.getPointAt( u );
  19320. tangent = tangents[ i ];
  19321. normal = normals[ i ];
  19322. binormal = binormals[ i ];
  19323. if ( this.debug ) {
  19324. this.debug.add( new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff ) );
  19325. this.debug.add( new THREE.ArrowHelper(normal, pos, radius, 0xff0000 ) );
  19326. this.debug.add( new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00 ) );
  19327. }
  19328. for ( j = 0; j < this.radiusSegments; j++ ) {
  19329. v = j / this.radiusSegments * 2 * Math.PI;
  19330. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19331. cy = this.radius * Math.sin( v );
  19332. pos2.copy( pos );
  19333. pos2.x += cx * normal.x + cy * binormal.x;
  19334. pos2.y += cx * normal.y + cy * binormal.y;
  19335. pos2.z += cx * normal.z + cy * binormal.z;
  19336. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  19337. }
  19338. }
  19339. // construct the mesh
  19340. for ( i = 0; i < this.segments; i++ ) {
  19341. for ( j = 0; j < this.radiusSegments; j++ ) {
  19342. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  19343. jp = (j + 1) % this.radiusSegments;
  19344. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  19345. b = this.grid[ ip ][ j ];
  19346. c = this.grid[ ip ][ jp ];
  19347. d = this.grid[ i ][ jp ];
  19348. uva = new THREE.Vector2( i / this.segments, j / this.radiusSegments );
  19349. uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radiusSegments );
  19350. uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radiusSegments );
  19351. uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radiusSegments );
  19352. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19353. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  19354. }
  19355. }
  19356. this.computeCentroids();
  19357. this.computeFaceNormals();
  19358. this.computeVertexNormals();
  19359. };
  19360. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19361. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19362. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  19363. var tangent = new THREE.Vector3(),
  19364. normal = new THREE.Vector3(),
  19365. binormal = new THREE.Vector3(),
  19366. tangents = [],
  19367. normals = [],
  19368. binormals = [],
  19369. vec = new THREE.Vector3(),
  19370. mat = new THREE.Matrix4(),
  19371. numpoints = segments + 1,
  19372. theta,
  19373. epsilon = 0.0001,
  19374. smallest,
  19375. tx, ty, tz,
  19376. i, u, v;
  19377. // expose internals
  19378. this.tangents = tangents;
  19379. this.normals = normals;
  19380. this.binormals = binormals;
  19381. // compute the tangent vectors for each segment on the path
  19382. for ( i = 0; i < numpoints; i++ ) {
  19383. u = i / ( numpoints - 1 );
  19384. tangents[ i ] = path.getTangentAt( u );
  19385. tangents[ i ].normalize();
  19386. }
  19387. initialNormal3();
  19388. function initialNormal1(lastBinormal) {
  19389. // fixed start binormal. Has dangers of 0 vectors
  19390. normals[ 0 ] = new THREE.Vector3();
  19391. binormals[ 0 ] = new THREE.Vector3();
  19392. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19393. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  19394. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19395. }
  19396. function initialNormal2() {
  19397. // This uses the Frenet-Serret formula for deriving binormal
  19398. var t2 = path.getTangentAt( epsilon );
  19399. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  19400. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  19401. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  19402. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19403. }
  19404. function initialNormal3() {
  19405. // select an initial normal vector perpenicular to the first tangent vector,
  19406. // and in the direction of the smallest tangent xyz component
  19407. normals[ 0 ] = new THREE.Vector3();
  19408. binormals[ 0 ] = new THREE.Vector3();
  19409. smallest = Number.MAX_VALUE;
  19410. tx = Math.abs( tangents[ 0 ].x );
  19411. ty = Math.abs( tangents[ 0 ].y );
  19412. tz = Math.abs( tangents[ 0 ].z );
  19413. if ( tx <= smallest ) {
  19414. smallest = tx;
  19415. normal.set( 1, 0, 0 );
  19416. }
  19417. if ( ty <= smallest ) {
  19418. smallest = ty;
  19419. normal.set( 0, 1, 0 );
  19420. }
  19421. if ( tz <= smallest ) {
  19422. normal.set( 0, 0, 1 );
  19423. }
  19424. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19425. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19426. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19427. }
  19428. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19429. for ( i = 1; i < numpoints; i++ ) {
  19430. normals[ i ] = normals[ i-1 ].clone();
  19431. binormals[ i ] = binormals[ i-1 ].clone();
  19432. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  19433. if ( vec.length() > epsilon ) {
  19434. vec.normalize();
  19435. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  19436. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19437. }
  19438. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19439. }
  19440. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19441. if ( closed ) {
  19442. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  19443. theta /= ( numpoints - 1 );
  19444. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  19445. theta = -theta;
  19446. }
  19447. for ( i = 1; i < numpoints; i++ ) {
  19448. // twist a little...
  19449. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19450. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19451. }
  19452. }
  19453. };
  19454. /**
  19455. * @author clockworkgeek / https://github.com/clockworkgeek
  19456. * @author timothypratley / https://github.com/timothypratley
  19457. */
  19458. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  19459. THREE.Geometry.call( this );
  19460. radius = radius || 1;
  19461. detail = detail || 0;
  19462. var that = this;
  19463. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  19464. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  19465. }
  19466. var midpoints = [], p = this.vertices;
  19467. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19468. make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );
  19469. }
  19470. this.mergeVertices();
  19471. // Apply radius
  19472. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19473. this.vertices[ i ].multiplyScalar( radius );
  19474. }
  19475. // Project vector onto sphere's surface
  19476. function prepare( vector ) {
  19477. var vertex = vector.normalize().clone();
  19478. vertex.index = that.vertices.push( vertex ) - 1;
  19479. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19480. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19481. var v = inclination( vector ) / Math.PI + 0.5;
  19482. vertex.uv = new THREE.Vector2( u, 1 - v );
  19483. return vertex;
  19484. }
  19485. // Approximate a curved face with recursively sub-divided triangles.
  19486. function make( v1, v2, v3, detail ) {
  19487. if ( detail < 1 ) {
  19488. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19489. face.centroid.add( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  19490. face.normal = face.centroid.clone().normalize();
  19491. that.faces.push( face );
  19492. var azi = azimuth( face.centroid );
  19493. that.faceVertexUvs[ 0 ].push( [
  19494. correctUV( v1.uv, v1, azi ),
  19495. correctUV( v2.uv, v2, azi ),
  19496. correctUV( v3.uv, v3, azi )
  19497. ] );
  19498. } else {
  19499. detail -= 1;
  19500. // split triangle into 4 smaller triangles
  19501. make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
  19502. make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
  19503. make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
  19504. make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant
  19505. }
  19506. }
  19507. function midpoint( v1, v2 ) {
  19508. if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
  19509. if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];
  19510. var mid = midpoints[ v1.index ][ v2.index ];
  19511. if ( mid === undefined ) {
  19512. // generate mean point and project to surface with prepare()
  19513. midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
  19514. new THREE.Vector3().addVectors( v1, v2 ).divideScalar( 2 )
  19515. );
  19516. }
  19517. return mid;
  19518. }
  19519. // Angle around the Y axis, counter-clockwise when looking from above.
  19520. function azimuth( vector ) {
  19521. return Math.atan2( vector.z, -vector.x );
  19522. }
  19523. // Angle above the XZ plane.
  19524. function inclination( vector ) {
  19525. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19526. }
  19527. // Texture fixing helper. Spheres have some odd behaviours.
  19528. function correctUV( uv, vector, azimuth ) {
  19529. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  19530. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  19531. return uv;
  19532. }
  19533. this.computeCentroids();
  19534. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19535. };
  19536. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19537. /**
  19538. * @author timothypratley / https://github.com/timothypratley
  19539. */
  19540. THREE.IcosahedronGeometry = function ( radius, detail ) {
  19541. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19542. var vertices = [
  19543. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  19544. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  19545. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  19546. ];
  19547. var faces = [
  19548. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  19549. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  19550. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  19551. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  19552. ];
  19553. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19554. };
  19555. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19556. /**
  19557. * @author timothypratley / https://github.com/timothypratley
  19558. */
  19559. THREE.OctahedronGeometry = function ( radius, detail ) {
  19560. var vertices = [
  19561. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  19562. ];
  19563. var faces = [
  19564. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  19565. ];
  19566. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19567. };
  19568. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19569. /**
  19570. * @author timothypratley / https://github.com/timothypratley
  19571. */
  19572. THREE.TetrahedronGeometry = function ( radius, detail ) {
  19573. var vertices = [
  19574. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  19575. ];
  19576. var faces = [
  19577. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  19578. ];
  19579. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19580. };
  19581. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19582. /**
  19583. * @author zz85 / https://github.com/zz85
  19584. * Parametric Surfaces Geometry
  19585. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  19586. *
  19587. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  19588. *
  19589. */
  19590. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  19591. THREE.Geometry.call( this );
  19592. var verts = this.vertices;
  19593. var faces = this.faces;
  19594. var uvs = this.faceVertexUvs[ 0 ];
  19595. useTris = (useTris === undefined) ? false : useTris;
  19596. var i, il, j, p;
  19597. var u, v;
  19598. var stackCount = stacks + 1;
  19599. var sliceCount = slices + 1;
  19600. for ( i = 0; i <= stacks; i ++ ) {
  19601. v = i / stacks;
  19602. for ( j = 0; j <= slices; j ++ ) {
  19603. u = j / slices;
  19604. p = func( u, v );
  19605. verts.push( p );
  19606. }
  19607. }
  19608. var a, b, c, d;
  19609. var uva, uvb, uvc, uvd;
  19610. for ( i = 0; i < stacks; i ++ ) {
  19611. for ( j = 0; j < slices; j ++ ) {
  19612. a = i * sliceCount + j;
  19613. b = i * sliceCount + j + 1;
  19614. c = (i + 1) * sliceCount + j;
  19615. d = (i + 1) * sliceCount + j + 1;
  19616. uva = new THREE.Vector2( j / slices, i / stacks );
  19617. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  19618. uvc = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  19619. uvd = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  19620. if ( useTris ) {
  19621. faces.push( new THREE.Face3( a, b, c ) );
  19622. faces.push( new THREE.Face3( b, d, c ) );
  19623. uvs.push( [ uva, uvb, uvc ] );
  19624. uvs.push( [ uvb, uvd, uvc ] );
  19625. } else {
  19626. faces.push( new THREE.Face4( a, b, d, c ) );
  19627. uvs.push( [ uva, uvb, uvd, uvc ] );
  19628. }
  19629. }
  19630. }
  19631. // console.log(this);
  19632. // magic bullet
  19633. // var diff = this.mergeVertices();
  19634. // console.log('removed ', diff, ' vertices by merging');
  19635. this.computeCentroids();
  19636. this.computeFaceNormals();
  19637. this.computeVertexNormals();
  19638. };
  19639. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19640. /**
  19641. * @author qiao / https://github.com/qiao
  19642. * @fileoverview This is a convex hull generator using the incremental method.
  19643. * The complexity is O(n^2) where n is the number of vertices.
  19644. * O(nlogn) algorithms do exist, but they are much more complicated.
  19645. *
  19646. * Benchmark:
  19647. *
  19648. * Platform: CPU: P7350 @2.00GHz Engine: V8
  19649. *
  19650. * Num Vertices Time(ms)
  19651. *
  19652. * 10 1
  19653. * 20 3
  19654. * 30 19
  19655. * 40 48
  19656. * 50 107
  19657. */
  19658. THREE.ConvexGeometry = function( vertices ) {
  19659. THREE.Geometry.call( this );
  19660. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  19661. for ( var i = 3; i < vertices.length; i++ ) {
  19662. addPoint( i );
  19663. }
  19664. function addPoint( vertexId ) {
  19665. var vertex = vertices[ vertexId ].clone();
  19666. var mag = vertex.length();
  19667. vertex.x += mag * randomOffset();
  19668. vertex.y += mag * randomOffset();
  19669. vertex.z += mag * randomOffset();
  19670. var hole = [];
  19671. for ( var f = 0; f < faces.length; ) {
  19672. var face = faces[ f ];
  19673. // for each face, if the vertex can see it,
  19674. // then we try to add the face's edges into the hole.
  19675. if ( visible( face, vertex ) ) {
  19676. for ( var e = 0; e < 3; e++ ) {
  19677. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  19678. var boundary = true;
  19679. // remove duplicated edges.
  19680. for ( var h = 0; h < hole.length; h++ ) {
  19681. if ( equalEdge( hole[ h ], edge ) ) {
  19682. hole[ h ] = hole[ hole.length - 1 ];
  19683. hole.pop();
  19684. boundary = false;
  19685. break;
  19686. }
  19687. }
  19688. if ( boundary ) {
  19689. hole.push( edge );
  19690. }
  19691. }
  19692. // remove faces[ f ]
  19693. faces[ f ] = faces[ faces.length - 1 ];
  19694. faces.pop();
  19695. } else { // not visible
  19696. f++;
  19697. }
  19698. }
  19699. // construct the new faces formed by the edges of the hole and the vertex
  19700. for ( var h = 0; h < hole.length; h++ ) {
  19701. faces.push( [
  19702. hole[ h ][ 0 ],
  19703. hole[ h ][ 1 ],
  19704. vertexId
  19705. ] );
  19706. }
  19707. }
  19708. /**
  19709. * Whether the face is visible from the vertex
  19710. */
  19711. function visible( face, vertex ) {
  19712. var va = vertices[ face[ 0 ] ];
  19713. var vb = vertices[ face[ 1 ] ];
  19714. var vc = vertices[ face[ 2 ] ];
  19715. var n = normal( va, vb, vc );
  19716. // distance from face to origin
  19717. var dist = n.dot( va );
  19718. return n.dot( vertex ) >= dist;
  19719. }
  19720. /**
  19721. * Face normal
  19722. */
  19723. function normal( va, vb, vc ) {
  19724. var cb = new THREE.Vector3();
  19725. var ab = new THREE.Vector3();
  19726. cb.subVectors( vc, vb );
  19727. ab.subVectors( va, vb );
  19728. cb.cross( ab );
  19729. cb.normalize();
  19730. return cb;
  19731. }
  19732. /**
  19733. * Detect whether two edges are equal.
  19734. * Note that when constructing the convex hull, two same edges can only
  19735. * be of the negative direction.
  19736. */
  19737. function equalEdge( ea, eb ) {
  19738. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  19739. }
  19740. /**
  19741. * Create a random offset between -1e-6 and 1e-6.
  19742. */
  19743. function randomOffset() {
  19744. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  19745. }
  19746. /**
  19747. * XXX: Not sure if this is the correct approach. Need someone to review.
  19748. */
  19749. function vertexUv( vertex ) {
  19750. var mag = vertex.length();
  19751. return new THREE.Vector2( vertex.x / mag, vertex.y / mag );
  19752. }
  19753. // Push vertices into `this.vertices`, skipping those inside the hull
  19754. var id = 0;
  19755. var newId = new Array( vertices.length ); // map from old vertex id to new id
  19756. for ( var i = 0; i < faces.length; i++ ) {
  19757. var face = faces[ i ];
  19758. for ( var j = 0; j < 3; j++ ) {
  19759. if ( newId[ face[ j ] ] === undefined ) {
  19760. newId[ face[ j ] ] = id++;
  19761. this.vertices.push( vertices[ face[ j ] ] );
  19762. }
  19763. face[ j ] = newId[ face[ j ] ];
  19764. }
  19765. }
  19766. // Convert faces into instances of THREE.Face3
  19767. for ( var i = 0; i < faces.length; i++ ) {
  19768. this.faces.push( new THREE.Face3(
  19769. faces[ i ][ 0 ],
  19770. faces[ i ][ 1 ],
  19771. faces[ i ][ 2 ]
  19772. ) );
  19773. }
  19774. // Compute UVs
  19775. for ( var i = 0; i < this.faces.length; i++ ) {
  19776. var face = this.faces[ i ];
  19777. this.faceVertexUvs[ 0 ].push( [
  19778. vertexUv( this.vertices[ face.a ] ),
  19779. vertexUv( this.vertices[ face.b ] ),
  19780. vertexUv( this.vertices[ face.c ])
  19781. ] );
  19782. }
  19783. this.computeCentroids();
  19784. this.computeFaceNormals();
  19785. this.computeVertexNormals();
  19786. };
  19787. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19788. /**
  19789. * @author sroucheray / http://sroucheray.org/
  19790. * @author mrdoob / http://mrdoob.com/
  19791. */
  19792. THREE.AxisHelper = function ( size ) {
  19793. var geometry = new THREE.Geometry();
  19794. geometry.vertices.push(
  19795. new THREE.Vector3(), new THREE.Vector3( size || 1, 0, 0 ),
  19796. new THREE.Vector3(), new THREE.Vector3( 0, size || 1, 0 ),
  19797. new THREE.Vector3(), new THREE.Vector3( 0, 0, size || 1 )
  19798. );
  19799. geometry.colors.push(
  19800. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  19801. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  19802. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  19803. );
  19804. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  19805. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  19806. };
  19807. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  19808. /**
  19809. * @author WestLangley / http://github.com/WestLangley
  19810. * @author zz85 / https://github.com/zz85
  19811. * @author bhouston / https://exocortex.com
  19812. *
  19813. * Creates an arrow for visualizing directions
  19814. *
  19815. * Parameters:
  19816. * dir - Vector3
  19817. * origin - Vector3
  19818. * length - Number
  19819. * hex - color in hex value
  19820. */
  19821. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  19822. THREE.Object3D.call( this );
  19823. if ( length === undefined ) length = 20;
  19824. if ( hex === undefined ) hex = 0xffff00;
  19825. var lineGeometry = new THREE.Geometry();
  19826. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  19827. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  19828. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  19829. this.add( this.line );
  19830. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  19831. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  19832. this.cone.position.set( 0, 1, 0 );
  19833. this.add( this.cone );
  19834. if ( origin instanceof THREE.Vector3 ) this.position = origin;
  19835. this.setDirection( dir );
  19836. this.setLength( length );
  19837. };
  19838. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  19839. THREE.ArrowHelper.prototype.setDirection = function ( dir ) {
  19840. var d = THREE.ArrowHelper.__v1.copy( dir ).normalize();
  19841. if ( d.y > 0.999 ) {
  19842. this.rotation.set( 0, 0, 0 );
  19843. } else if ( d.y < - 0.999 ) {
  19844. this.rotation.set( Math.PI, 0, 0 );
  19845. } else {
  19846. var axis = THREE.ArrowHelper.__v2.set( d.z, 0, - d.x ).normalize();
  19847. var radians = Math.acos( d.y );
  19848. var quaternion = THREE.ArrowHelper.__q1.setFromAxisAngle( axis, radians );
  19849. this.rotation.setEulerFromQuaternion( quaternion, this.eulerOrder );
  19850. }
  19851. };
  19852. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  19853. this.scale.set( length, length, length );
  19854. };
  19855. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  19856. this.line.material.color.setHex( hex );
  19857. this.cone.material.color.setHex( hex );
  19858. };
  19859. THREE.ArrowHelper.__v1 = new THREE.Vector3();
  19860. THREE.ArrowHelper.__v2 = new THREE.Vector3();
  19861. THREE.ArrowHelper.__q1 = new THREE.Quaternion();
  19862. /**
  19863. * @author alteredq / http://alteredqualia.com/
  19864. *
  19865. * - shows frustum, line of sight and up of the camera
  19866. * - suitable for fast updates
  19867. * - based on frustum visualization in lightgl.js shadowmap example
  19868. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  19869. */
  19870. THREE.CameraHelper = function ( camera ) {
  19871. THREE.Line.call( this );
  19872. var scope = this;
  19873. this.geometry = new THREE.Geometry();
  19874. this.material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  19875. this.type = THREE.LinePieces;
  19876. this.matrixWorld = camera.matrixWorld;
  19877. this.matrixAutoUpdate = false;
  19878. this.pointMap = {};
  19879. // colors
  19880. var hexFrustum = 0xffaa00;
  19881. var hexCone = 0xff0000;
  19882. var hexUp = 0x00aaff;
  19883. var hexTarget = 0xffffff;
  19884. var hexCross = 0x333333;
  19885. // near
  19886. addLine( "n1", "n2", hexFrustum );
  19887. addLine( "n2", "n4", hexFrustum );
  19888. addLine( "n4", "n3", hexFrustum );
  19889. addLine( "n3", "n1", hexFrustum );
  19890. // far
  19891. addLine( "f1", "f2", hexFrustum );
  19892. addLine( "f2", "f4", hexFrustum );
  19893. addLine( "f4", "f3", hexFrustum );
  19894. addLine( "f3", "f1", hexFrustum );
  19895. // sides
  19896. addLine( "n1", "f1", hexFrustum );
  19897. addLine( "n2", "f2", hexFrustum );
  19898. addLine( "n3", "f3", hexFrustum );
  19899. addLine( "n4", "f4", hexFrustum );
  19900. // cone
  19901. addLine( "p", "n1", hexCone );
  19902. addLine( "p", "n2", hexCone );
  19903. addLine( "p", "n3", hexCone );
  19904. addLine( "p", "n4", hexCone );
  19905. // up
  19906. addLine( "u1", "u2", hexUp );
  19907. addLine( "u2", "u3", hexUp );
  19908. addLine( "u3", "u1", hexUp );
  19909. // target
  19910. addLine( "c", "t", hexTarget );
  19911. addLine( "p", "c", hexCross );
  19912. // cross
  19913. addLine( "cn1", "cn2", hexCross );
  19914. addLine( "cn3", "cn4", hexCross );
  19915. addLine( "cf1", "cf2", hexCross );
  19916. addLine( "cf3", "cf4", hexCross );
  19917. this.camera = camera;
  19918. function addLine( a, b, hex ) {
  19919. addPoint( a, hex );
  19920. addPoint( b, hex );
  19921. }
  19922. function addPoint( id, hex ) {
  19923. scope.geometry.vertices.push( new THREE.Vector3() );
  19924. scope.geometry.colors.push( new THREE.Color( hex ) );
  19925. if ( scope.pointMap[ id ] === undefined ) scope.pointMap[ id ] = [];
  19926. scope.pointMap[ id ].push( scope.geometry.vertices.length - 1 );
  19927. }
  19928. this.update( camera );
  19929. };
  19930. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  19931. THREE.CameraHelper.prototype.update = function () {
  19932. var scope = this;
  19933. var w = 1, h = 1;
  19934. // we need just camera projection matrix
  19935. // world matrix must be identity
  19936. THREE.CameraHelper.__c.projectionMatrix.copy( this.camera.projectionMatrix );
  19937. // center / target
  19938. setPoint( "c", 0, 0, -1 );
  19939. setPoint( "t", 0, 0, 1 );
  19940. // near
  19941. setPoint( "n1", -w, -h, -1 );
  19942. setPoint( "n2", w, -h, -1 );
  19943. setPoint( "n3", -w, h, -1 );
  19944. setPoint( "n4", w, h, -1 );
  19945. // far
  19946. setPoint( "f1", -w, -h, 1 );
  19947. setPoint( "f2", w, -h, 1 );
  19948. setPoint( "f3", -w, h, 1 );
  19949. setPoint( "f4", w, h, 1 );
  19950. // up
  19951. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  19952. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  19953. setPoint( "u3", 0, h * 2, -1 );
  19954. // cross
  19955. setPoint( "cf1", -w, 0, 1 );
  19956. setPoint( "cf2", w, 0, 1 );
  19957. setPoint( "cf3", 0, -h, 1 );
  19958. setPoint( "cf4", 0, h, 1 );
  19959. setPoint( "cn1", -w, 0, -1 );
  19960. setPoint( "cn2", w, 0, -1 );
  19961. setPoint( "cn3", 0, -h, -1 );
  19962. setPoint( "cn4", 0, h, -1 );
  19963. function setPoint( point, x, y, z ) {
  19964. THREE.CameraHelper.__v.set( x, y, z );
  19965. THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
  19966. var points = scope.pointMap[ point ];
  19967. if ( points !== undefined ) {
  19968. for ( var i = 0, il = points.length; i < il; i ++ ) {
  19969. scope.geometry.vertices[ points[ i ] ].copy( THREE.CameraHelper.__v );
  19970. }
  19971. }
  19972. }
  19973. this.geometry.verticesNeedUpdate = true;
  19974. };
  19975. THREE.CameraHelper.__projector = new THREE.Projector();
  19976. THREE.CameraHelper.__v = new THREE.Vector3();
  19977. THREE.CameraHelper.__c = new THREE.Camera();
  19978. /**
  19979. * @author alteredq / http://alteredqualia.com/
  19980. *
  19981. * - shows directional light color, intensity, position, orientation and target
  19982. */
  19983. THREE.DirectionalLightHelper = function ( light, sphereSize ) {
  19984. THREE.Object3D.call( this );
  19985. this.light = light;
  19986. // position
  19987. this.position = light.position;
  19988. // direction
  19989. this.direction = new THREE.Vector3();
  19990. this.direction.subVectors( light.target.position, light.position );
  19991. // color
  19992. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  19993. this.color = light.color.clone();
  19994. this.color.multiplyScalar( intensity );
  19995. var hexColor = this.color.getHex();
  19996. // light helper
  19997. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  19998. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  19999. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20000. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20001. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20002. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20003. this.add( this.lightSphere );
  20004. this.add( this.lightRays );
  20005. this.lightSphere.properties.isGizmo = true;
  20006. this.lightSphere.properties.gizmoSubject = light;
  20007. this.lightSphere.properties.gizmoRoot = this;
  20008. // light target helper
  20009. this.targetSphere = null;
  20010. if ( light.target.properties.targetInverse !== undefined ) {
  20011. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  20012. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  20013. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  20014. this.targetSphere.position = light.target.position;
  20015. this.targetSphere.properties.isGizmo = true;
  20016. this.targetSphere.properties.gizmoSubject = light.target;
  20017. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  20018. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20019. var lineGeometry = new THREE.Geometry();
  20020. lineGeometry.vertices.push( this.position.clone() );
  20021. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  20022. lineGeometry.computeLineDistances();
  20023. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  20024. this.targetLine.properties.isGizmo = true;
  20025. }
  20026. //
  20027. this.properties.isGizmo = true;
  20028. }
  20029. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20030. THREE.DirectionalLightHelper.prototype.update = function () {
  20031. // update arrow orientation
  20032. // pointing from light to target
  20033. this.direction.subVectors( this.light.target.position, this.light.position );
  20034. // update arrow, spheres, rays and line colors to light color * light intensity
  20035. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20036. this.color.copy( this.light.color );
  20037. this.color.multiplyScalar( intensity );
  20038. this.lightSphere.material.color.copy( this.color );
  20039. this.lightRays.material.color.copy( this.color );
  20040. // Only update targetSphere and targetLine if available
  20041. if ( this.targetSphere !== null ) {
  20042. this.targetSphere.material.color.copy( this.color );
  20043. this.targetLine.material.color.copy( this.color );
  20044. // update target line vertices
  20045. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  20046. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  20047. this.targetLine.geometry.computeLineDistances();
  20048. this.targetLine.geometry.verticesNeedUpdate = true;
  20049. }
  20050. }
  20051. /**
  20052. * @author alteredq / http://alteredqualia.com/
  20053. *
  20054. * - shows hemisphere light intensity, sky and ground colors and directions
  20055. */
  20056. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  20057. THREE.Object3D.call( this );
  20058. this.light = light;
  20059. // position
  20060. this.position = light.position;
  20061. //
  20062. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20063. // sky color
  20064. this.color = light.color.clone();
  20065. this.color.multiplyScalar( intensity );
  20066. var hexColor = this.color.getHex();
  20067. // ground color
  20068. this.groundColor = light.groundColor.clone();
  20069. this.groundColor.multiplyScalar( intensity );
  20070. var hexColorGround = this.groundColor.getHex();
  20071. // double colored light bulb
  20072. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, 0, Math.PI * 0.5 );
  20073. var bulbGroundGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, Math.PI * 0.5, Math.PI );
  20074. var bulbSkyMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20075. var bulbGroundMaterial = new THREE.MeshBasicMaterial( { color: hexColorGround, fog: false } );
  20076. for ( var i = 0, il = bulbGeometry.faces.length; i < il; i ++ ) {
  20077. bulbGeometry.faces[ i ].materialIndex = 0;
  20078. }
  20079. for ( var i = 0, il = bulbGroundGeometry.faces.length; i < il; i ++ ) {
  20080. bulbGroundGeometry.faces[ i ].materialIndex = 1;
  20081. }
  20082. THREE.GeometryUtils.merge( bulbGeometry, bulbGroundGeometry );
  20083. this.lightSphere = new THREE.Mesh( bulbGeometry, new THREE.MeshFaceMaterial( [ bulbSkyMaterial, bulbGroundMaterial ] ) );
  20084. // arrows for sky and ground light directions
  20085. this.lightArrow = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * 1.1, 0 ), arrowLength, hexColor );
  20086. this.lightArrow.rotation.x = Math.PI;
  20087. this.lightArrowGround = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * -1.1, 0 ), arrowLength, hexColorGround );
  20088. var joint = new THREE.Object3D();
  20089. joint.rotation.x = -Math.PI * 0.5;
  20090. joint.add( this.lightSphere );
  20091. joint.add( this.lightArrow );
  20092. joint.add( this.lightArrowGround );
  20093. this.add( joint );
  20094. //
  20095. this.lightSphere.properties.isGizmo = true;
  20096. this.lightSphere.properties.gizmoSubject = light;
  20097. this.lightSphere.properties.gizmoRoot = this;
  20098. //
  20099. this.properties.isGizmo = true;
  20100. //
  20101. this.target = new THREE.Vector3();
  20102. this.lookAt( this.target );
  20103. }
  20104. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20105. THREE.HemisphereLightHelper.prototype.update = function () {
  20106. // update sphere sky and ground colors to light color * light intensity
  20107. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20108. this.color.copy( this.light.color );
  20109. this.color.multiplyScalar( intensity );
  20110. this.groundColor.copy( this.light.groundColor );
  20111. this.groundColor.multiplyScalar( intensity );
  20112. this.lightSphere.material.materials[ 0 ].color.copy( this.color );
  20113. this.lightSphere.material.materials[ 1 ].color.copy( this.groundColor );
  20114. this.lightArrow.setColor( this.color.getHex() );
  20115. this.lightArrowGround.setColor( this.groundColor.getHex() );
  20116. this.lookAt( this.target );
  20117. }
  20118. /**
  20119. * @author alteredq / http://alteredqualia.com/
  20120. *
  20121. * - shows point light color, intensity, position and distance
  20122. */
  20123. THREE.PointLightHelper = function ( light, sphereSize ) {
  20124. THREE.Object3D.call( this );
  20125. this.light = light;
  20126. // position
  20127. this.position = light.position;
  20128. // color
  20129. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20130. this.color = light.color.clone();
  20131. this.color.multiplyScalar( intensity );
  20132. var hexColor = this.color.getHex();
  20133. // light helper
  20134. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20135. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20136. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20137. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20138. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20139. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20140. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20141. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20142. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20143. var d = light.distance;
  20144. if ( d === 0.0 ) {
  20145. this.lightDistance.visible = false;
  20146. } else {
  20147. this.lightDistance.scale.set( d, d, d );
  20148. }
  20149. this.add( this.lightSphere );
  20150. this.add( this.lightRays );
  20151. this.add( this.lightDistance );
  20152. //
  20153. this.lightSphere.properties.isGizmo = true;
  20154. this.lightSphere.properties.gizmoSubject = light;
  20155. this.lightSphere.properties.gizmoRoot = this;
  20156. //
  20157. this.properties.isGizmo = true;
  20158. }
  20159. THREE.PointLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20160. THREE.PointLightHelper.prototype.update = function () {
  20161. // update sphere and rays colors to light color * light intensity
  20162. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20163. this.color.copy( this.light.color );
  20164. this.color.multiplyScalar( intensity );
  20165. this.lightSphere.material.color.copy( this.color );
  20166. this.lightRays.material.color.copy( this.color );
  20167. this.lightDistance.material.color.copy( this.color );
  20168. //
  20169. var d = this.light.distance;
  20170. if ( d === 0.0 ) {
  20171. this.lightDistance.visible = false;
  20172. } else {
  20173. this.lightDistance.visible = true;
  20174. this.lightDistance.scale.set( d, d, d );
  20175. }
  20176. }
  20177. /**
  20178. * @author alteredq / http://alteredqualia.com/
  20179. *
  20180. * - shows spot light color, intensity, position, orientation, light cone and target
  20181. */
  20182. THREE.SpotLightHelper = function ( light, sphereSize ) {
  20183. THREE.Object3D.call( this );
  20184. this.light = light;
  20185. // position
  20186. this.position = light.position;
  20187. // direction
  20188. this.direction = new THREE.Vector3();
  20189. this.direction.subVectors( light.target.position, light.position );
  20190. // color
  20191. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20192. this.color = light.color.clone();
  20193. this.color.multiplyScalar( intensity );
  20194. var hexColor = this.color.getHex();
  20195. // light helper
  20196. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20197. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20198. var coneGeometry = new THREE.CylinderGeometry( 0.0001, 1, 1, 8, 1, true );
  20199. var coneMatrix = new THREE.Matrix4();
  20200. coneMatrix.rotateX( -Math.PI/2 );
  20201. coneMatrix.translate( new THREE.Vector3( 0, -0.5, 0 ) );
  20202. coneGeometry.applyMatrix( coneMatrix );
  20203. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20204. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20205. var coneMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.3, transparent: true } );
  20206. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20207. this.lightCone = new THREE.Mesh( coneGeometry, coneMaterial );
  20208. var coneLength = light.distance ? light.distance : 10000;
  20209. var coneWidth = coneLength * Math.tan( light.angle * 0.5 ) * 2;
  20210. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  20211. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20212. this.gyroscope = new THREE.Gyroscope();
  20213. this.gyroscope.add( this.lightSphere );
  20214. this.gyroscope.add( this.lightRays );
  20215. this.add( this.gyroscope );
  20216. this.add( this.lightCone );
  20217. this.lookAt( light.target.position );
  20218. this.lightSphere.properties.isGizmo = true;
  20219. this.lightSphere.properties.gizmoSubject = light;
  20220. this.lightSphere.properties.gizmoRoot = this;
  20221. // light target helper
  20222. this.targetSphere = null;
  20223. if ( light.target.properties.targetInverse !== undefined ) {
  20224. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  20225. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  20226. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  20227. this.targetSphere.position = light.target.position;
  20228. this.targetSphere.properties.isGizmo = true;
  20229. this.targetSphere.properties.gizmoSubject = light.target;
  20230. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  20231. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20232. var lineGeometry = new THREE.Geometry();
  20233. lineGeometry.vertices.push( this.position.clone() );
  20234. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  20235. lineGeometry.computeLineDistances();
  20236. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  20237. this.targetLine.properties.isGizmo = true;
  20238. }
  20239. //
  20240. this.properties.isGizmo = true;
  20241. }
  20242. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20243. THREE.SpotLightHelper.prototype.update = function () {
  20244. // update arrow orientation
  20245. // pointing from light to target
  20246. this.direction.subVectors( this.light.target.position, this.light.position );
  20247. // update light cone orientation and size
  20248. this.lookAt( this.light.target.position );
  20249. var coneLength = this.light.distance ? this.light.distance : 10000;
  20250. var coneWidth = coneLength * Math.tan( this.light.angle * 0.5 ) * 2;
  20251. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  20252. // update arrow, spheres, rays and line colors to light color * light intensity
  20253. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20254. this.color.copy( this.light.color );
  20255. this.color.multiplyScalar( intensity );
  20256. this.lightSphere.material.color.copy( this.color );
  20257. this.lightRays.material.color.copy( this.color );
  20258. this.lightCone.material.color.copy( this.color );
  20259. // Only update targetSphere and targetLine if available
  20260. if ( this.targetSphere !== null ) {
  20261. this.targetSphere.material.color.copy( this.color );
  20262. this.targetLine.material.color.copy( this.color );
  20263. // update target line vertices
  20264. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  20265. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  20266. this.targetLine.geometry.computeLineDistances();
  20267. this.targetLine.geometry.verticesNeedUpdate = true;
  20268. }
  20269. };
  20270. /**
  20271. * @author alteredq / http://alteredqualia.com/
  20272. */
  20273. THREE.ImmediateRenderObject = function ( ) {
  20274. THREE.Object3D.call( this );
  20275. this.render = function ( renderCallback ) { };
  20276. };
  20277. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20278. /**
  20279. * @author mikael emtinger / http://gomo.se/
  20280. * @author alteredq / http://alteredqualia.com/
  20281. */
  20282. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20283. THREE.Object3D.call( this );
  20284. this.lensFlares = [];
  20285. this.positionScreen = new THREE.Vector3();
  20286. this.customUpdateCallback = undefined;
  20287. if( texture !== undefined ) {
  20288. this.add( texture, size, distance, blending, color );
  20289. }
  20290. };
  20291. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20292. /*
  20293. * Add: adds another flare
  20294. */
  20295. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20296. if( size === undefined ) size = -1;
  20297. if( distance === undefined ) distance = 0;
  20298. if( opacity === undefined ) opacity = 1;
  20299. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20300. if( blending === undefined ) blending = THREE.NormalBlending;
  20301. distance = Math.min( distance, Math.max( 0, distance ) );
  20302. this.lensFlares.push( { texture: texture, // THREE.Texture
  20303. size: size, // size in pixels (-1 = use texture.width)
  20304. distance: distance, // distance (0-1) from light source (0=at light source)
  20305. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20306. scale: 1, // scale
  20307. rotation: 1, // rotation
  20308. opacity: opacity, // opacity
  20309. color: color, // color
  20310. blending: blending } ); // blending
  20311. };
  20312. /*
  20313. * Update lens flares update positions on all flares based on the screen position
  20314. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20315. */
  20316. THREE.LensFlare.prototype.updateLensFlares = function () {
  20317. var f, fl = this.lensFlares.length;
  20318. var flare;
  20319. var vecX = -this.positionScreen.x * 2;
  20320. var vecY = -this.positionScreen.y * 2;
  20321. for( f = 0; f < fl; f ++ ) {
  20322. flare = this.lensFlares[ f ];
  20323. flare.x = this.positionScreen.x + vecX * flare.distance;
  20324. flare.y = this.positionScreen.y + vecY * flare.distance;
  20325. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20326. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20327. }
  20328. };
  20329. /**
  20330. * @author alteredq / http://alteredqualia.com/
  20331. */
  20332. THREE.MorphBlendMesh = function( geometry, material ) {
  20333. THREE.Mesh.call( this, geometry, material );
  20334. this.animationsMap = {};
  20335. this.animationsList = [];
  20336. // prepare default animation
  20337. // (all frames played together in 1 second)
  20338. var numFrames = this.geometry.morphTargets.length;
  20339. var name = "__default";
  20340. var startFrame = 0;
  20341. var endFrame = numFrames - 1;
  20342. var fps = numFrames / 1;
  20343. this.createAnimation( name, startFrame, endFrame, fps );
  20344. this.setAnimationWeight( name, 1 );
  20345. };
  20346. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20347. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20348. var animation = {
  20349. startFrame: start,
  20350. endFrame: end,
  20351. length: end - start + 1,
  20352. fps: fps,
  20353. duration: ( end - start ) / fps,
  20354. lastFrame: 0,
  20355. currentFrame: 0,
  20356. active: false,
  20357. time: 0,
  20358. direction: 1,
  20359. weight: 1,
  20360. directionBackwards: false,
  20361. mirroredLoop: false
  20362. };
  20363. this.animationsMap[ name ] = animation;
  20364. this.animationsList.push( animation );
  20365. };
  20366. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20367. var pattern = /([a-z]+)(\d+)/;
  20368. var firstAnimation, frameRanges = {};
  20369. var geometry = this.geometry;
  20370. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20371. var morph = geometry.morphTargets[ i ];
  20372. var chunks = morph.name.match( pattern );
  20373. if ( chunks && chunks.length > 1 ) {
  20374. var name = chunks[ 1 ];
  20375. var num = chunks[ 2 ];
  20376. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20377. var range = frameRanges[ name ];
  20378. if ( i < range.start ) range.start = i;
  20379. if ( i > range.end ) range.end = i;
  20380. if ( ! firstAnimation ) firstAnimation = name;
  20381. }
  20382. }
  20383. for ( var name in frameRanges ) {
  20384. var range = frameRanges[ name ];
  20385. this.createAnimation( name, range.start, range.end, fps );
  20386. }
  20387. this.firstAnimation = firstAnimation;
  20388. };
  20389. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20390. var animation = this.animationsMap[ name ];
  20391. if ( animation ) {
  20392. animation.direction = 1;
  20393. animation.directionBackwards = false;
  20394. }
  20395. };
  20396. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20397. var animation = this.animationsMap[ name ];
  20398. if ( animation ) {
  20399. animation.direction = -1;
  20400. animation.directionBackwards = true;
  20401. }
  20402. };
  20403. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20404. var animation = this.animationsMap[ name ];
  20405. if ( animation ) {
  20406. animation.fps = fps;
  20407. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20408. }
  20409. };
  20410. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20411. var animation = this.animationsMap[ name ];
  20412. if ( animation ) {
  20413. animation.duration = duration;
  20414. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20415. }
  20416. };
  20417. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20418. var animation = this.animationsMap[ name ];
  20419. if ( animation ) {
  20420. animation.weight = weight;
  20421. }
  20422. };
  20423. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20424. var animation = this.animationsMap[ name ];
  20425. if ( animation ) {
  20426. animation.time = time;
  20427. }
  20428. };
  20429. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20430. var time = 0;
  20431. var animation = this.animationsMap[ name ];
  20432. if ( animation ) {
  20433. time = animation.time;
  20434. }
  20435. return time;
  20436. };
  20437. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20438. var duration = -1;
  20439. var animation = this.animationsMap[ name ];
  20440. if ( animation ) {
  20441. duration = animation.duration;
  20442. }
  20443. return duration;
  20444. };
  20445. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20446. var animation = this.animationsMap[ name ];
  20447. if ( animation ) {
  20448. animation.time = 0;
  20449. animation.active = true;
  20450. } else {
  20451. console.warn( "animation[" + name + "] undefined" );
  20452. }
  20453. };
  20454. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20455. var animation = this.animationsMap[ name ];
  20456. if ( animation ) {
  20457. animation.active = false;
  20458. }
  20459. };
  20460. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20461. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20462. var animation = this.animationsList[ i ];
  20463. if ( ! animation.active ) continue;
  20464. var frameTime = animation.duration / animation.length;
  20465. animation.time += animation.direction * delta;
  20466. if ( animation.mirroredLoop ) {
  20467. if ( animation.time > animation.duration || animation.time < 0 ) {
  20468. animation.direction *= -1;
  20469. if ( animation.time > animation.duration ) {
  20470. animation.time = animation.duration;
  20471. animation.directionBackwards = true;
  20472. }
  20473. if ( animation.time < 0 ) {
  20474. animation.time = 0;
  20475. animation.directionBackwards = false;
  20476. }
  20477. }
  20478. } else {
  20479. animation.time = animation.time % animation.duration;
  20480. if ( animation.time < 0 ) animation.time += animation.duration;
  20481. }
  20482. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20483. var weight = animation.weight;
  20484. if ( keyframe !== animation.currentFrame ) {
  20485. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20486. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20487. this.morphTargetInfluences[ keyframe ] = 0;
  20488. animation.lastFrame = animation.currentFrame;
  20489. animation.currentFrame = keyframe;
  20490. }
  20491. var mix = ( animation.time % frameTime ) / frameTime;
  20492. if ( animation.directionBackwards ) mix = 1 - mix;
  20493. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  20494. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  20495. }
  20496. };
  20497. /**
  20498. * @author mikael emtinger / http://gomo.se/
  20499. * @author alteredq / http://alteredqualia.com/
  20500. */
  20501. THREE.LensFlarePlugin = function ( ) {
  20502. var _gl, _renderer, _precision, _lensFlare = {};
  20503. this.init = function ( renderer ) {
  20504. _gl = renderer.context;
  20505. _renderer = renderer;
  20506. _precision = renderer.getPrecision();
  20507. _lensFlare.vertices = new Float32Array( 8 + 8 );
  20508. _lensFlare.faces = new Uint16Array( 6 );
  20509. var i = 0;
  20510. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  20511. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  20512. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  20513. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  20514. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20515. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20516. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  20517. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  20518. i = 0;
  20519. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  20520. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  20521. // buffers
  20522. _lensFlare.vertexBuffer = _gl.createBuffer();
  20523. _lensFlare.elementBuffer = _gl.createBuffer();
  20524. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20525. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  20526. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20527. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  20528. // textures
  20529. _lensFlare.tempTexture = _gl.createTexture();
  20530. _lensFlare.occlusionTexture = _gl.createTexture();
  20531. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20532. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  20533. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20534. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20535. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20536. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20537. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20538. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  20539. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20540. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20541. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20542. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20543. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  20544. _lensFlare.hasVertexTexture = false;
  20545. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  20546. } else {
  20547. _lensFlare.hasVertexTexture = true;
  20548. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  20549. }
  20550. _lensFlare.attributes = {};
  20551. _lensFlare.uniforms = {};
  20552. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  20553. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  20554. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  20555. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  20556. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  20557. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  20558. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  20559. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  20560. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  20561. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  20562. };
  20563. /*
  20564. * Render lens flares
  20565. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  20566. * reads these back and calculates occlusion.
  20567. * Then _lensFlare.update_lensFlares() is called to re-position and
  20568. * update transparency of flares. Then they are rendered.
  20569. *
  20570. */
  20571. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20572. var flares = scene.__webglFlares,
  20573. nFlares = flares.length;
  20574. if ( ! nFlares ) return;
  20575. var tempPosition = new THREE.Vector3();
  20576. var invAspect = viewportHeight / viewportWidth,
  20577. halfViewportWidth = viewportWidth * 0.5,
  20578. halfViewportHeight = viewportHeight * 0.5;
  20579. var size = 16 / viewportHeight,
  20580. scale = new THREE.Vector2( size * invAspect, size );
  20581. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  20582. screenPositionPixels = new THREE.Vector2( 1, 1 );
  20583. var uniforms = _lensFlare.uniforms,
  20584. attributes = _lensFlare.attributes;
  20585. // set _lensFlare program and reset blending
  20586. _gl.useProgram( _lensFlare.program );
  20587. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  20588. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  20589. // loop through all lens flares to update their occlusion and positions
  20590. // setup gl and common used attribs/unforms
  20591. _gl.uniform1i( uniforms.occlusionMap, 0 );
  20592. _gl.uniform1i( uniforms.map, 1 );
  20593. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20594. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  20595. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  20596. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20597. _gl.disable( _gl.CULL_FACE );
  20598. _gl.depthMask( false );
  20599. var i, j, jl, flare, sprite;
  20600. for ( i = 0; i < nFlares; i ++ ) {
  20601. size = 16 / viewportHeight;
  20602. scale.set( size * invAspect, size );
  20603. // calc object screen position
  20604. flare = flares[ i ];
  20605. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  20606. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  20607. tempPosition.applyMatrix4( camera.projectionMatrix );
  20608. // setup arrays for gl programs
  20609. screenPosition.copy( tempPosition )
  20610. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  20611. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  20612. // screen cull
  20613. if ( _lensFlare.hasVertexTexture || (
  20614. screenPositionPixels.x > 0 &&
  20615. screenPositionPixels.x < viewportWidth &&
  20616. screenPositionPixels.y > 0 &&
  20617. screenPositionPixels.y < viewportHeight ) ) {
  20618. // save current RGB to temp texture
  20619. _gl.activeTexture( _gl.TEXTURE1 );
  20620. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20621. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20622. // render pink quad
  20623. _gl.uniform1i( uniforms.renderType, 0 );
  20624. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20625. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20626. _gl.disable( _gl.BLEND );
  20627. _gl.enable( _gl.DEPTH_TEST );
  20628. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20629. // copy result to occlusionMap
  20630. _gl.activeTexture( _gl.TEXTURE0 );
  20631. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20632. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20633. // restore graphics
  20634. _gl.uniform1i( uniforms.renderType, 1 );
  20635. _gl.disable( _gl.DEPTH_TEST );
  20636. _gl.activeTexture( _gl.TEXTURE1 );
  20637. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20638. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20639. // update object positions
  20640. flare.positionScreen.copy( screenPosition )
  20641. if ( flare.customUpdateCallback ) {
  20642. flare.customUpdateCallback( flare );
  20643. } else {
  20644. flare.updateLensFlares();
  20645. }
  20646. // render flares
  20647. _gl.uniform1i( uniforms.renderType, 2 );
  20648. _gl.enable( _gl.BLEND );
  20649. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  20650. sprite = flare.lensFlares[ j ];
  20651. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  20652. screenPosition.x = sprite.x;
  20653. screenPosition.y = sprite.y;
  20654. screenPosition.z = sprite.z;
  20655. size = sprite.size * sprite.scale / viewportHeight;
  20656. scale.x = size * invAspect;
  20657. scale.y = size;
  20658. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20659. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20660. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  20661. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  20662. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  20663. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  20664. _renderer.setTexture( sprite.texture, 1 );
  20665. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20666. }
  20667. }
  20668. }
  20669. }
  20670. // restore gl
  20671. _gl.enable( _gl.CULL_FACE );
  20672. _gl.enable( _gl.DEPTH_TEST );
  20673. _gl.depthMask( true );
  20674. };
  20675. function createProgram ( shader, precision ) {
  20676. var program = _gl.createProgram();
  20677. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  20678. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  20679. var prefix = "precision " + precision + " float;\n";
  20680. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  20681. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  20682. _gl.compileShader( fragmentShader );
  20683. _gl.compileShader( vertexShader );
  20684. _gl.attachShader( program, fragmentShader );
  20685. _gl.attachShader( program, vertexShader );
  20686. _gl.linkProgram( program );
  20687. return program;
  20688. };
  20689. };
  20690. /**
  20691. * @author alteredq / http://alteredqualia.com/
  20692. */
  20693. THREE.ShadowMapPlugin = function ( ) {
  20694. var _gl,
  20695. _renderer,
  20696. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  20697. _frustum = new THREE.Frustum(),
  20698. _projScreenMatrix = new THREE.Matrix4(),
  20699. _min = new THREE.Vector3(),
  20700. _max = new THREE.Vector3();
  20701. this.init = function ( renderer ) {
  20702. _gl = renderer.context;
  20703. _renderer = renderer;
  20704. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  20705. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  20706. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  20707. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  20708. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  20709. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  20710. _depthMaterial._shadowPass = true;
  20711. _depthMaterialMorph._shadowPass = true;
  20712. _depthMaterialSkin._shadowPass = true;
  20713. _depthMaterialMorphSkin._shadowPass = true;
  20714. };
  20715. this.render = function ( scene, camera ) {
  20716. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  20717. this.update( scene, camera );
  20718. };
  20719. this.update = function ( scene, camera ) {
  20720. var i, il, j, jl, n,
  20721. shadowMap, shadowMatrix, shadowCamera,
  20722. program, buffer, material,
  20723. webglObject, object, light,
  20724. renderList,
  20725. lights = [],
  20726. k = 0,
  20727. fog = null;
  20728. // set GL state for depth map
  20729. _gl.clearColor( 1, 1, 1, 1 );
  20730. _gl.disable( _gl.BLEND );
  20731. _gl.enable( _gl.CULL_FACE );
  20732. _gl.frontFace( _gl.CCW );
  20733. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  20734. _gl.cullFace( _gl.FRONT );
  20735. } else {
  20736. _gl.cullFace( _gl.BACK );
  20737. }
  20738. _renderer.setDepthTest( true );
  20739. // preprocess lights
  20740. // - skip lights that are not casting shadows
  20741. // - create virtual lights for cascaded shadow maps
  20742. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  20743. light = scene.__lights[ i ];
  20744. if ( ! light.castShadow ) continue;
  20745. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  20746. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  20747. var virtualLight;
  20748. if ( ! light.shadowCascadeArray[ n ] ) {
  20749. virtualLight = createVirtualLight( light, n );
  20750. virtualLight.originalCamera = camera;
  20751. var gyro = new THREE.Gyroscope();
  20752. gyro.position = light.shadowCascadeOffset;
  20753. gyro.add( virtualLight );
  20754. gyro.add( virtualLight.target );
  20755. camera.add( gyro );
  20756. light.shadowCascadeArray[ n ] = virtualLight;
  20757. console.log( "Created virtualLight", virtualLight );
  20758. } else {
  20759. virtualLight = light.shadowCascadeArray[ n ];
  20760. }
  20761. updateVirtualLight( light, n );
  20762. lights[ k ] = virtualLight;
  20763. k ++;
  20764. }
  20765. } else {
  20766. lights[ k ] = light;
  20767. k ++;
  20768. }
  20769. }
  20770. // render depth map
  20771. for ( i = 0, il = lights.length; i < il; i ++ ) {
  20772. light = lights[ i ];
  20773. if ( ! light.shadowMap ) {
  20774. var shadowFilter = THREE.LinearFilter;
  20775. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  20776. shadowFilter = THREE.NearestFilter;
  20777. }
  20778. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  20779. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  20780. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  20781. light.shadowMatrix = new THREE.Matrix4();
  20782. }
  20783. if ( ! light.shadowCamera ) {
  20784. if ( light instanceof THREE.SpotLight ) {
  20785. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  20786. } else if ( light instanceof THREE.DirectionalLight ) {
  20787. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  20788. } else {
  20789. console.error( "Unsupported light type for shadow" );
  20790. continue;
  20791. }
  20792. scene.add( light.shadowCamera );
  20793. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  20794. }
  20795. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  20796. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  20797. light.shadowCamera.add( light.cameraHelper );
  20798. }
  20799. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  20800. updateShadowCamera( camera, light );
  20801. }
  20802. shadowMap = light.shadowMap;
  20803. shadowMatrix = light.shadowMatrix;
  20804. shadowCamera = light.shadowCamera;
  20805. shadowCamera.position.copy( light.matrixWorld.getPosition() );
  20806. shadowCamera.lookAt( light.target.matrixWorld.getPosition() );
  20807. shadowCamera.updateMatrixWorld();
  20808. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  20809. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  20810. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  20811. // compute shadow matrix
  20812. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  20813. 0.0, 0.5, 0.0, 0.5,
  20814. 0.0, 0.0, 0.5, 0.5,
  20815. 0.0, 0.0, 0.0, 1.0 );
  20816. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  20817. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  20818. // update camera matrices and frustum
  20819. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  20820. _frustum.setFromMatrix( _projScreenMatrix );
  20821. // render shadow map
  20822. _renderer.setRenderTarget( shadowMap );
  20823. _renderer.clear();
  20824. // set object matrices & frustum culling
  20825. renderList = scene.__webglObjects;
  20826. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20827. webglObject = renderList[ j ];
  20828. object = webglObject.object;
  20829. webglObject.render = false;
  20830. if ( object.visible && object.castShadow ) {
  20831. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  20832. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  20833. webglObject.render = true;
  20834. }
  20835. }
  20836. }
  20837. // render regular objects
  20838. var objectMaterial, useMorphing, useSkinning;
  20839. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20840. webglObject = renderList[ j ];
  20841. if ( webglObject.render ) {
  20842. object = webglObject.object;
  20843. buffer = webglObject.buffer;
  20844. // culling is overriden globally for all objects
  20845. // while rendering depth map
  20846. // need to deal with MeshFaceMaterial somehow
  20847. // in that case just use the first of material.materials for now
  20848. // (proper solution would require to break objects by materials
  20849. // similarly to regular rendering and then set corresponding
  20850. // depth materials per each chunk instead of just once per object)
  20851. objectMaterial = getObjectMaterial( object );
  20852. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  20853. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  20854. if ( object.customDepthMaterial ) {
  20855. material = object.customDepthMaterial;
  20856. } else if ( useSkinning ) {
  20857. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  20858. } else if ( useMorphing ) {
  20859. material = _depthMaterialMorph;
  20860. } else {
  20861. material = _depthMaterial;
  20862. }
  20863. if ( buffer instanceof THREE.BufferGeometry ) {
  20864. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  20865. } else {
  20866. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  20867. }
  20868. }
  20869. }
  20870. // set matrices and render immediate objects
  20871. renderList = scene.__webglObjectsImmediate;
  20872. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20873. webglObject = renderList[ j ];
  20874. object = webglObject.object;
  20875. if ( object.visible && object.castShadow ) {
  20876. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  20877. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  20878. }
  20879. }
  20880. }
  20881. // restore GL state
  20882. var clearColor = _renderer.getClearColor(),
  20883. clearAlpha = _renderer.getClearAlpha();
  20884. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  20885. _gl.enable( _gl.BLEND );
  20886. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  20887. _gl.cullFace( _gl.BACK );
  20888. }
  20889. };
  20890. function createVirtualLight( light, cascade ) {
  20891. var virtualLight = new THREE.DirectionalLight();
  20892. virtualLight.isVirtual = true;
  20893. virtualLight.onlyShadow = true;
  20894. virtualLight.castShadow = true;
  20895. virtualLight.shadowCameraNear = light.shadowCameraNear;
  20896. virtualLight.shadowCameraFar = light.shadowCameraFar;
  20897. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  20898. virtualLight.shadowCameraRight = light.shadowCameraRight;
  20899. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  20900. virtualLight.shadowCameraTop = light.shadowCameraTop;
  20901. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  20902. virtualLight.shadowDarkness = light.shadowDarkness;
  20903. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  20904. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  20905. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  20906. virtualLight.pointsWorld = [];
  20907. virtualLight.pointsFrustum = [];
  20908. var pointsWorld = virtualLight.pointsWorld,
  20909. pointsFrustum = virtualLight.pointsFrustum;
  20910. for ( var i = 0; i < 8; i ++ ) {
  20911. pointsWorld[ i ] = new THREE.Vector3();
  20912. pointsFrustum[ i ] = new THREE.Vector3();
  20913. }
  20914. var nearZ = light.shadowCascadeNearZ[ cascade ];
  20915. var farZ = light.shadowCascadeFarZ[ cascade ];
  20916. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  20917. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  20918. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  20919. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  20920. pointsFrustum[ 4 ].set( -1, -1, farZ );
  20921. pointsFrustum[ 5 ].set( 1, -1, farZ );
  20922. pointsFrustum[ 6 ].set( -1, 1, farZ );
  20923. pointsFrustum[ 7 ].set( 1, 1, farZ );
  20924. return virtualLight;
  20925. }
  20926. // Synchronize virtual light with the original light
  20927. function updateVirtualLight( light, cascade ) {
  20928. var virtualLight = light.shadowCascadeArray[ cascade ];
  20929. virtualLight.position.copy( light.position );
  20930. virtualLight.target.position.copy( light.target.position );
  20931. virtualLight.lookAt( virtualLight.target );
  20932. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  20933. virtualLight.shadowDarkness = light.shadowDarkness;
  20934. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  20935. var nearZ = light.shadowCascadeNearZ[ cascade ];
  20936. var farZ = light.shadowCascadeFarZ[ cascade ];
  20937. var pointsFrustum = virtualLight.pointsFrustum;
  20938. pointsFrustum[ 0 ].z = nearZ;
  20939. pointsFrustum[ 1 ].z = nearZ;
  20940. pointsFrustum[ 2 ].z = nearZ;
  20941. pointsFrustum[ 3 ].z = nearZ;
  20942. pointsFrustum[ 4 ].z = farZ;
  20943. pointsFrustum[ 5 ].z = farZ;
  20944. pointsFrustum[ 6 ].z = farZ;
  20945. pointsFrustum[ 7 ].z = farZ;
  20946. }
  20947. // Fit shadow camera's ortho frustum to camera frustum
  20948. function updateShadowCamera( camera, light ) {
  20949. var shadowCamera = light.shadowCamera,
  20950. pointsFrustum = light.pointsFrustum,
  20951. pointsWorld = light.pointsWorld;
  20952. _min.set( Infinity, Infinity, Infinity );
  20953. _max.set( -Infinity, -Infinity, -Infinity );
  20954. for ( var i = 0; i < 8; i ++ ) {
  20955. var p = pointsWorld[ i ];
  20956. p.copy( pointsFrustum[ i ] );
  20957. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  20958. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  20959. if ( p.x < _min.x ) _min.x = p.x;
  20960. if ( p.x > _max.x ) _max.x = p.x;
  20961. if ( p.y < _min.y ) _min.y = p.y;
  20962. if ( p.y > _max.y ) _max.y = p.y;
  20963. if ( p.z < _min.z ) _min.z = p.z;
  20964. if ( p.z > _max.z ) _max.z = p.z;
  20965. }
  20966. shadowCamera.left = _min.x;
  20967. shadowCamera.right = _max.x;
  20968. shadowCamera.top = _max.y;
  20969. shadowCamera.bottom = _min.y;
  20970. // can't really fit near/far
  20971. //shadowCamera.near = _min.z;
  20972. //shadowCamera.far = _max.z;
  20973. shadowCamera.updateProjectionMatrix();
  20974. }
  20975. // For the moment just ignore objects that have multiple materials with different animation methods
  20976. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  20977. function getObjectMaterial( object ) {
  20978. return object.material instanceof THREE.MeshFaceMaterial
  20979. ? object.material.materials[ 0 ]
  20980. : object.material;
  20981. };
  20982. };
  20983. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  20984. /**
  20985. * @author mikael emtinger / http://gomo.se/
  20986. * @author alteredq / http://alteredqualia.com/
  20987. */
  20988. THREE.SpritePlugin = function ( ) {
  20989. var _gl, _renderer, _precision, _sprite = {};
  20990. this.init = function ( renderer ) {
  20991. _gl = renderer.context;
  20992. _renderer = renderer;
  20993. _precision = renderer.getPrecision();
  20994. _sprite.vertices = new Float32Array( 8 + 8 );
  20995. _sprite.faces = new Uint16Array( 6 );
  20996. var i = 0;
  20997. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  20998. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  20999. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  21000. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  21001. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  21002. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  21003. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  21004. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  21005. i = 0;
  21006. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  21007. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  21008. _sprite.vertexBuffer = _gl.createBuffer();
  21009. _sprite.elementBuffer = _gl.createBuffer();
  21010. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21011. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  21012. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21013. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  21014. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ], _precision );
  21015. _sprite.attributes = {};
  21016. _sprite.uniforms = {};
  21017. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  21018. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  21019. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  21020. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  21021. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  21022. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  21023. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  21024. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  21025. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  21026. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  21027. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  21028. _sprite.uniforms.sizeAttenuation = _gl.getUniformLocation( _sprite.program, "sizeAttenuation" );
  21029. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  21030. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  21031. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  21032. _sprite.uniforms.fogType = _gl.getUniformLocation( _sprite.program, "fogType" );
  21033. _sprite.uniforms.fogDensity = _gl.getUniformLocation( _sprite.program, "fogDensity" );
  21034. _sprite.uniforms.fogNear = _gl.getUniformLocation( _sprite.program, "fogNear" );
  21035. _sprite.uniforms.fogFar = _gl.getUniformLocation( _sprite.program, "fogFar" );
  21036. _sprite.uniforms.fogColor = _gl.getUniformLocation( _sprite.program, "fogColor" );
  21037. _sprite.uniforms.alphaTest = _gl.getUniformLocation( _sprite.program, "alphaTest" );
  21038. };
  21039. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21040. var sprites = scene.__webglSprites,
  21041. nSprites = sprites.length;
  21042. if ( ! nSprites ) return;
  21043. var attributes = _sprite.attributes,
  21044. uniforms = _sprite.uniforms;
  21045. var invAspect = viewportHeight / viewportWidth;
  21046. var halfViewportWidth = viewportWidth * 0.5,
  21047. halfViewportHeight = viewportHeight * 0.5;
  21048. // setup gl
  21049. _gl.useProgram( _sprite.program );
  21050. _gl.enableVertexAttribArray( attributes.position );
  21051. _gl.enableVertexAttribArray( attributes.uv );
  21052. _gl.disable( _gl.CULL_FACE );
  21053. _gl.enable( _gl.BLEND );
  21054. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21055. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21056. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21057. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21058. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  21059. _gl.activeTexture( _gl.TEXTURE0 );
  21060. _gl.uniform1i( uniforms.map, 0 );
  21061. var oldFogType = 0;
  21062. var sceneFogType = 0;
  21063. var fog = scene.fog;
  21064. if ( fog ) {
  21065. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  21066. if ( fog instanceof THREE.Fog ) {
  21067. _gl.uniform1f( uniforms.fogNear, fog.near );
  21068. _gl.uniform1f( uniforms.fogFar, fog.far );
  21069. _gl.uniform1i( uniforms.fogType, 1 );
  21070. oldFogType = 1;
  21071. sceneFogType = 1;
  21072. } else if ( fog instanceof THREE.FogExp2 ) {
  21073. _gl.uniform1f( uniforms.fogDensity, fog.density );
  21074. _gl.uniform1i( uniforms.fogType, 2 );
  21075. oldFogType = 2;
  21076. sceneFogType = 2;
  21077. }
  21078. } else {
  21079. _gl.uniform1i( uniforms.fogType, 0 );
  21080. oldFogType = 0;
  21081. sceneFogType = 0;
  21082. }
  21083. // update positions and sort
  21084. var i, sprite, material, screenPosition, size, fogType, scale = [];
  21085. for( i = 0; i < nSprites; i ++ ) {
  21086. sprite = sprites[ i ];
  21087. material = sprite.material;
  21088. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21089. if ( ! material.useScreenCoordinates ) {
  21090. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  21091. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  21092. } else {
  21093. sprite.z = - sprite.position.z;
  21094. }
  21095. }
  21096. sprites.sort( painterSortStable );
  21097. // render all sprites
  21098. for( i = 0; i < nSprites; i ++ ) {
  21099. sprite = sprites[ i ];
  21100. material = sprite.material;
  21101. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21102. if ( material.map && material.map.image && material.map.image.width ) {
  21103. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  21104. if ( material.useScreenCoordinates === true ) {
  21105. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  21106. _gl.uniform3f(
  21107. uniforms.screenPosition,
  21108. ( ( sprite.position.x * _renderer.devicePixelRatio ) - halfViewportWidth ) / halfViewportWidth,
  21109. ( halfViewportHeight - ( sprite.position.y * _renderer.devicePixelRatio ) ) / halfViewportHeight,
  21110. Math.max( 0, Math.min( 1, sprite.position.z ) )
  21111. );
  21112. scale[ 0 ] = _renderer.devicePixelRatio;
  21113. scale[ 1 ] = _renderer.devicePixelRatio;
  21114. } else {
  21115. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  21116. _gl.uniform1i( uniforms.sizeAttenuation, material.sizeAttenuation ? 1 : 0 );
  21117. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  21118. scale[ 0 ] = 1;
  21119. scale[ 1 ] = 1;
  21120. }
  21121. if ( scene.fog && material.fog ) {
  21122. fogType = sceneFogType;
  21123. } else {
  21124. fogType = 0;
  21125. }
  21126. if ( oldFogType !== fogType ) {
  21127. _gl.uniform1i( uniforms.fogType, fogType );
  21128. oldFogType = fogType;
  21129. }
  21130. size = 1 / ( material.scaleByViewport ? viewportHeight : 1 );
  21131. scale[ 0 ] *= size * invAspect * sprite.scale.x
  21132. scale[ 1 ] *= size * sprite.scale.y;
  21133. _gl.uniform2f( uniforms.uvScale, material.uvScale.x, material.uvScale.y );
  21134. _gl.uniform2f( uniforms.uvOffset, material.uvOffset.x, material.uvOffset.y );
  21135. _gl.uniform2f( uniforms.alignment, material.alignment.x, material.alignment.y );
  21136. _gl.uniform1f( uniforms.opacity, material.opacity );
  21137. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  21138. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21139. _gl.uniform2fv( uniforms.scale, scale );
  21140. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  21141. _renderer.setDepthTest( material.depthTest );
  21142. _renderer.setDepthWrite( material.depthWrite );
  21143. _renderer.setTexture( material.map, 0 );
  21144. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21145. }
  21146. }
  21147. // restore gl
  21148. _gl.enable( _gl.CULL_FACE );
  21149. };
  21150. function createProgram ( shader, precision ) {
  21151. var program = _gl.createProgram();
  21152. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21153. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21154. var prefix = "precision " + precision + " float;\n";
  21155. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21156. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21157. _gl.compileShader( fragmentShader );
  21158. _gl.compileShader( vertexShader );
  21159. _gl.attachShader( program, fragmentShader );
  21160. _gl.attachShader( program, vertexShader );
  21161. _gl.linkProgram( program );
  21162. return program;
  21163. };
  21164. function painterSortStable ( a, b ) {
  21165. if ( a.z !== b.z ) {
  21166. return b.z - a.z;
  21167. } else {
  21168. return b.id - a.id;
  21169. }
  21170. };
  21171. };
  21172. /**
  21173. * @author alteredq / http://alteredqualia.com/
  21174. */
  21175. THREE.DepthPassPlugin = function ( ) {
  21176. this.enabled = false;
  21177. this.renderTarget = null;
  21178. var _gl,
  21179. _renderer,
  21180. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21181. _frustum = new THREE.Frustum(),
  21182. _projScreenMatrix = new THREE.Matrix4();
  21183. this.init = function ( renderer ) {
  21184. _gl = renderer.context;
  21185. _renderer = renderer;
  21186. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21187. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21188. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21189. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21190. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21191. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21192. _depthMaterial._shadowPass = true;
  21193. _depthMaterialMorph._shadowPass = true;
  21194. _depthMaterialSkin._shadowPass = true;
  21195. _depthMaterialMorphSkin._shadowPass = true;
  21196. };
  21197. this.render = function ( scene, camera ) {
  21198. if ( ! this.enabled ) return;
  21199. this.update( scene, camera );
  21200. };
  21201. this.update = function ( scene, camera ) {
  21202. var i, il, j, jl, n,
  21203. program, buffer, material,
  21204. webglObject, object, light,
  21205. renderList,
  21206. fog = null;
  21207. // set GL state for depth map
  21208. _gl.clearColor( 1, 1, 1, 1 );
  21209. _gl.disable( _gl.BLEND );
  21210. _renderer.setDepthTest( true );
  21211. // update scene
  21212. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21213. // update camera matrices and frustum
  21214. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21215. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  21216. _frustum.setFromMatrix( _projScreenMatrix );
  21217. // render depth map
  21218. _renderer.setRenderTarget( this.renderTarget );
  21219. _renderer.clear();
  21220. // set object matrices & frustum culling
  21221. renderList = scene.__webglObjects;
  21222. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21223. webglObject = renderList[ j ];
  21224. object = webglObject.object;
  21225. webglObject.render = false;
  21226. if ( object.visible ) {
  21227. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21228. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21229. webglObject.render = true;
  21230. }
  21231. }
  21232. }
  21233. // render regular objects
  21234. var objectMaterial, useMorphing, useSkinning;
  21235. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21236. webglObject = renderList[ j ];
  21237. if ( webglObject.render ) {
  21238. object = webglObject.object;
  21239. buffer = webglObject.buffer;
  21240. // todo: create proper depth material for particles
  21241. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  21242. objectMaterial = getObjectMaterial( object );
  21243. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  21244. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21245. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21246. if ( object.customDepthMaterial ) {
  21247. material = object.customDepthMaterial;
  21248. } else if ( useSkinning ) {
  21249. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21250. } else if ( useMorphing ) {
  21251. material = _depthMaterialMorph;
  21252. } else {
  21253. material = _depthMaterial;
  21254. }
  21255. if ( buffer instanceof THREE.BufferGeometry ) {
  21256. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21257. } else {
  21258. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21259. }
  21260. }
  21261. }
  21262. // set matrices and render immediate objects
  21263. renderList = scene.__webglObjectsImmediate;
  21264. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21265. webglObject = renderList[ j ];
  21266. object = webglObject.object;
  21267. if ( object.visible ) {
  21268. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21269. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21270. }
  21271. }
  21272. // restore GL state
  21273. var clearColor = _renderer.getClearColor(),
  21274. clearAlpha = _renderer.getClearAlpha();
  21275. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21276. _gl.enable( _gl.BLEND );
  21277. };
  21278. // For the moment just ignore objects that have multiple materials with different animation methods
  21279. // Only the first material will be taken into account for deciding which depth material to use
  21280. function getObjectMaterial( object ) {
  21281. return object.material instanceof THREE.MeshFaceMaterial
  21282. ? object.material.materials[ 0 ]
  21283. : object.material;
  21284. };
  21285. };
  21286. /**
  21287. * @author mikael emtinger / http://gomo.se/
  21288. *
  21289. */
  21290. THREE.ShaderFlares = {
  21291. 'lensFlareVertexTexture': {
  21292. vertexShader: [
  21293. "uniform lowp int renderType;",
  21294. "uniform vec3 screenPosition;",
  21295. "uniform vec2 scale;",
  21296. "uniform float rotation;",
  21297. "uniform sampler2D occlusionMap;",
  21298. "attribute vec2 position;",
  21299. "attribute vec2 uv;",
  21300. "varying vec2 vUV;",
  21301. "varying float vVisibility;",
  21302. "void main() {",
  21303. "vUV = uv;",
  21304. "vec2 pos = position;",
  21305. "if( renderType == 2 ) {",
  21306. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  21307. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  21308. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  21309. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  21310. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  21311. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  21312. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  21313. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  21314. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21315. "vVisibility = ( visibility.r / 9.0 ) *",
  21316. "( 1.0 - visibility.g / 9.0 ) *",
  21317. "( visibility.b / 9.0 ) *",
  21318. "( 1.0 - visibility.a / 9.0 );",
  21319. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21320. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21321. "}",
  21322. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21323. "}"
  21324. ].join( "\n" ),
  21325. fragmentShader: [
  21326. "uniform lowp int renderType;",
  21327. "uniform sampler2D map;",
  21328. "uniform float opacity;",
  21329. "uniform vec3 color;",
  21330. "varying vec2 vUV;",
  21331. "varying float vVisibility;",
  21332. "void main() {",
  21333. // pink square
  21334. "if( renderType == 0 ) {",
  21335. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21336. // restore
  21337. "} else if( renderType == 1 ) {",
  21338. "gl_FragColor = texture2D( map, vUV );",
  21339. // flare
  21340. "} else {",
  21341. "vec4 texture = texture2D( map, vUV );",
  21342. "texture.a *= opacity * vVisibility;",
  21343. "gl_FragColor = texture;",
  21344. "gl_FragColor.rgb *= color;",
  21345. "}",
  21346. "}"
  21347. ].join( "\n" )
  21348. },
  21349. 'lensFlare': {
  21350. vertexShader: [
  21351. "uniform lowp int renderType;",
  21352. "uniform vec3 screenPosition;",
  21353. "uniform vec2 scale;",
  21354. "uniform float rotation;",
  21355. "attribute vec2 position;",
  21356. "attribute vec2 uv;",
  21357. "varying vec2 vUV;",
  21358. "void main() {",
  21359. "vUV = uv;",
  21360. "vec2 pos = position;",
  21361. "if( renderType == 2 ) {",
  21362. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21363. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21364. "}",
  21365. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21366. "}"
  21367. ].join( "\n" ),
  21368. fragmentShader: [
  21369. "precision mediump float;",
  21370. "uniform lowp int renderType;",
  21371. "uniform sampler2D map;",
  21372. "uniform sampler2D occlusionMap;",
  21373. "uniform float opacity;",
  21374. "uniform vec3 color;",
  21375. "varying vec2 vUV;",
  21376. "void main() {",
  21377. // pink square
  21378. "if( renderType == 0 ) {",
  21379. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  21380. // restore
  21381. "} else if( renderType == 1 ) {",
  21382. "gl_FragColor = texture2D( map, vUV );",
  21383. // flare
  21384. "} else {",
  21385. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  21386. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  21387. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  21388. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  21389. "visibility = ( 1.0 - visibility / 4.0 );",
  21390. "vec4 texture = texture2D( map, vUV );",
  21391. "texture.a *= opacity * visibility;",
  21392. "gl_FragColor = texture;",
  21393. "gl_FragColor.rgb *= color;",
  21394. "}",
  21395. "}"
  21396. ].join( "\n" )
  21397. }
  21398. };
  21399. /**
  21400. * @author mikael emtinger / http://gomo.se/
  21401. * @author alteredq / http://alteredqualia.com/
  21402. *
  21403. */
  21404. THREE.ShaderSprite = {
  21405. 'sprite': {
  21406. vertexShader: [
  21407. "uniform int useScreenCoordinates;",
  21408. "uniform int sizeAttenuation;",
  21409. "uniform vec3 screenPosition;",
  21410. "uniform mat4 modelViewMatrix;",
  21411. "uniform mat4 projectionMatrix;",
  21412. "uniform float rotation;",
  21413. "uniform vec2 scale;",
  21414. "uniform vec2 alignment;",
  21415. "uniform vec2 uvOffset;",
  21416. "uniform vec2 uvScale;",
  21417. "attribute vec2 position;",
  21418. "attribute vec2 uv;",
  21419. "varying vec2 vUV;",
  21420. "void main() {",
  21421. "vUV = uvOffset + uv * uvScale;",
  21422. "vec2 alignedPosition = position + alignment;",
  21423. "vec2 rotatedPosition;",
  21424. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  21425. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  21426. "vec4 finalPosition;",
  21427. "if( useScreenCoordinates != 0 ) {",
  21428. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  21429. "} else {",
  21430. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  21431. "finalPosition.xy += rotatedPosition * ( sizeAttenuation == 1 ? 1.0 : finalPosition.z );",
  21432. "}",
  21433. "gl_Position = finalPosition;",
  21434. "}"
  21435. ].join( "\n" ),
  21436. fragmentShader: [
  21437. "uniform vec3 color;",
  21438. "uniform sampler2D map;",
  21439. "uniform float opacity;",
  21440. "uniform int fogType;",
  21441. "uniform vec3 fogColor;",
  21442. "uniform float fogDensity;",
  21443. "uniform float fogNear;",
  21444. "uniform float fogFar;",
  21445. "uniform float alphaTest;",
  21446. "varying vec2 vUV;",
  21447. "void main() {",
  21448. "vec4 texture = texture2D( map, vUV );",
  21449. "if ( texture.a < alphaTest ) discard;",
  21450. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  21451. "if ( fogType > 0 ) {",
  21452. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  21453. "float fogFactor = 0.0;",
  21454. "if ( fogType == 1 ) {",
  21455. "fogFactor = smoothstep( fogNear, fogFar, depth );",
  21456. "} else {",
  21457. "const float LOG2 = 1.442695;",
  21458. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  21459. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  21460. "}",
  21461. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  21462. "}",
  21463. "}"
  21464. ].join( "\n" )
  21465. }
  21466. };
粤ICP备19079148号