three.js 792 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772
  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 : new THREE.Vector2( Infinity, Infinity );
  1311. this.max = ( max !== undefined ) ? max : 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 : new THREE.Vector3( Infinity, Infinity, Infinity );
  1454. this.max = ( max !== undefined ) ? max : 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 : new THREE.Vector3();
  2479. this.direction = ( direction !== undefined ) ? direction : 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 ) ? center : new THREE.Vector3();
  2569. this.radius = ( radius !== undefined ) ? radius : 0;
  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. return new THREE.Frustum().copy( this );
  2723. }
  2724. };
  2725. /**
  2726. * @author bhouston / http://exocortex.com
  2727. */
  2728. THREE.Plane = function ( normal, constant ) {
  2729. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  2730. this.constant = ( constant !== undefined ) ? constant : 0;
  2731. };
  2732. THREE.Plane.prototype = {
  2733. constructor: THREE.Plane,
  2734. set: function ( normal, constant ) {
  2735. this.normal.copy( normal );
  2736. this.constant = constant;
  2737. return this;
  2738. },
  2739. setComponents: function ( x, y, z, w ) {
  2740. this.normal.set( x, y, z );
  2741. this.constant = w;
  2742. return this;
  2743. },
  2744. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  2745. this.normal.copy( normal ).normalize();
  2746. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  2747. return this;
  2748. },
  2749. setFromCoplanarPoints: function ( a, b, c ) {
  2750. var normal = THREE.Plane.__v1.subVectors( c, b ).cross( THREE.Plane.__v2.subVectors( a, b ) ).normalize();
  2751. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  2752. this.setFromNormalAndCoplanarPoint( normal, a );
  2753. return this;
  2754. },
  2755. copy: function ( plane ) {
  2756. this.normal.copy( plane.normal );
  2757. this.constant = plane.constant;
  2758. return this;
  2759. },
  2760. normalize: function () {
  2761. // Note: will lead to a divide by zero if the plane is invalid.
  2762. var inverseNormalLength = 1.0 / this.normal.length();
  2763. this.normal.multiplyScalar( inverseNormalLength );
  2764. this.constant *= inverseNormalLength;
  2765. return this;
  2766. },
  2767. negate: function () {
  2768. this.constant *= -1;
  2769. this.normal.negate();
  2770. return this;
  2771. },
  2772. distanceToPoint: function ( point ) {
  2773. return this.normal.dot( point ) + this.constant;
  2774. },
  2775. distanceToSphere: function ( sphere ) {
  2776. return this.distanceToPoint( sphere.center ) - sphere.radius;
  2777. },
  2778. projectPoint: function ( point, optionalTarget ) {
  2779. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  2780. },
  2781. orthoPoint: function ( point, optionalTarget ) {
  2782. var perpendicularMagnitude = this.distanceToPoint( point );
  2783. var result = optionalTarget || new THREE.Vector3();
  2784. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  2785. },
  2786. isIntersectionLine: function ( startPoint, endPoint ) {
  2787. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  2788. var startSign = this.distanceToPoint( startPoint );
  2789. var endSign = this.distanceToPoint( endPoint );
  2790. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  2791. },
  2792. intersectLine: function ( startPoint, endPoint, optionalTarget ) {
  2793. var result = optionalTarget || new THREE.Vector3();
  2794. var direction = THREE.Plane.__v1.subVectors( endPoint, startPoint );
  2795. var denominator = this.normal.dot( direction );
  2796. if ( denominator == 0 ) {
  2797. // line is coplanar, return origin
  2798. if( this.distanceToPoint( startPoint ) == 0 ) {
  2799. return result.copy( startPoint );
  2800. }
  2801. // Unsure if this is the correct method to handle this case.
  2802. return undefined;
  2803. }
  2804. var t = - ( startPoint.dot( this.normal ) + this.constant ) / denominator;
  2805. if( t < 0 || t > 1 ) {
  2806. return undefined;
  2807. }
  2808. return result.copy( direction ).multiplyScalar( t ).add( startPoint );
  2809. },
  2810. coplanarPoint: function ( optionalTarget ) {
  2811. var result = optionalTarget || new THREE.Vector3();
  2812. return result.copy( this.normal ).multiplyScalar( - this.constant );
  2813. },
  2814. transform: function ( matrix, optionalNormalMatrix ) {
  2815. // compute new normal based on theory here:
  2816. // http://www.songho.ca/opengl/gl_normaltransform.html
  2817. optionalNormalMatrix = optionalNormalMatrix || new THREE.Matrix3().getInverse( matrix ).transpose();
  2818. var newNormal = THREE.Plane.__v1.copy( this.normal ).applyMatrix3( optionalNormalMatrix );
  2819. var newCoplanarPoint = this.coplanarPoint( THREE.Plane.__v2 );
  2820. newCoplanarPoint.applyMatrix4( matrix );
  2821. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  2822. return this;
  2823. },
  2824. translate: function ( offset ) {
  2825. this.constant = this.constant - offset.dot( this.normal );
  2826. return this;
  2827. },
  2828. equals: function ( plane ) {
  2829. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  2830. },
  2831. clone: function () {
  2832. return new THREE.Plane().copy( this );
  2833. }
  2834. };
  2835. THREE.Plane.__vZero = new THREE.Vector3( 0, 0, 0 );
  2836. THREE.Plane.__v1 = new THREE.Vector3();
  2837. THREE.Plane.__v2 = new THREE.Vector3();
  2838. /**
  2839. * @author alteredq / http://alteredqualia.com/
  2840. */
  2841. THREE.Math = {
  2842. // Clamp value to range <a, b>
  2843. clamp: function ( x, a, b ) {
  2844. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  2845. },
  2846. // Clamp value to range <a, inf)
  2847. clampBottom: function ( x, a ) {
  2848. return x < a ? a : x;
  2849. },
  2850. // Linear mapping from range <a1, a2> to range <b1, b2>
  2851. mapLinear: function ( x, a1, a2, b1, b2 ) {
  2852. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  2853. },
  2854. // Random float from <0, 1> with 16 bits of randomness
  2855. // (standard Math.random() creates repetitive patterns when applied over larger space)
  2856. random16: function () {
  2857. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  2858. },
  2859. // Random integer from <low, high> interval
  2860. randInt: function ( low, high ) {
  2861. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  2862. },
  2863. // Random float from <low, high> interval
  2864. randFloat: function ( low, high ) {
  2865. return low + Math.random() * ( high - low );
  2866. },
  2867. // Random float from <-range/2, range/2> interval
  2868. randFloatSpread: function ( range ) {
  2869. return range * ( 0.5 - Math.random() );
  2870. },
  2871. sign: function ( x ) {
  2872. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  2873. },
  2874. degToRad: function ( degrees ) {
  2875. return degrees * THREE.Math.__d2r;
  2876. },
  2877. radToDeg: function ( radians ) {
  2878. return radians * THREE.Math.__r2d;
  2879. }
  2880. };
  2881. THREE.Math.__d2r = Math.PI / 180;
  2882. THREE.Math.__r2d = 180 / Math.PI;
  2883. /**
  2884. * @author mikael emtinger / http://gomo.se/
  2885. * @author alteredq / http://alteredqualia.com/
  2886. * @author WestLangley / http://github.com/WestLangley
  2887. * @author bhouston / http://exocortex.com
  2888. */
  2889. THREE.Quaternion = function( x, y, z, w ) {
  2890. this.x = x || 0;
  2891. this.y = y || 0;
  2892. this.z = z || 0;
  2893. this.w = ( w !== undefined ) ? w : 1;
  2894. };
  2895. THREE.Quaternion.prototype = {
  2896. constructor: THREE.Quaternion,
  2897. set: function ( x, y, z, w ) {
  2898. this.x = x;
  2899. this.y = y;
  2900. this.z = z;
  2901. this.w = w;
  2902. return this;
  2903. },
  2904. copy: function ( q ) {
  2905. this.x = q.x;
  2906. this.y = q.y;
  2907. this.z = q.z;
  2908. this.w = q.w;
  2909. return this;
  2910. },
  2911. setFromEuler: function ( v, order ) {
  2912. // http://www.mathworks.com/matlabcentral/fileexchange/
  2913. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2914. // content/SpinCalc.m
  2915. var c1 = Math.cos( v.x / 2 );
  2916. var c2 = Math.cos( v.y / 2 );
  2917. var c3 = Math.cos( v.z / 2 );
  2918. var s1 = Math.sin( v.x / 2 );
  2919. var s2 = Math.sin( v.y / 2 );
  2920. var s3 = Math.sin( v.z / 2 );
  2921. if ( order === undefined || order === 'XYZ' ) {
  2922. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2923. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2924. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2925. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2926. } else if ( order === 'YXZ' ) {
  2927. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2928. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2929. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2930. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2931. } else if ( order === 'ZXY' ) {
  2932. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2933. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2934. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2935. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2936. } else if ( order === 'ZYX' ) {
  2937. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2938. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2939. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2940. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2941. } else if ( order === 'YZX' ) {
  2942. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2943. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2944. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2945. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2946. } else if ( order === 'XZY' ) {
  2947. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2948. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2949. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2950. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2951. }
  2952. return this;
  2953. },
  2954. setFromAxisAngle: function ( axis, angle ) {
  2955. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2956. // axis have to be normalized
  2957. var halfAngle = angle / 2,
  2958. s = Math.sin( halfAngle );
  2959. this.x = axis.x * s;
  2960. this.y = axis.y * s;
  2961. this.z = axis.z * s;
  2962. this.w = Math.cos( halfAngle );
  2963. return this;
  2964. },
  2965. setFromRotationMatrix: function ( m ) {
  2966. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2967. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2968. var te = m.elements,
  2969. m11 = te[0], m12 = te[4], m13 = te[8],
  2970. m21 = te[1], m22 = te[5], m23 = te[9],
  2971. m31 = te[2], m32 = te[6], m33 = te[10],
  2972. trace = m11 + m22 + m33,
  2973. s;
  2974. if ( trace > 0 ) {
  2975. s = 0.5 / Math.sqrt( trace + 1.0 );
  2976. this.w = 0.25 / s;
  2977. this.x = ( m32 - m23 ) * s;
  2978. this.y = ( m13 - m31 ) * s;
  2979. this.z = ( m21 - m12 ) * s;
  2980. } else if ( m11 > m22 && m11 > m33 ) {
  2981. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2982. this.w = (m32 - m23 ) / s;
  2983. this.x = 0.25 * s;
  2984. this.y = (m12 + m21 ) / s;
  2985. this.z = (m13 + m31 ) / s;
  2986. } else if ( m22 > m33 ) {
  2987. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2988. this.w = (m13 - m31 ) / s;
  2989. this.x = (m12 + m21 ) / s;
  2990. this.y = 0.25 * s;
  2991. this.z = (m23 + m32 ) / s;
  2992. } else {
  2993. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2994. this.w = ( m21 - m12 ) / s;
  2995. this.x = ( m13 + m31 ) / s;
  2996. this.y = ( m23 + m32 ) / s;
  2997. this.z = 0.25 * s;
  2998. }
  2999. return this;
  3000. },
  3001. inverse: function () {
  3002. this.conjugate().normalize();
  3003. return this;
  3004. },
  3005. conjugate: function () {
  3006. this.x *= -1;
  3007. this.y *= -1;
  3008. this.z *= -1;
  3009. return this;
  3010. },
  3011. lengthSq: function () {
  3012. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  3013. },
  3014. length: function () {
  3015. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  3016. },
  3017. normalize: function () {
  3018. var l = this.length();
  3019. if ( l === 0 ) {
  3020. this.x = 0;
  3021. this.y = 0;
  3022. this.z = 0;
  3023. this.w = 1;
  3024. } else {
  3025. l = 1 / l;
  3026. this.x = this.x * l;
  3027. this.y = this.y * l;
  3028. this.z = this.z * l;
  3029. this.w = this.w * l;
  3030. }
  3031. return this;
  3032. },
  3033. multiply: function ( q, p ) {
  3034. if ( p !== undefined ) {
  3035. console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  3036. return this.multiplyQuaternions( q, p );
  3037. }
  3038. return this.multiplyQuaternions( this, q );
  3039. },
  3040. multiplyQuaternions: function ( a, b ) {
  3041. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  3042. var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w;
  3043. var qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  3044. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  3045. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  3046. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  3047. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  3048. return this;
  3049. },
  3050. slerp: function ( qb, t ) {
  3051. var x = this.x, y = this.y, z = this.z, w = this.w;
  3052. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  3053. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  3054. if ( cosHalfTheta < 0 ) {
  3055. this.w = -qb.w;
  3056. this.x = -qb.x;
  3057. this.y = -qb.y;
  3058. this.z = -qb.z;
  3059. cosHalfTheta = -cosHalfTheta;
  3060. } else {
  3061. this.copy( qb );
  3062. }
  3063. if ( cosHalfTheta >= 1.0 ) {
  3064. this.w = w;
  3065. this.x = x;
  3066. this.y = y;
  3067. this.z = z;
  3068. return this;
  3069. }
  3070. var halfTheta = Math.acos( cosHalfTheta );
  3071. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  3072. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  3073. this.w = 0.5 * ( w + this.w );
  3074. this.x = 0.5 * ( x + this.x );
  3075. this.y = 0.5 * ( y + this.y );
  3076. this.z = 0.5 * ( z + this.z );
  3077. return this;
  3078. }
  3079. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  3080. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  3081. this.w = ( w * ratioA + this.w * ratioB );
  3082. this.x = ( x * ratioA + this.x * ratioB );
  3083. this.y = ( y * ratioA + this.y * ratioB );
  3084. this.z = ( z * ratioA + this.z * ratioB );
  3085. return this;
  3086. },
  3087. equals: function ( v ) {
  3088. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  3089. },
  3090. clone: function () {
  3091. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  3092. }
  3093. }
  3094. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  3095. return qm.copy( qa ).slerp( qb, t );
  3096. }
  3097. /**
  3098. * Spline from Tween.js, slightly optimized (and trashed)
  3099. * http://sole.github.com/tween.js/examples/05_spline.html
  3100. *
  3101. * @author mrdoob / http://mrdoob.com/
  3102. * @author alteredq / http://alteredqualia.com/
  3103. */
  3104. THREE.Spline = function ( points ) {
  3105. this.points = points;
  3106. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3107. point, intPoint, weight, w2, w3,
  3108. pa, pb, pc, pd;
  3109. this.initFromArray = function( a ) {
  3110. this.points = [];
  3111. for ( var i = 0; i < a.length; i++ ) {
  3112. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3113. }
  3114. };
  3115. this.getPoint = function ( k ) {
  3116. point = ( this.points.length - 1 ) * k;
  3117. intPoint = Math.floor( point );
  3118. weight = point - intPoint;
  3119. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3120. c[ 1 ] = intPoint;
  3121. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3122. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3123. pa = this.points[ c[ 0 ] ];
  3124. pb = this.points[ c[ 1 ] ];
  3125. pc = this.points[ c[ 2 ] ];
  3126. pd = this.points[ c[ 3 ] ];
  3127. w2 = weight * weight;
  3128. w3 = weight * w2;
  3129. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3130. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3131. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3132. return v3;
  3133. };
  3134. this.getControlPointsArray = function () {
  3135. var i, p, l = this.points.length,
  3136. coords = [];
  3137. for ( i = 0; i < l; i ++ ) {
  3138. p = this.points[ i ];
  3139. coords[ i ] = [ p.x, p.y, p.z ];
  3140. }
  3141. return coords;
  3142. };
  3143. // approximate length by summing linear segments
  3144. this.getLength = function ( nSubDivisions ) {
  3145. var i, index, nSamples, position,
  3146. point = 0, intPoint = 0, oldIntPoint = 0,
  3147. oldPosition = new THREE.Vector3(),
  3148. tmpVec = new THREE.Vector3(),
  3149. chunkLengths = [],
  3150. totalLength = 0;
  3151. // first point has 0 length
  3152. chunkLengths[ 0 ] = 0;
  3153. if ( !nSubDivisions ) nSubDivisions = 100;
  3154. nSamples = this.points.length * nSubDivisions;
  3155. oldPosition.copy( this.points[ 0 ] );
  3156. for ( i = 1; i < nSamples; i ++ ) {
  3157. index = i / nSamples;
  3158. position = this.getPoint( index );
  3159. tmpVec.copy( position );
  3160. totalLength += tmpVec.distanceTo( oldPosition );
  3161. oldPosition.copy( position );
  3162. point = ( this.points.length - 1 ) * index;
  3163. intPoint = Math.floor( point );
  3164. if ( intPoint != oldIntPoint ) {
  3165. chunkLengths[ intPoint ] = totalLength;
  3166. oldIntPoint = intPoint;
  3167. }
  3168. }
  3169. // last point ends with total length
  3170. chunkLengths[ chunkLengths.length ] = totalLength;
  3171. return { chunks: chunkLengths, total: totalLength };
  3172. };
  3173. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3174. var i, j,
  3175. index, indexCurrent, indexNext,
  3176. linearDistance, realDistance,
  3177. sampling, position,
  3178. newpoints = [],
  3179. tmpVec = new THREE.Vector3(),
  3180. sl = this.getLength();
  3181. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3182. for ( i = 1; i < this.points.length; i++ ) {
  3183. //tmpVec.copy( this.points[ i - 1 ] );
  3184. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3185. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3186. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3187. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3188. indexNext = i / ( this.points.length - 1 );
  3189. for ( j = 1; j < sampling - 1; j++ ) {
  3190. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3191. position = this.getPoint( index );
  3192. newpoints.push( tmpVec.copy( position ).clone() );
  3193. }
  3194. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3195. }
  3196. this.points = newpoints;
  3197. };
  3198. // Catmull-Rom
  3199. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3200. var v0 = ( p2 - p0 ) * 0.5,
  3201. v1 = ( p3 - p1 ) * 0.5;
  3202. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3203. };
  3204. };
  3205. /**
  3206. * @author bhouston / http://exocortex.com
  3207. * @author mrdoob / http://mrdoob.com/
  3208. */
  3209. THREE.Triangle = function ( a, b, c ) {
  3210. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3211. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3212. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3213. };
  3214. THREE.Triangle.normal = function( a, b, c, optionalTarget ) {
  3215. var result = optionalTarget || new THREE.Vector3();
  3216. result.subVectors( c, b );
  3217. THREE.Triangle.__v0.subVectors( a, b );
  3218. result.cross( THREE.Triangle.__v0 );
  3219. var resultLengthSq = result.lengthSq();
  3220. if( resultLengthSq > 0 ) {
  3221. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3222. }
  3223. return result.set( 0, 0, 0 );
  3224. };
  3225. // static/instance method to calculate barycoordinates
  3226. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3227. THREE.Triangle.barycoordFromPoint = function ( point, a, b, c, optionalTarget ) {
  3228. THREE.Triangle.__v0.subVectors( c, a );
  3229. THREE.Triangle.__v1.subVectors( b, a );
  3230. THREE.Triangle.__v2.subVectors( point, a );
  3231. var dot00 = THREE.Triangle.__v0.dot( THREE.Triangle.__v0 );
  3232. var dot01 = THREE.Triangle.__v0.dot( THREE.Triangle.__v1 );
  3233. var dot02 = THREE.Triangle.__v0.dot( THREE.Triangle.__v2 );
  3234. var dot11 = THREE.Triangle.__v1.dot( THREE.Triangle.__v1 );
  3235. var dot12 = THREE.Triangle.__v1.dot( THREE.Triangle.__v2 );
  3236. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3237. var result = optionalTarget || new THREE.Vector3();
  3238. // colinear or singular triangle
  3239. if( denom == 0 ) {
  3240. // arbitrary location outside of triangle?
  3241. // not sure if this is the best idea, maybe should be returning undefined
  3242. return result.set( -2, -1, -1 );
  3243. }
  3244. var invDenom = 1 / denom;
  3245. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3246. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3247. // barycoordinates must always sum to 1
  3248. return result.set( 1 - u - v, v, u );
  3249. };
  3250. THREE.Triangle.containsPoint = function ( point, a, b, c ) {
  3251. // NOTE: need to use __v3 here because __v0, __v1 and __v2 are used in barycoordFromPoint.
  3252. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, THREE.Triangle.__v3 );
  3253. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3254. };
  3255. THREE.Triangle.prototype = {
  3256. constructor: THREE.Triangle,
  3257. set: function ( a, b, c ) {
  3258. this.a.copy( a );
  3259. this.b.copy( b );
  3260. this.c.copy( c );
  3261. return this;
  3262. },
  3263. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3264. this.a.copy( points[i0] );
  3265. this.b.copy( points[i1] );
  3266. this.c.copy( points[i2] );
  3267. return this;
  3268. },
  3269. copy: function ( triangle ) {
  3270. this.a.copy( triangle.a );
  3271. this.b.copy( triangle.b );
  3272. this.c.copy( triangle.c );
  3273. return this;
  3274. },
  3275. area: function () {
  3276. THREE.Triangle.__v0.subVectors( this.c, this.b );
  3277. THREE.Triangle.__v1.subVectors( this.a, this.b );
  3278. return THREE.Triangle.__v0.cross( THREE.Triangle.__v1 ).length() * 0.5;
  3279. },
  3280. midpoint: function ( optionalTarget ) {
  3281. var result = optionalTarget || new THREE.Vector3();
  3282. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  3283. },
  3284. normal: function ( optionalTarget ) {
  3285. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3286. },
  3287. plane: function ( optionalTarget ) {
  3288. var result = optionalTarget || new THREE.Plane();
  3289. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  3290. },
  3291. barycoordFromPoint: function ( point, optionalTarget ) {
  3292. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  3293. },
  3294. containsPoint: function ( point ) {
  3295. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  3296. },
  3297. equals: function ( triangle ) {
  3298. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  3299. },
  3300. clone: function () {
  3301. return new THREE.Triangle().copy( this );
  3302. }
  3303. };
  3304. THREE.Triangle.__v0 = new THREE.Vector3();
  3305. THREE.Triangle.__v1 = new THREE.Vector3();
  3306. THREE.Triangle.__v2 = new THREE.Vector3();
  3307. THREE.Triangle.__v3 = new THREE.Vector3();
  3308. /**
  3309. * @author mrdoob / http://mrdoob.com/
  3310. */
  3311. THREE.Vertex = function ( v ) {
  3312. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  3313. return v;
  3314. };
  3315. /**
  3316. * @author mrdoob / http://mrdoob.com/
  3317. */
  3318. THREE.UV = function ( u, v ) {
  3319. console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
  3320. return new THREE.Vector2( u, v );
  3321. };
  3322. /**
  3323. * @author alteredq / http://alteredqualia.com/
  3324. */
  3325. THREE.Clock = function ( autoStart ) {
  3326. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  3327. this.startTime = 0;
  3328. this.oldTime = 0;
  3329. this.elapsedTime = 0;
  3330. this.running = false;
  3331. };
  3332. THREE.Clock.prototype.start = function () {
  3333. this.startTime = Date.now();
  3334. this.oldTime = this.startTime;
  3335. this.running = true;
  3336. };
  3337. THREE.Clock.prototype.stop = function () {
  3338. this.getElapsedTime();
  3339. this.running = false;
  3340. };
  3341. THREE.Clock.prototype.getElapsedTime = function () {
  3342. this.getDelta();
  3343. return this.elapsedTime;
  3344. };
  3345. THREE.Clock.prototype.getDelta = function () {
  3346. var diff = 0;
  3347. if ( this.autoStart && ! this.running ) {
  3348. this.start();
  3349. }
  3350. if ( this.running ) {
  3351. var newTime = Date.now();
  3352. diff = 0.001 * ( newTime - this.oldTime );
  3353. this.oldTime = newTime;
  3354. this.elapsedTime += diff;
  3355. }
  3356. return diff;
  3357. };/**
  3358. * https://github.com/mrdoob/eventdispatcher.js/
  3359. */
  3360. THREE.EventDispatcher = function () {
  3361. var listeners = {};
  3362. this.addEventListener = function ( type, listener ) {
  3363. if ( listeners[ type ] === undefined ) {
  3364. listeners[ type ] = [];
  3365. }
  3366. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  3367. listeners[ type ].push( listener );
  3368. }
  3369. };
  3370. this.removeEventListener = function ( type, listener ) {
  3371. var index = listeners[ type ].indexOf( listener );
  3372. if ( index !== - 1 ) {
  3373. listeners[ type ].splice( index, 1 );
  3374. }
  3375. };
  3376. this.dispatchEvent = function ( event ) {
  3377. var listenerArray = listeners[ event.type ];
  3378. if ( listenerArray !== undefined ) {
  3379. event.target = this;
  3380. for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
  3381. listenerArray[ i ].call( this, event );
  3382. }
  3383. }
  3384. };
  3385. };
  3386. /**
  3387. * @author mrdoob / http://mrdoob.com/
  3388. * @author bhouston / http://exocortex.com/
  3389. */
  3390. ( function ( THREE ) {
  3391. THREE.Raycaster = function ( origin, direction, near, far ) {
  3392. this.ray = new THREE.Ray( origin, direction );
  3393. // normalized ray.direction required for accurate distance calculations
  3394. if( this.ray.direction.length() > 0 ) {
  3395. this.ray.direction.normalize();
  3396. }
  3397. this.near = near || 0;
  3398. this.far = far || Infinity;
  3399. };
  3400. var sphere = new THREE.Sphere();
  3401. var localRay = new THREE.Ray();
  3402. var facePlane = new THREE.Plane();
  3403. var intersectPoint = new THREE.Vector3();
  3404. var inverseMatrix = new THREE.Matrix4();
  3405. var descSort = function ( a, b ) {
  3406. return a.distance - b.distance;
  3407. };
  3408. var intersectObject = function ( object, raycaster, intersects ) {
  3409. if ( object instanceof THREE.Particle ) {
  3410. var distance = raycaster.ray.distanceToPoint( object.matrixWorld.getPosition() );
  3411. if ( distance > object.scale.x ) {
  3412. return intersects;
  3413. }
  3414. intersects.push( {
  3415. distance: distance,
  3416. point: object.position,
  3417. face: null,
  3418. object: object
  3419. } );
  3420. } else if ( object instanceof THREE.Mesh ) {
  3421. // Checking boundingSphere distance to ray
  3422. sphere.set(
  3423. object.matrixWorld.getPosition(),
  3424. object.geometry.boundingSphere.radius* object.matrixWorld.getMaxScaleOnAxis() );
  3425. if ( ! raycaster.ray.isIntersectionSphere( sphere ) ) {
  3426. return intersects;
  3427. }
  3428. // Checking faces
  3429. var geometry = object.geometry;
  3430. var vertices = geometry.vertices;
  3431. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3432. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  3433. var side = object.material.side;
  3434. var a, b, c, d;
  3435. var precision = raycaster.precision;
  3436. object.matrixRotationWorld.extractRotation( object.matrixWorld );
  3437. inverseMatrix.getInverse( object.matrixWorld );
  3438. localRay.copy( raycaster.ray ).transform( inverseMatrix );
  3439. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  3440. var face = geometry.faces[ f ];
  3441. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  3442. if ( material === undefined ) continue;
  3443. facePlane.setFromNormalAndCoplanarPoint( face.normal, vertices[face.a] );
  3444. var planeDistance = localRay.distanceToPlane( facePlane );
  3445. // bail if raycaster and plane are parallel
  3446. if ( Math.abs( planeDistance ) < precision ) continue;
  3447. // if negative distance, then plane is behind raycaster
  3448. if ( planeDistance < 0 ) continue;
  3449. // check if we hit the wrong side of a single sided face
  3450. side = material.side;
  3451. if( side !== THREE.DoubleSide ) {
  3452. var planeSign = localRay.direction.dot( facePlane.normal );
  3453. if( ! ( side === THREE.FrontSide ? planeSign < 0 : planeSign > 0 ) ) continue;
  3454. }
  3455. // this can be done using the planeDistance from localRay because localRay wasn't normalized, but ray was
  3456. if ( planeDistance < raycaster.near || planeDistance > raycaster.far ) continue;
  3457. intersectPoint = localRay.at( planeDistance, intersectPoint ); // passing in intersectPoint avoids a copy
  3458. if ( face instanceof THREE.Face3 ) {
  3459. a = vertices[ face.a ];
  3460. b = vertices[ face.b ];
  3461. c = vertices[ face.c ];
  3462. if ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, c ) ) continue;
  3463. } else if ( face instanceof THREE.Face4 ) {
  3464. a = vertices[ face.a ];
  3465. b = vertices[ face.b ];
  3466. c = vertices[ face.c ];
  3467. d = vertices[ face.d ];
  3468. if ( ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, d ) ) &&
  3469. ( ! THREE.Triangle.containsPoint( intersectPoint, b, c, d ) ) ) continue;
  3470. } else {
  3471. // This is added because if we call out of this if/else group when none of the cases
  3472. // match it will add a point to the intersection list erroneously.
  3473. throw Error( "face type not supported" );
  3474. }
  3475. intersects.push( {
  3476. distance: planeDistance, // this works because the original ray was normalized, and the transformed localRay wasn't
  3477. point: raycaster.ray.at( planeDistance ),
  3478. face: face,
  3479. faceIndex: f,
  3480. object: object
  3481. } );
  3482. }
  3483. }
  3484. };
  3485. var intersectDescendants = function ( object, raycaster, intersects ) {
  3486. var descendants = object.getDescendants();
  3487. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  3488. intersectObject( descendants[ i ], raycaster, intersects );
  3489. }
  3490. };
  3491. //
  3492. THREE.Raycaster.prototype.precision = 0.0001;
  3493. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  3494. this.ray.set( origin, direction );
  3495. // normalized ray.direction required for accurate distance calculations
  3496. if( this.ray.direction.length() > 0 ) {
  3497. this.ray.direction.normalize();
  3498. }
  3499. };
  3500. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  3501. var intersects = [];
  3502. if ( recursive === true ) {
  3503. intersectDescendants( object, this, intersects );
  3504. }
  3505. intersectObject( object, this, intersects );
  3506. intersects.sort( descSort );
  3507. return intersects;
  3508. };
  3509. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  3510. var intersects = [];
  3511. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  3512. intersectObject( objects[ i ], this, intersects );
  3513. if ( recursive === true ) {
  3514. intersectDescendants( objects[ i ], this, intersects );
  3515. }
  3516. }
  3517. intersects.sort( descSort );
  3518. return intersects;
  3519. };
  3520. }( THREE ) );
  3521. /**
  3522. * @author mrdoob / http://mrdoob.com/
  3523. * @author mikael emtinger / http://gomo.se/
  3524. * @author alteredq / http://alteredqualia.com/
  3525. */
  3526. THREE.Object3D = function () {
  3527. this.id = THREE.Object3DIdCount ++;
  3528. this.name = '';
  3529. this.properties = {};
  3530. this.parent = undefined;
  3531. this.children = [];
  3532. this.up = new THREE.Vector3( 0, 1, 0 );
  3533. this.position = new THREE.Vector3();
  3534. this.rotation = new THREE.Vector3();
  3535. this.eulerOrder = THREE.Object3D.defaultEulerOrder;
  3536. this.scale = new THREE.Vector3( 1, 1, 1 );
  3537. this.renderDepth = null;
  3538. this.rotationAutoUpdate = true;
  3539. this.matrix = new THREE.Matrix4();
  3540. this.matrixWorld = new THREE.Matrix4();
  3541. this.matrixRotationWorld = new THREE.Matrix4();
  3542. this.matrixAutoUpdate = true;
  3543. this.matrixWorldNeedsUpdate = true;
  3544. this.quaternion = new THREE.Quaternion();
  3545. this.useQuaternion = false;
  3546. this.visible = true;
  3547. this.castShadow = false;
  3548. this.receiveShadow = false;
  3549. this.frustumCulled = true;
  3550. this._vector = new THREE.Vector3();
  3551. };
  3552. THREE.Object3D.prototype = {
  3553. constructor: THREE.Object3D,
  3554. applyMatrix: function ( matrix ) {
  3555. this.matrix.multiplyMatrices( matrix, this.matrix );
  3556. this.scale.getScaleFromMatrix( this.matrix );
  3557. var mat = new THREE.Matrix4().extractRotation( this.matrix );
  3558. this.rotation.setEulerFromRotationMatrix( mat, this.eulerOrder );
  3559. this.position.getPositionFromMatrix( this.matrix );
  3560. },
  3561. translate: function ( distance, axis ) {
  3562. this.matrix.rotateAxis( axis );
  3563. this.position.add( axis.multiplyScalar( distance ) );
  3564. },
  3565. translateX: function ( distance ) {
  3566. this.translate( distance, this._vector.set( 1, 0, 0 ) );
  3567. },
  3568. translateY: function ( distance ) {
  3569. this.translate( distance, this._vector.set( 0, 1, 0 ) );
  3570. },
  3571. translateZ: function ( distance ) {
  3572. this.translate( distance, this._vector.set( 0, 0, 1 ) );
  3573. },
  3574. localToWorld: function ( vector ) {
  3575. return vector.applyMatrix4( this.matrixWorld );
  3576. },
  3577. worldToLocal: function ( vector ) {
  3578. return vector.applyMatrix4( THREE.Object3D.__m1.getInverse( this.matrixWorld ) );
  3579. },
  3580. lookAt: function ( vector ) {
  3581. // TODO: Add hierarchy support.
  3582. this.matrix.lookAt( vector, this.position, this.up );
  3583. if ( this.rotationAutoUpdate ) {
  3584. if ( this.useQuaternion === false ) {
  3585. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  3586. } else {
  3587. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  3588. }
  3589. }
  3590. },
  3591. add: function ( object ) {
  3592. if ( object === this ) {
  3593. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  3594. return;
  3595. }
  3596. if ( object instanceof THREE.Object3D ) {
  3597. if ( object.parent !== undefined ) {
  3598. object.parent.remove( object );
  3599. }
  3600. object.parent = this;
  3601. this.children.push( object );
  3602. // add to scene
  3603. var scene = this;
  3604. while ( scene.parent !== undefined ) {
  3605. scene = scene.parent;
  3606. }
  3607. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  3608. scene.__addObject( object );
  3609. }
  3610. }
  3611. },
  3612. remove: function ( object ) {
  3613. var index = this.children.indexOf( object );
  3614. if ( index !== - 1 ) {
  3615. object.parent = undefined;
  3616. this.children.splice( index, 1 );
  3617. // remove from scene
  3618. var scene = this;
  3619. while ( scene.parent !== undefined ) {
  3620. scene = scene.parent;
  3621. }
  3622. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  3623. scene.__removeObject( object );
  3624. }
  3625. }
  3626. },
  3627. traverse: function ( callback ) {
  3628. callback( this );
  3629. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3630. this.children[ i ].traverse( callback );
  3631. }
  3632. },
  3633. getChildByName: function ( name, recursive ) {
  3634. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3635. var child = this.children[ i ];
  3636. if ( child.name === name ) {
  3637. return child;
  3638. }
  3639. if ( recursive === true ) {
  3640. child = child.getChildByName( name, recursive );
  3641. if ( child !== undefined ) {
  3642. return child;
  3643. }
  3644. }
  3645. }
  3646. return undefined;
  3647. },
  3648. getDescendants: function ( array ) {
  3649. if ( array === undefined ) array = [];
  3650. Array.prototype.push.apply( array, this.children );
  3651. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3652. this.children[ i ].getDescendants( array );
  3653. }
  3654. return array;
  3655. },
  3656. updateMatrix: function () {
  3657. this.matrix.setPosition( this.position );
  3658. if ( this.useQuaternion === false ) {
  3659. this.matrix.setRotationFromEuler( this.rotation, this.eulerOrder );
  3660. } else {
  3661. this.matrix.setRotationFromQuaternion( this.quaternion );
  3662. }
  3663. if ( this.scale.x !== 1 || this.scale.y !== 1 || this.scale.z !== 1 ) {
  3664. this.matrix.scale( this.scale );
  3665. }
  3666. this.matrixWorldNeedsUpdate = true;
  3667. },
  3668. updateMatrixWorld: function ( force ) {
  3669. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  3670. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  3671. if ( this.parent === undefined ) {
  3672. this.matrixWorld.copy( this.matrix );
  3673. } else {
  3674. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  3675. }
  3676. this.matrixWorldNeedsUpdate = false;
  3677. force = true;
  3678. }
  3679. // update children
  3680. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3681. this.children[ i ].updateMatrixWorld( force );
  3682. }
  3683. },
  3684. clone: function ( object ) {
  3685. if ( object === undefined ) object = new THREE.Object3D();
  3686. object.name = this.name;
  3687. object.up.copy( this.up );
  3688. object.position.copy( this.position );
  3689. if ( object.rotation instanceof THREE.Vector3 ) object.rotation.copy( this.rotation ); // because of Sprite madness
  3690. object.eulerOrder = this.eulerOrder;
  3691. object.scale.copy( this.scale );
  3692. object.renderDepth = this.renderDepth;
  3693. object.rotationAutoUpdate = this.rotationAutoUpdate;
  3694. object.matrix.copy( this.matrix );
  3695. object.matrixWorld.copy( this.matrixWorld );
  3696. object.matrixRotationWorld.copy( this.matrixRotationWorld );
  3697. object.matrixAutoUpdate = this.matrixAutoUpdate;
  3698. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  3699. object.quaternion.copy( this.quaternion );
  3700. object.useQuaternion = this.useQuaternion;
  3701. object.visible = this.visible;
  3702. object.castShadow = this.castShadow;
  3703. object.receiveShadow = this.receiveShadow;
  3704. object.frustumCulled = this.frustumCulled;
  3705. for ( var i = 0; i < this.children.length; i ++ ) {
  3706. var child = this.children[ i ];
  3707. object.add( child.clone() );
  3708. }
  3709. return object;
  3710. }
  3711. };
  3712. THREE.Object3D.__m1 = new THREE.Matrix4();
  3713. THREE.Object3D.defaultEulerOrder = 'XYZ',
  3714. THREE.Object3DIdCount = 0;
  3715. /**
  3716. * @author mrdoob / http://mrdoob.com/
  3717. * @author supereggbert / http://www.paulbrunt.co.uk/
  3718. * @author julianwa / https://github.com/julianwa
  3719. */
  3720. THREE.Projector = function() {
  3721. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  3722. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  3723. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  3724. _face4Count, _face4Pool = [], _face4PoolLength = 0,
  3725. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  3726. _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
  3727. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  3728. _vector3 = new THREE.Vector3(),
  3729. _vector4 = new THREE.Vector4(),
  3730. _viewMatrix = new THREE.Matrix4(),
  3731. _viewProjectionMatrix = new THREE.Matrix4(),
  3732. _modelMatrix,
  3733. _modelViewProjectionMatrix = new THREE.Matrix4(),
  3734. _normalMatrix = new THREE.Matrix3(),
  3735. _normalViewMatrix = new THREE.Matrix3(),
  3736. _centroid = new THREE.Vector3(),
  3737. _frustum = new THREE.Frustum(),
  3738. _clippedVertex1PositionScreen = new THREE.Vector4(),
  3739. _clippedVertex2PositionScreen = new THREE.Vector4(),
  3740. _face3VertexNormals;
  3741. this.projectVector = function ( vector, camera ) {
  3742. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  3743. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  3744. return vector.applyMatrix4( _viewProjectionMatrix );
  3745. };
  3746. this.unprojectVector = function ( vector, camera ) {
  3747. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  3748. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, camera.projectionMatrixInverse );
  3749. return vector.applyMatrix4( _viewProjectionMatrix );
  3750. };
  3751. this.pickingRay = function ( vector, camera ) {
  3752. // set two vectors with opposing z values
  3753. vector.z = -1.0;
  3754. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  3755. this.unprojectVector( vector, camera );
  3756. this.unprojectVector( end, camera );
  3757. // find direction from vector to end
  3758. end.sub( vector ).normalize();
  3759. return new THREE.Raycaster( vector, end );
  3760. };
  3761. var projectGraph = function ( root, sortObjects ) {
  3762. _objectCount = 0;
  3763. _renderData.objects.length = 0;
  3764. _renderData.sprites.length = 0;
  3765. _renderData.lights.length = 0;
  3766. var projectObject = function ( parent ) {
  3767. for ( var c = 0, cl = parent.children.length; c < cl; c ++ ) {
  3768. var object = parent.children[ c ];
  3769. if ( object.visible === false ) continue;
  3770. if ( object instanceof THREE.Light ) {
  3771. _renderData.lights.push( object );
  3772. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  3773. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  3774. _object = getNextObjectInPool();
  3775. _object.object = object;
  3776. if ( object.renderDepth !== null ) {
  3777. _object.z = object.renderDepth;
  3778. } else {
  3779. _vector3.copy( object.matrixWorld.getPosition() );
  3780. _vector3.applyMatrix4( _viewProjectionMatrix );
  3781. _object.z = _vector3.z;
  3782. }
  3783. _renderData.objects.push( _object );
  3784. }
  3785. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  3786. _object = getNextObjectInPool();
  3787. _object.object = object;
  3788. // TODO: Find an elegant and performant solution and remove this dupe code.
  3789. if ( object.renderDepth !== null ) {
  3790. _object.z = object.renderDepth;
  3791. } else {
  3792. _vector3.copy( object.matrixWorld.getPosition() );
  3793. _vector3.applyMatrix4( _viewProjectionMatrix );
  3794. _object.z = _vector3.z;
  3795. }
  3796. _renderData.sprites.push( _object );
  3797. } else {
  3798. _object = getNextObjectInPool();
  3799. _object.object = object;
  3800. if ( object.renderDepth !== null ) {
  3801. _object.z = object.renderDepth;
  3802. } else {
  3803. _vector3.copy( object.matrixWorld.getPosition() );
  3804. _vector3.applyMatrix4( _viewProjectionMatrix );
  3805. _object.z = _vector3.z;
  3806. }
  3807. _renderData.objects.push( _object );
  3808. }
  3809. projectObject( object );
  3810. }
  3811. };
  3812. projectObject( root );
  3813. if ( sortObjects === true ) _renderData.objects.sort( painterSort );
  3814. return _renderData;
  3815. };
  3816. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  3817. var near = camera.near, far = camera.far, visible = false,
  3818. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  3819. geometry, vertices, vertex, vertexPositionScreen,
  3820. faces, face, faceVertexNormals, faceVertexUvs, uvs,
  3821. v1, v2, v3, v4, isFaceMaterial, objectMaterials;
  3822. _face3Count = 0;
  3823. _face4Count = 0;
  3824. _lineCount = 0;
  3825. _particleCount = 0;
  3826. _renderData.elements.length = 0;
  3827. scene.updateMatrixWorld();
  3828. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  3829. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  3830. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  3831. _normalViewMatrix.getInverse( _viewMatrix );
  3832. _normalViewMatrix.transpose();
  3833. _frustum.setFromMatrix( _viewProjectionMatrix );
  3834. _renderData = projectGraph( scene, sortObjects );
  3835. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  3836. object = _renderData.objects[ o ].object;
  3837. _modelMatrix = object.matrixWorld;
  3838. _vertexCount = 0;
  3839. if ( object instanceof THREE.Mesh ) {
  3840. geometry = object.geometry;
  3841. vertices = geometry.vertices;
  3842. faces = geometry.faces;
  3843. faceVertexUvs = geometry.faceVertexUvs;
  3844. _normalMatrix.getInverse( _modelMatrix );
  3845. _normalMatrix.transpose();
  3846. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3847. objectMaterials = isFaceMaterial === true ? object.material : null;
  3848. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  3849. _vertex = getNextVertexInPool();
  3850. _vertex.positionWorld.copy( vertices[ v ] );
  3851. _vertex.positionWorld.applyMatrix4( _modelMatrix );
  3852. _vertex.positionScreen.copy( _vertex.positionWorld );
  3853. _vertex.positionScreen.applyMatrix4( _viewProjectionMatrix );
  3854. _vertex.positionScreen.multiplyScalar( 1 / _vertex.positionScreen.w );
  3855. _vertex.visible = _vertex.positionScreen.z > -1 && _vertex.positionScreen.z < 1;
  3856. }
  3857. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  3858. face = faces[ f ];
  3859. var material = isFaceMaterial === true
  3860. ? objectMaterials.materials[ face.materialIndex ]
  3861. : object.material;
  3862. if ( material === undefined ) continue;
  3863. var side = material.side;
  3864. if ( face instanceof THREE.Face3 ) {
  3865. v1 = _vertexPool[ face.a ];
  3866. v2 = _vertexPool[ face.b ];
  3867. v3 = _vertexPool[ face.c ];
  3868. if ( v1.visible === true && v2.visible === true && v3.visible === true ) {
  3869. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  3870. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  3871. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  3872. _face = getNextFace3InPool();
  3873. _face.v1.copy( v1 );
  3874. _face.v2.copy( v2 );
  3875. _face.v3.copy( v3 );
  3876. } else {
  3877. continue;
  3878. }
  3879. } else {
  3880. continue;
  3881. }
  3882. } else if ( face instanceof THREE.Face4 ) {
  3883. v1 = _vertexPool[ face.a ];
  3884. v2 = _vertexPool[ face.b ];
  3885. v3 = _vertexPool[ face.c ];
  3886. v4 = _vertexPool[ face.d ];
  3887. if ( v1.visible === true && v2.visible === true && v3.visible === true && v4.visible === true ) {
  3888. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  3889. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  3890. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  3891. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  3892. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  3893. _face = getNextFace4InPool();
  3894. _face.v1.copy( v1 );
  3895. _face.v2.copy( v2 );
  3896. _face.v3.copy( v3 );
  3897. _face.v4.copy( v4 );
  3898. } else {
  3899. continue;
  3900. }
  3901. } else {
  3902. continue;
  3903. }
  3904. }
  3905. _face.normalModel.copy( face.normal );
  3906. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  3907. _face.normalModel.negate();
  3908. }
  3909. _face.normalModel.applyMatrix3( _normalMatrix );
  3910. _face.normalModel.normalize();
  3911. _face.normalModelView.copy( _face.normalModel );
  3912. _face.normalModelView.applyMatrix3( _normalViewMatrix );
  3913. _face.centroidModel.copy( face.centroid );
  3914. _face.centroidModel.applyMatrix4( _modelMatrix );
  3915. faceVertexNormals = face.vertexNormals;
  3916. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  3917. var normalModel = _face.vertexNormalsModel[ n ];
  3918. normalModel.copy( faceVertexNormals[ n ] );
  3919. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  3920. normalModel.negate();
  3921. }
  3922. normalModel.applyMatrix3( _normalMatrix );
  3923. normalModel.normalize();
  3924. var normalModelView = _face.vertexNormalsModelView[ n ];
  3925. normalModelView.copy( normalModel );
  3926. normalModelView.applyMatrix3( _normalViewMatrix );
  3927. }
  3928. _face.vertexNormalsLength = faceVertexNormals.length;
  3929. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  3930. uvs = faceVertexUvs[ c ][ f ];
  3931. if ( uvs === undefined ) continue;
  3932. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  3933. _face.uvs[ c ][ u ] = uvs[ u ];
  3934. }
  3935. }
  3936. _face.color = face.color;
  3937. _face.material = material;
  3938. _centroid.copy( _face.centroidModel )
  3939. _centroid.applyMatrix4( _viewProjectionMatrix );
  3940. _face.z = _centroid.z;
  3941. _renderData.elements.push( _face );
  3942. }
  3943. } else if ( object instanceof THREE.Line ) {
  3944. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  3945. vertices = object.geometry.vertices;
  3946. v1 = getNextVertexInPool();
  3947. v1.positionScreen.copy( vertices[ 0 ] );
  3948. v1.positionScreen.applyMatrix4( _modelViewProjectionMatrix );
  3949. // Handle LineStrip and LinePieces
  3950. var step = object.type === THREE.LinePieces ? 2 : 1;
  3951. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  3952. v1 = getNextVertexInPool();
  3953. v1.positionScreen.copy( vertices[ v ] );
  3954. v1.positionScreen.applyMatrix4( _modelViewProjectionMatrix );
  3955. if ( ( v + 1 ) % step > 0 ) continue;
  3956. v2 = _vertexPool[ _vertexCount - 2 ];
  3957. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  3958. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  3959. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  3960. // Perform the perspective divide
  3961. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  3962. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  3963. _line = getNextLineInPool();
  3964. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  3965. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  3966. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  3967. _line.material = object.material;
  3968. _renderData.elements.push( _line );
  3969. }
  3970. }
  3971. }
  3972. }
  3973. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  3974. object = _renderData.sprites[ o ].object;
  3975. _modelMatrix = object.matrixWorld;
  3976. if ( object instanceof THREE.Particle ) {
  3977. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  3978. _vector4.applyMatrix4( _viewProjectionMatrix );
  3979. _vector4.z /= _vector4.w;
  3980. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  3981. _particle = getNextParticleInPool();
  3982. _particle.object = object;
  3983. _particle.x = _vector4.x / _vector4.w;
  3984. _particle.y = _vector4.y / _vector4.w;
  3985. _particle.z = _vector4.z;
  3986. _particle.rotation = object.rotation.z;
  3987. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  3988. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  3989. _particle.material = object.material;
  3990. _renderData.elements.push( _particle );
  3991. }
  3992. }
  3993. }
  3994. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  3995. return _renderData;
  3996. };
  3997. // Pools
  3998. function getNextObjectInPool() {
  3999. if ( _objectCount === _objectPoolLength ) {
  4000. var object = new THREE.RenderableObject();
  4001. _objectPool.push( object );
  4002. _objectPoolLength ++;
  4003. _objectCount ++;
  4004. return object;
  4005. }
  4006. return _objectPool[ _objectCount ++ ];
  4007. }
  4008. function getNextVertexInPool() {
  4009. if ( _vertexCount === _vertexPoolLength ) {
  4010. var vertex = new THREE.RenderableVertex();
  4011. _vertexPool.push( vertex );
  4012. _vertexPoolLength ++;
  4013. _vertexCount ++;
  4014. return vertex;
  4015. }
  4016. return _vertexPool[ _vertexCount ++ ];
  4017. }
  4018. function getNextFace3InPool() {
  4019. if ( _face3Count === _face3PoolLength ) {
  4020. var face = new THREE.RenderableFace3();
  4021. _face3Pool.push( face );
  4022. _face3PoolLength ++;
  4023. _face3Count ++;
  4024. return face;
  4025. }
  4026. return _face3Pool[ _face3Count ++ ];
  4027. }
  4028. function getNextFace4InPool() {
  4029. if ( _face4Count === _face4PoolLength ) {
  4030. var face = new THREE.RenderableFace4();
  4031. _face4Pool.push( face );
  4032. _face4PoolLength ++;
  4033. _face4Count ++;
  4034. return face;
  4035. }
  4036. return _face4Pool[ _face4Count ++ ];
  4037. }
  4038. function getNextLineInPool() {
  4039. if ( _lineCount === _linePoolLength ) {
  4040. var line = new THREE.RenderableLine();
  4041. _linePool.push( line );
  4042. _linePoolLength ++;
  4043. _lineCount ++
  4044. return line;
  4045. }
  4046. return _linePool[ _lineCount ++ ];
  4047. }
  4048. function getNextParticleInPool() {
  4049. if ( _particleCount === _particlePoolLength ) {
  4050. var particle = new THREE.RenderableParticle();
  4051. _particlePool.push( particle );
  4052. _particlePoolLength ++;
  4053. _particleCount ++
  4054. return particle;
  4055. }
  4056. return _particlePool[ _particleCount ++ ];
  4057. }
  4058. //
  4059. function painterSort( a, b ) {
  4060. return b.z - a.z;
  4061. }
  4062. function clipLine( s1, s2 ) {
  4063. var alpha1 = 0, alpha2 = 1,
  4064. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  4065. // Z = -1 and Z = +1, respectively.
  4066. bc1near = s1.z + s1.w,
  4067. bc2near = s2.z + s2.w,
  4068. bc1far = - s1.z + s1.w,
  4069. bc2far = - s2.z + s2.w;
  4070. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  4071. // Both vertices lie entirely within all clip planes.
  4072. return true;
  4073. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  4074. // Both vertices lie entirely outside one of the clip planes.
  4075. return false;
  4076. } else {
  4077. // The line segment spans at least one clip plane.
  4078. if ( bc1near < 0 ) {
  4079. // v1 lies outside the near plane, v2 inside
  4080. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  4081. } else if ( bc2near < 0 ) {
  4082. // v2 lies outside the near plane, v1 inside
  4083. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  4084. }
  4085. if ( bc1far < 0 ) {
  4086. // v1 lies outside the far plane, v2 inside
  4087. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  4088. } else if ( bc2far < 0 ) {
  4089. // v2 lies outside the far plane, v2 inside
  4090. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  4091. }
  4092. if ( alpha2 < alpha1 ) {
  4093. // The line segment spans two boundaries, but is outside both of them.
  4094. // (This can't happen when we're only clipping against just near/far but good
  4095. // to leave the check here for future usage if other clip planes are added.)
  4096. return false;
  4097. } else {
  4098. // Update the s1 and s2 vertices to match the clipped line segment.
  4099. s1.lerp( s2, alpha1 );
  4100. s2.lerp( s1, 1 - alpha2 );
  4101. return true;
  4102. }
  4103. }
  4104. }
  4105. };
  4106. /**
  4107. * @author mrdoob / http://mrdoob.com/
  4108. * @author alteredq / http://alteredqualia.com/
  4109. */
  4110. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  4111. this.a = a;
  4112. this.b = b;
  4113. this.c = c;
  4114. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4115. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4116. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4117. this.vertexColors = color instanceof Array ? color : [];
  4118. this.vertexTangents = [];
  4119. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4120. this.centroid = new THREE.Vector3();
  4121. };
  4122. THREE.Face3.prototype = {
  4123. constructor: THREE.Face3,
  4124. clone: function () {
  4125. var face = new THREE.Face3( this.a, this.b, this.c );
  4126. face.normal.copy( this.normal );
  4127. face.color.copy( this.color );
  4128. face.centroid.copy( this.centroid );
  4129. face.materialIndex = this.materialIndex;
  4130. var i, il;
  4131. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4132. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4133. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4134. return face;
  4135. }
  4136. };
  4137. /**
  4138. * @author mrdoob / http://mrdoob.com/
  4139. * @author alteredq / http://alteredqualia.com/
  4140. */
  4141. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  4142. this.a = a;
  4143. this.b = b;
  4144. this.c = c;
  4145. this.d = d;
  4146. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4147. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4148. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4149. this.vertexColors = color instanceof Array ? color : [];
  4150. this.vertexTangents = [];
  4151. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4152. this.centroid = new THREE.Vector3();
  4153. };
  4154. THREE.Face4.prototype = {
  4155. constructor: THREE.Face4,
  4156. clone: function () {
  4157. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  4158. face.normal.copy( this.normal );
  4159. face.color.copy( this.color );
  4160. face.centroid.copy( this.centroid );
  4161. face.materialIndex = this.materialIndex;
  4162. var i, il;
  4163. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4164. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4165. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4166. return face;
  4167. }
  4168. };
  4169. /**
  4170. * @author mrdoob / http://mrdoob.com/
  4171. * @author kile / http://kile.stravaganza.org/
  4172. * @author alteredq / http://alteredqualia.com/
  4173. * @author mikael emtinger / http://gomo.se/
  4174. * @author zz85 / http://www.lab4games.net/zz85/blog
  4175. * @author bhouston / http://exocortex.com
  4176. */
  4177. THREE.Geometry = function () {
  4178. THREE.EventDispatcher.call( this );
  4179. this.id = THREE.GeometryIdCount ++;
  4180. this.name = '';
  4181. this.vertices = [];
  4182. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  4183. this.normals = []; // one-to-one vertex normals, used in Ribbon
  4184. this.faces = [];
  4185. this.faceUvs = [[]];
  4186. this.faceVertexUvs = [[]];
  4187. this.morphTargets = [];
  4188. this.morphColors = [];
  4189. this.morphNormals = [];
  4190. this.skinWeights = [];
  4191. this.skinIndices = [];
  4192. this.lineDistances = [];
  4193. this.boundingBox = null;
  4194. this.boundingSphere = null;
  4195. this.hasTangents = false;
  4196. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  4197. // update flags
  4198. this.verticesNeedUpdate = false;
  4199. this.elementsNeedUpdate = false;
  4200. this.uvsNeedUpdate = false;
  4201. this.normalsNeedUpdate = false;
  4202. this.tangentsNeedUpdate = false;
  4203. this.colorsNeedUpdate = false;
  4204. this.lineDistancesNeedUpdate = false;
  4205. this.buffersNeedUpdate = false;
  4206. };
  4207. THREE.Geometry.prototype = {
  4208. constructor: THREE.Geometry,
  4209. applyMatrix: function ( matrix ) {
  4210. var normalMatrix = new THREE.Matrix3().getInverse( matrix ).transpose();
  4211. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  4212. var vertex = this.vertices[ i ];
  4213. vertex.applyMatrix4( matrix );
  4214. }
  4215. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  4216. var face = this.faces[ i ];
  4217. face.normal.applyMatrix3( normalMatrix ).normalize();
  4218. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  4219. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  4220. }
  4221. face.centroid.applyMatrix4( matrix );
  4222. }
  4223. },
  4224. computeCentroids: function () {
  4225. var f, fl, face;
  4226. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4227. face = this.faces[ f ];
  4228. face.centroid.set( 0, 0, 0 );
  4229. if ( face instanceof THREE.Face3 ) {
  4230. face.centroid.add( this.vertices[ face.a ] );
  4231. face.centroid.add( this.vertices[ face.b ] );
  4232. face.centroid.add( this.vertices[ face.c ] );
  4233. face.centroid.divideScalar( 3 );
  4234. } else if ( face instanceof THREE.Face4 ) {
  4235. face.centroid.add( this.vertices[ face.a ] );
  4236. face.centroid.add( this.vertices[ face.b ] );
  4237. face.centroid.add( this.vertices[ face.c ] );
  4238. face.centroid.add( this.vertices[ face.d ] );
  4239. face.centroid.divideScalar( 4 );
  4240. }
  4241. }
  4242. },
  4243. computeFaceNormals: function () {
  4244. var n, nl, v, vl, vertex, f, fl, face, vA, vB, vC,
  4245. cb = new THREE.Vector3(), ab = new THREE.Vector3();
  4246. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4247. face = this.faces[ f ];
  4248. vA = this.vertices[ face.a ];
  4249. vB = this.vertices[ face.b ];
  4250. vC = this.vertices[ face.c ];
  4251. cb.subVectors( vC, vB );
  4252. ab.subVectors( vA, vB );
  4253. cb.cross( ab );
  4254. cb.normalize();
  4255. face.normal.copy( cb );
  4256. }
  4257. },
  4258. computeVertexNormals: function ( areaWeighted ) {
  4259. var v, vl, f, fl, face, vertices;
  4260. // create internal buffers for reuse when calling this method repeatedly
  4261. // (otherwise memory allocation / deallocation every frame is big resource hog)
  4262. if ( this.__tmpVertices === undefined ) {
  4263. this.__tmpVertices = new Array( this.vertices.length );
  4264. vertices = this.__tmpVertices;
  4265. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4266. vertices[ v ] = new THREE.Vector3();
  4267. }
  4268. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4269. face = this.faces[ f ];
  4270. if ( face instanceof THREE.Face3 ) {
  4271. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4272. } else if ( face instanceof THREE.Face4 ) {
  4273. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4274. }
  4275. }
  4276. } else {
  4277. vertices = this.__tmpVertices;
  4278. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4279. vertices[ v ].set( 0, 0, 0 );
  4280. }
  4281. }
  4282. if ( areaWeighted ) {
  4283. // vertex normals weighted by triangle areas
  4284. // http://www.iquilezles.org/www/articles/normals/normals.htm
  4285. var vA, vB, vC, vD;
  4286. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  4287. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  4288. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4289. face = this.faces[ f ];
  4290. if ( face instanceof THREE.Face3 ) {
  4291. vA = this.vertices[ face.a ];
  4292. vB = this.vertices[ face.b ];
  4293. vC = this.vertices[ face.c ];
  4294. cb.subVectors( vC, vB );
  4295. ab.subVectors( vA, vB );
  4296. cb.cross( ab );
  4297. vertices[ face.a ].add( cb );
  4298. vertices[ face.b ].add( cb );
  4299. vertices[ face.c ].add( cb );
  4300. } else if ( face instanceof THREE.Face4 ) {
  4301. vA = this.vertices[ face.a ];
  4302. vB = this.vertices[ face.b ];
  4303. vC = this.vertices[ face.c ];
  4304. vD = this.vertices[ face.d ];
  4305. // abd
  4306. db.subVectors( vD, vB );
  4307. ab.subVectors( vA, vB );
  4308. db.cross( ab );
  4309. vertices[ face.a ].add( db );
  4310. vertices[ face.b ].add( db );
  4311. vertices[ face.d ].add( db );
  4312. // bcd
  4313. dc.subVectors( vD, vC );
  4314. bc.subVectors( vB, vC );
  4315. dc.cross( bc );
  4316. vertices[ face.b ].add( dc );
  4317. vertices[ face.c ].add( dc );
  4318. vertices[ face.d ].add( dc );
  4319. }
  4320. }
  4321. } else {
  4322. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4323. face = this.faces[ f ];
  4324. if ( face instanceof THREE.Face3 ) {
  4325. vertices[ face.a ].add( face.normal );
  4326. vertices[ face.b ].add( face.normal );
  4327. vertices[ face.c ].add( face.normal );
  4328. } else if ( face instanceof THREE.Face4 ) {
  4329. vertices[ face.a ].add( face.normal );
  4330. vertices[ face.b ].add( face.normal );
  4331. vertices[ face.c ].add( face.normal );
  4332. vertices[ face.d ].add( face.normal );
  4333. }
  4334. }
  4335. }
  4336. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4337. vertices[ v ].normalize();
  4338. }
  4339. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4340. face = this.faces[ f ];
  4341. if ( face instanceof THREE.Face3 ) {
  4342. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4343. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4344. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4345. } else if ( face instanceof THREE.Face4 ) {
  4346. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4347. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4348. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4349. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  4350. }
  4351. }
  4352. },
  4353. computeMorphNormals: function () {
  4354. var i, il, f, fl, face;
  4355. // save original normals
  4356. // - create temp variables on first access
  4357. // otherwise just copy (for faster repeated calls)
  4358. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4359. face = this.faces[ f ];
  4360. if ( ! face.__originalFaceNormal ) {
  4361. face.__originalFaceNormal = face.normal.clone();
  4362. } else {
  4363. face.__originalFaceNormal.copy( face.normal );
  4364. }
  4365. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  4366. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  4367. if ( ! face.__originalVertexNormals[ i ] ) {
  4368. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  4369. } else {
  4370. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  4371. }
  4372. }
  4373. }
  4374. // use temp geometry to compute face and vertex normals for each morph
  4375. var tmpGeo = new THREE.Geometry();
  4376. tmpGeo.faces = this.faces;
  4377. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  4378. // create on first access
  4379. if ( ! this.morphNormals[ i ] ) {
  4380. this.morphNormals[ i ] = {};
  4381. this.morphNormals[ i ].faceNormals = [];
  4382. this.morphNormals[ i ].vertexNormals = [];
  4383. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  4384. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  4385. var faceNormal, vertexNormals;
  4386. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4387. face = this.faces[ f ];
  4388. faceNormal = new THREE.Vector3();
  4389. if ( face instanceof THREE.Face3 ) {
  4390. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  4391. } else {
  4392. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  4393. }
  4394. dstNormalsFace.push( faceNormal );
  4395. dstNormalsVertex.push( vertexNormals );
  4396. }
  4397. }
  4398. var morphNormals = this.morphNormals[ i ];
  4399. // set vertices to morph target
  4400. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  4401. // compute morph normals
  4402. tmpGeo.computeFaceNormals();
  4403. tmpGeo.computeVertexNormals();
  4404. // store morph normals
  4405. var faceNormal, vertexNormals;
  4406. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4407. face = this.faces[ f ];
  4408. faceNormal = morphNormals.faceNormals[ f ];
  4409. vertexNormals = morphNormals.vertexNormals[ f ];
  4410. faceNormal.copy( face.normal );
  4411. if ( face instanceof THREE.Face3 ) {
  4412. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4413. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4414. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4415. } else {
  4416. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4417. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4418. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4419. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  4420. }
  4421. }
  4422. }
  4423. // restore original normals
  4424. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4425. face = this.faces[ f ];
  4426. face.normal = face.__originalFaceNormal;
  4427. face.vertexNormals = face.__originalVertexNormals;
  4428. }
  4429. },
  4430. computeTangents: function () {
  4431. // based on http://www.terathon.com/code/tangent.html
  4432. // tangents go to vertices
  4433. var f, fl, v, vl, i, il, vertexIndex,
  4434. face, uv, vA, vB, vC, uvA, uvB, uvC,
  4435. x1, x2, y1, y2, z1, z2,
  4436. s1, s2, t1, t2, r, t, test,
  4437. tan1 = [], tan2 = [],
  4438. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  4439. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  4440. n = new THREE.Vector3(), w;
  4441. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4442. tan1[ v ] = new THREE.Vector3();
  4443. tan2[ v ] = new THREE.Vector3();
  4444. }
  4445. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  4446. vA = context.vertices[ a ];
  4447. vB = context.vertices[ b ];
  4448. vC = context.vertices[ c ];
  4449. uvA = uv[ ua ];
  4450. uvB = uv[ ub ];
  4451. uvC = uv[ uc ];
  4452. x1 = vB.x - vA.x;
  4453. x2 = vC.x - vA.x;
  4454. y1 = vB.y - vA.y;
  4455. y2 = vC.y - vA.y;
  4456. z1 = vB.z - vA.z;
  4457. z2 = vC.z - vA.z;
  4458. s1 = uvB.x - uvA.x;
  4459. s2 = uvC.x - uvA.x;
  4460. t1 = uvB.y - uvA.y;
  4461. t2 = uvC.y - uvA.y;
  4462. r = 1.0 / ( s1 * t2 - s2 * t1 );
  4463. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  4464. ( t2 * y1 - t1 * y2 ) * r,
  4465. ( t2 * z1 - t1 * z2 ) * r );
  4466. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  4467. ( s1 * y2 - s2 * y1 ) * r,
  4468. ( s1 * z2 - s2 * z1 ) * r );
  4469. tan1[ a ].add( sdir );
  4470. tan1[ b ].add( sdir );
  4471. tan1[ c ].add( sdir );
  4472. tan2[ a ].add( tdir );
  4473. tan2[ b ].add( tdir );
  4474. tan2[ c ].add( tdir );
  4475. }
  4476. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4477. face = this.faces[ f ];
  4478. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  4479. if ( face instanceof THREE.Face3 ) {
  4480. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  4481. } else if ( face instanceof THREE.Face4 ) {
  4482. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  4483. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  4484. }
  4485. }
  4486. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  4487. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4488. face = this.faces[ f ];
  4489. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  4490. n.copy( face.vertexNormals[ i ] );
  4491. vertexIndex = face[ faceIndex[ i ] ];
  4492. t = tan1[ vertexIndex ];
  4493. // Gram-Schmidt orthogonalize
  4494. tmp.copy( t );
  4495. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  4496. // Calculate handedness
  4497. tmp2.crossVectors( face.vertexNormals[ i ], t );
  4498. test = tmp2.dot( tan2[ vertexIndex ] );
  4499. w = (test < 0.0) ? -1.0 : 1.0;
  4500. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  4501. }
  4502. }
  4503. this.hasTangents = true;
  4504. },
  4505. computeLineDistances: function ( ) {
  4506. var d = 0;
  4507. var vertices = this.vertices;
  4508. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4509. if ( i > 0 ) {
  4510. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  4511. }
  4512. this.lineDistances[ i ] = d;
  4513. }
  4514. },
  4515. computeBoundingBox: function () {
  4516. if ( this.boundingBox === null ) {
  4517. this.boundingBox = new THREE.Box3();
  4518. }
  4519. this.boundingBox.setFromPoints( this.vertices );
  4520. },
  4521. computeBoundingSphere: function () {
  4522. if ( this.boundingSphere === null ) {
  4523. this.boundingSphere = new THREE.Sphere();
  4524. }
  4525. this.boundingSphere.setFromCenterAndPoints( this.boundingSphere.center, this.vertices );
  4526. },
  4527. /*
  4528. * Checks for duplicate vertices with hashmap.
  4529. * Duplicated vertices are removed
  4530. * and faces' vertices are updated.
  4531. */
  4532. mergeVertices: function () {
  4533. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  4534. var unique = [], changes = [];
  4535. var v, key;
  4536. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  4537. var precision = Math.pow( 10, precisionPoints );
  4538. var i,il, face;
  4539. var indices, k, j, jl, u;
  4540. // reset cache of vertices as it now will be changing.
  4541. this.__tmpVertices = undefined;
  4542. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  4543. v = this.vertices[ i ];
  4544. key = [ Math.round( v.x * precision ), Math.round( v.y * precision ), Math.round( v.z * precision ) ].join( '_' );
  4545. if ( verticesMap[ key ] === undefined ) {
  4546. verticesMap[ key ] = i;
  4547. unique.push( this.vertices[ i ] );
  4548. changes[ i ] = unique.length - 1;
  4549. } else {
  4550. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  4551. changes[ i ] = changes[ verticesMap[ key ] ];
  4552. }
  4553. };
  4554. // if faces are completely degenerate after merging vertices, we
  4555. // have to remove them from the geometry.
  4556. var faceIndicesToRemove = [];
  4557. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  4558. face = this.faces[ i ];
  4559. if ( face instanceof THREE.Face3 ) {
  4560. face.a = changes[ face.a ];
  4561. face.b = changes[ face.b ];
  4562. face.c = changes[ face.c ];
  4563. indices = [ face.a, face.b, face.c ];
  4564. var dupIndex = -1;
  4565. // if any duplicate vertices are found in a Face3
  4566. // we have to remove the face as nothing can be saved
  4567. for ( var n = 0; n < 3; n ++ ) {
  4568. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  4569. dupIndex = n;
  4570. faceIndicesToRemove.push( i );
  4571. break;
  4572. }
  4573. }
  4574. } else if ( face instanceof THREE.Face4 ) {
  4575. face.a = changes[ face.a ];
  4576. face.b = changes[ face.b ];
  4577. face.c = changes[ face.c ];
  4578. face.d = changes[ face.d ];
  4579. // check dups in (a, b, c, d) and convert to -> face3
  4580. indices = [ face.a, face.b, face.c, face.d ];
  4581. var dupIndex = -1;
  4582. for ( var n = 0; n < 4; n ++ ) {
  4583. if ( indices[ n ] == indices[ ( n + 1 ) % 4 ] ) {
  4584. // if more than one duplicated vertex is found
  4585. // we can't generate any valid Face3's, thus
  4586. // we need to remove this face complete.
  4587. if ( dupIndex >= 0 ) {
  4588. faceIndicesToRemove.push( i );
  4589. }
  4590. dupIndex = n;
  4591. }
  4592. }
  4593. if ( dupIndex >= 0 ) {
  4594. indices.splice( dupIndex, 1 );
  4595. var newFace = new THREE.Face3( indices[0], indices[1], indices[2], face.normal, face.color, face.materialIndex );
  4596. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  4597. u = this.faceVertexUvs[ j ][ i ];
  4598. if ( u ) {
  4599. u.splice( dupIndex, 1 );
  4600. }
  4601. }
  4602. if( face.vertexNormals && face.vertexNormals.length > 0) {
  4603. newFace.vertexNormals = face.vertexNormals;
  4604. newFace.vertexNormals.splice( dupIndex, 1 );
  4605. }
  4606. if( face.vertexColors && face.vertexColors.length > 0 ) {
  4607. newFace.vertexColors = face.vertexColors;
  4608. newFace.vertexColors.splice( dupIndex, 1 );
  4609. }
  4610. this.faces[ i ] = newFace;
  4611. }
  4612. }
  4613. }
  4614. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  4615. this.faces.splice( i, 1 );
  4616. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  4617. this.faceVertexUvs[ j ].splice( i, 1 );
  4618. }
  4619. }
  4620. // Use unique set of vertices
  4621. var diff = this.vertices.length - unique.length;
  4622. this.vertices = unique;
  4623. return diff;
  4624. },
  4625. clone: function () {
  4626. var geometry = new THREE.Geometry();
  4627. var vertices = this.vertices;
  4628. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4629. geometry.vertices.push( vertices[ i ].clone() );
  4630. }
  4631. var faces = this.faces;
  4632. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  4633. geometry.faces.push( faces[ i ].clone() );
  4634. }
  4635. var uvs = this.faceVertexUvs[ 0 ];
  4636. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  4637. var uv = uvs[ i ], uvCopy = [];
  4638. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  4639. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  4640. }
  4641. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  4642. }
  4643. return geometry;
  4644. },
  4645. dispose: function () {
  4646. this.dispatchEvent( { type: 'dispose' } );
  4647. }
  4648. };
  4649. THREE.GeometryIdCount = 0;
  4650. /**
  4651. * @author alteredq / http://alteredqualia.com/
  4652. */
  4653. THREE.BufferGeometry = function () {
  4654. THREE.EventDispatcher.call( this );
  4655. this.id = THREE.GeometryIdCount ++;
  4656. // attributes
  4657. this.attributes = {};
  4658. // attributes typed arrays are kept only if dynamic flag is set
  4659. this.dynamic = false;
  4660. // offsets for chunks when using indexed elements
  4661. this.offsets = [];
  4662. // boundings
  4663. this.boundingBox = null;
  4664. this.boundingSphere = null;
  4665. this.hasTangents = false;
  4666. // for compatibility
  4667. this.morphTargets = [];
  4668. };
  4669. THREE.BufferGeometry.prototype = {
  4670. constructor : THREE.BufferGeometry,
  4671. applyMatrix: function ( matrix ) {
  4672. var positionArray;
  4673. var normalArray;
  4674. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  4675. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  4676. if ( positionArray !== undefined ) {
  4677. matrix.multiplyVector3Array( positionArray );
  4678. this.verticesNeedUpdate = true;
  4679. }
  4680. if ( normalArray !== undefined ) {
  4681. var normalMatrix = new THREE.Matrix3();
  4682. normalMatrix.getInverse( matrix ).transpose();
  4683. normalMatrix.multiplyVector3Array( normalArray );
  4684. this.normalizeNormals();
  4685. this.normalsNeedUpdate = true;
  4686. }
  4687. },
  4688. computeBoundingBox: function () {
  4689. if ( this.boundingBox === null ) {
  4690. this.boundingBox = new THREE.Box3();
  4691. }
  4692. var positions = this.attributes[ "position" ].array;
  4693. if ( positions ) {
  4694. var bb = this.boundingBox;
  4695. var x, y, z;
  4696. if( positions.length >= 3 ) {
  4697. bb.min.x = bb.max.x = positions[ 0 ];
  4698. bb.min.y = bb.max.y = positions[ 1 ];
  4699. bb.min.z = bb.max.z = positions[ 2 ];
  4700. }
  4701. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  4702. x = positions[ i ];
  4703. y = positions[ i + 1 ];
  4704. z = positions[ i + 2 ];
  4705. // bounding box
  4706. if ( x < bb.min.x ) {
  4707. bb.min.x = x;
  4708. } else if ( x > bb.max.x ) {
  4709. bb.max.x = x;
  4710. }
  4711. if ( y < bb.min.y ) {
  4712. bb.min.y = y;
  4713. } else if ( y > bb.max.y ) {
  4714. bb.max.y = y;
  4715. }
  4716. if ( z < bb.min.z ) {
  4717. bb.min.z = z;
  4718. } else if ( z > bb.max.z ) {
  4719. bb.max.z = z;
  4720. }
  4721. }
  4722. }
  4723. if ( positions === undefined || positions.length === 0 ) {
  4724. this.boundingBox.min.set( 0, 0, 0 );
  4725. this.boundingBox.max.set( 0, 0, 0 );
  4726. }
  4727. },
  4728. computeBoundingSphere: function () {
  4729. if ( this.boundingSphere === null ) {
  4730. this.boundingSphere = new THREE.Sphere();
  4731. }
  4732. var positions = this.attributes[ "position" ].array;
  4733. if ( positions ) {
  4734. var radiusSq, maxRadiusSq = 0;
  4735. var x, y, z;
  4736. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  4737. x = positions[ i ];
  4738. y = positions[ i + 1 ];
  4739. z = positions[ i + 2 ];
  4740. radiusSq = x * x + y * y + z * z;
  4741. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  4742. }
  4743. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  4744. }
  4745. },
  4746. computeVertexNormals: function () {
  4747. if ( this.attributes[ "position" ] ) {
  4748. var i, il;
  4749. var j, jl;
  4750. var nVertexElements = this.attributes[ "position" ].array.length;
  4751. if ( this.attributes[ "normal" ] === undefined ) {
  4752. this.attributes[ "normal" ] = {
  4753. itemSize: 3,
  4754. array: new Float32Array( nVertexElements ),
  4755. numItems: nVertexElements
  4756. };
  4757. } else {
  4758. // reset existing normals to zero
  4759. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  4760. this.attributes[ "normal" ].array[ i ] = 0;
  4761. }
  4762. }
  4763. var positions = this.attributes[ "position" ].array;
  4764. var normals = this.attributes[ "normal" ].array;
  4765. var vA, vB, vC, x, y, z,
  4766. pA = new THREE.Vector3(),
  4767. pB = new THREE.Vector3(),
  4768. pC = new THREE.Vector3(),
  4769. cb = new THREE.Vector3(),
  4770. ab = new THREE.Vector3();
  4771. // indexed elements
  4772. if ( this.attributes[ "index" ] ) {
  4773. var indices = this.attributes[ "index" ].array;
  4774. var offsets = this.offsets;
  4775. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  4776. var start = offsets[ j ].start;
  4777. var count = offsets[ j ].count;
  4778. var index = offsets[ j ].index;
  4779. for ( i = start, il = start + count; i < il; i += 3 ) {
  4780. vA = index + indices[ i ];
  4781. vB = index + indices[ i + 1 ];
  4782. vC = index + indices[ i + 2 ];
  4783. x = positions[ vA * 3 ];
  4784. y = positions[ vA * 3 + 1 ];
  4785. z = positions[ vA * 3 + 2 ];
  4786. pA.set( x, y, z );
  4787. x = positions[ vB * 3 ];
  4788. y = positions[ vB * 3 + 1 ];
  4789. z = positions[ vB * 3 + 2 ];
  4790. pB.set( x, y, z );
  4791. x = positions[ vC * 3 ];
  4792. y = positions[ vC * 3 + 1 ];
  4793. z = positions[ vC * 3 + 2 ];
  4794. pC.set( x, y, z );
  4795. cb.subVectors( pC, pB );
  4796. ab.subVectors( pA, pB );
  4797. cb.cross( ab );
  4798. normals[ vA * 3 ] += cb.x;
  4799. normals[ vA * 3 + 1 ] += cb.y;
  4800. normals[ vA * 3 + 2 ] += cb.z;
  4801. normals[ vB * 3 ] += cb.x;
  4802. normals[ vB * 3 + 1 ] += cb.y;
  4803. normals[ vB * 3 + 2 ] += cb.z;
  4804. normals[ vC * 3 ] += cb.x;
  4805. normals[ vC * 3 + 1 ] += cb.y;
  4806. normals[ vC * 3 + 2 ] += cb.z;
  4807. }
  4808. }
  4809. // non-indexed elements (unconnected triangle soup)
  4810. } else {
  4811. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  4812. x = positions[ i ];
  4813. y = positions[ i + 1 ];
  4814. z = positions[ i + 2 ];
  4815. pA.set( x, y, z );
  4816. x = positions[ i + 3 ];
  4817. y = positions[ i + 4 ];
  4818. z = positions[ i + 5 ];
  4819. pB.set( x, y, z );
  4820. x = positions[ i + 6 ];
  4821. y = positions[ i + 7 ];
  4822. z = positions[ i + 8 ];
  4823. pC.set( x, y, z );
  4824. cb.subVectors( pC, pB );
  4825. ab.subVectors( pA, pB );
  4826. cb.cross( ab );
  4827. normals[ i ] = cb.x;
  4828. normals[ i + 1 ] = cb.y;
  4829. normals[ i + 2 ] = cb.z;
  4830. normals[ i + 3 ] = cb.x;
  4831. normals[ i + 4 ] = cb.y;
  4832. normals[ i + 5 ] = cb.z;
  4833. normals[ i + 6 ] = cb.x;
  4834. normals[ i + 7 ] = cb.y;
  4835. normals[ i + 8 ] = cb.z;
  4836. }
  4837. }
  4838. this.normalizeNormals();
  4839. this.normalsNeedUpdate = true;
  4840. }
  4841. },
  4842. normalizeNormals: function () {
  4843. var normals = this.attributes[ "normal" ].array;
  4844. var x, y, z, n;
  4845. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  4846. x = normals[ i ];
  4847. y = normals[ i + 1 ];
  4848. z = normals[ i + 2 ];
  4849. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  4850. normals[ i ] *= n;
  4851. normals[ i + 1 ] *= n;
  4852. normals[ i + 2 ] *= n;
  4853. }
  4854. },
  4855. computeTangents: function () {
  4856. // based on http://www.terathon.com/code/tangent.html
  4857. // (per vertex tangents)
  4858. if ( this.attributes[ "index" ] === undefined ||
  4859. this.attributes[ "position" ] === undefined ||
  4860. this.attributes[ "normal" ] === undefined ||
  4861. this.attributes[ "uv" ] === undefined ) {
  4862. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  4863. return;
  4864. }
  4865. var indices = this.attributes[ "index" ].array;
  4866. var positions = this.attributes[ "position" ].array;
  4867. var normals = this.attributes[ "normal" ].array;
  4868. var uvs = this.attributes[ "uv" ].array;
  4869. var nVertices = positions.length / 3;
  4870. if ( this.attributes[ "tangent" ] === undefined ) {
  4871. var nTangentElements = 4 * nVertices;
  4872. this.attributes[ "tangent" ] = {
  4873. itemSize: 4,
  4874. array: new Float32Array( nTangentElements ),
  4875. numItems: nTangentElements
  4876. };
  4877. }
  4878. var tangents = this.attributes[ "tangent" ].array;
  4879. var tan1 = [], tan2 = [];
  4880. for ( var k = 0; k < nVertices; k ++ ) {
  4881. tan1[ k ] = new THREE.Vector3();
  4882. tan2[ k ] = new THREE.Vector3();
  4883. }
  4884. var xA, yA, zA,
  4885. xB, yB, zB,
  4886. xC, yC, zC,
  4887. uA, vA,
  4888. uB, vB,
  4889. uC, vC,
  4890. x1, x2, y1, y2, z1, z2,
  4891. s1, s2, t1, t2, r;
  4892. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  4893. function handleTriangle( a, b, c ) {
  4894. xA = positions[ a * 3 ];
  4895. yA = positions[ a * 3 + 1 ];
  4896. zA = positions[ a * 3 + 2 ];
  4897. xB = positions[ b * 3 ];
  4898. yB = positions[ b * 3 + 1 ];
  4899. zB = positions[ b * 3 + 2 ];
  4900. xC = positions[ c * 3 ];
  4901. yC = positions[ c * 3 + 1 ];
  4902. zC = positions[ c * 3 + 2 ];
  4903. uA = uvs[ a * 2 ];
  4904. vA = uvs[ a * 2 + 1 ];
  4905. uB = uvs[ b * 2 ];
  4906. vB = uvs[ b * 2 + 1 ];
  4907. uC = uvs[ c * 2 ];
  4908. vC = uvs[ c * 2 + 1 ];
  4909. x1 = xB - xA;
  4910. x2 = xC - xA;
  4911. y1 = yB - yA;
  4912. y2 = yC - yA;
  4913. z1 = zB - zA;
  4914. z2 = zC - zA;
  4915. s1 = uB - uA;
  4916. s2 = uC - uA;
  4917. t1 = vB - vA;
  4918. t2 = vC - vA;
  4919. r = 1.0 / ( s1 * t2 - s2 * t1 );
  4920. sdir.set(
  4921. ( t2 * x1 - t1 * x2 ) * r,
  4922. ( t2 * y1 - t1 * y2 ) * r,
  4923. ( t2 * z1 - t1 * z2 ) * r
  4924. );
  4925. tdir.set(
  4926. ( s1 * x2 - s2 * x1 ) * r,
  4927. ( s1 * y2 - s2 * y1 ) * r,
  4928. ( s1 * z2 - s2 * z1 ) * r
  4929. );
  4930. tan1[ a ].add( sdir );
  4931. tan1[ b ].add( sdir );
  4932. tan1[ c ].add( sdir );
  4933. tan2[ a ].add( tdir );
  4934. tan2[ b ].add( tdir );
  4935. tan2[ c ].add( tdir );
  4936. }
  4937. var i, il;
  4938. var j, jl;
  4939. var iA, iB, iC;
  4940. var offsets = this.offsets;
  4941. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  4942. var start = offsets[ j ].start;
  4943. var count = offsets[ j ].count;
  4944. var index = offsets[ j ].index;
  4945. for ( i = start, il = start + count; i < il; i += 3 ) {
  4946. iA = index + indices[ i ];
  4947. iB = index + indices[ i + 1 ];
  4948. iC = index + indices[ i + 2 ];
  4949. handleTriangle( iA, iB, iC );
  4950. }
  4951. }
  4952. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  4953. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  4954. var w, t, test;
  4955. var nx, ny, nz;
  4956. function handleVertex( v ) {
  4957. n.x = normals[ v * 3 ];
  4958. n.y = normals[ v * 3 + 1 ];
  4959. n.z = normals[ v * 3 + 2 ];
  4960. n2.copy( n );
  4961. t = tan1[ v ];
  4962. // Gram-Schmidt orthogonalize
  4963. tmp.copy( t );
  4964. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  4965. // Calculate handedness
  4966. tmp2.crossVectors( n2, t );
  4967. test = tmp2.dot( tan2[ v ] );
  4968. w = ( test < 0.0 ) ? -1.0 : 1.0;
  4969. tangents[ v * 4 ] = tmp.x;
  4970. tangents[ v * 4 + 1 ] = tmp.y;
  4971. tangents[ v * 4 + 2 ] = tmp.z;
  4972. tangents[ v * 4 + 3 ] = w;
  4973. }
  4974. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  4975. var start = offsets[ j ].start;
  4976. var count = offsets[ j ].count;
  4977. var index = offsets[ j ].index;
  4978. for ( i = start, il = start + count; i < il; i += 3 ) {
  4979. iA = index + indices[ i ];
  4980. iB = index + indices[ i + 1 ];
  4981. iC = index + indices[ i + 2 ];
  4982. handleVertex( iA );
  4983. handleVertex( iB );
  4984. handleVertex( iC );
  4985. }
  4986. }
  4987. this.hasTangents = true;
  4988. this.tangentsNeedUpdate = true;
  4989. },
  4990. dispose: function () {
  4991. this.dispatchEvent( { type: 'dispose' } );
  4992. }
  4993. };
  4994. /**
  4995. * @author mrdoob / http://mrdoob.com/
  4996. * @author mikael emtinger / http://gomo.se/
  4997. */
  4998. THREE.Camera = function () {
  4999. THREE.Object3D.call( this );
  5000. this.matrixWorldInverse = new THREE.Matrix4();
  5001. this.projectionMatrix = new THREE.Matrix4();
  5002. this.projectionMatrixInverse = new THREE.Matrix4();
  5003. };
  5004. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  5005. THREE.Camera.prototype.lookAt = function ( vector ) {
  5006. // TODO: Add hierarchy support.
  5007. this.matrix.lookAt( this.position, vector, this.up );
  5008. if ( this.rotationAutoUpdate === true ) {
  5009. if ( this.useQuaternion === false ) {
  5010. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  5011. } else {
  5012. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  5013. }
  5014. }
  5015. };
  5016. /**
  5017. * @author alteredq / http://alteredqualia.com/
  5018. */
  5019. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  5020. THREE.Camera.call( this );
  5021. this.left = left;
  5022. this.right = right;
  5023. this.top = top;
  5024. this.bottom = bottom;
  5025. this.near = ( near !== undefined ) ? near : 0.1;
  5026. this.far = ( far !== undefined ) ? far : 2000;
  5027. this.updateProjectionMatrix();
  5028. };
  5029. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  5030. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  5031. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  5032. };
  5033. /**
  5034. * @author mrdoob / http://mrdoob.com/
  5035. * @author greggman / http://games.greggman.com/
  5036. * @author zz85 / http://www.lab4games.net/zz85/blog
  5037. */
  5038. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  5039. THREE.Camera.call( this );
  5040. this.fov = fov !== undefined ? fov : 50;
  5041. this.aspect = aspect !== undefined ? aspect : 1;
  5042. this.near = near !== undefined ? near : 0.1;
  5043. this.far = far !== undefined ? far : 2000;
  5044. this.updateProjectionMatrix();
  5045. };
  5046. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  5047. /**
  5048. * Uses Focal Length (in mm) to estimate and set FOV
  5049. * 35mm (fullframe) camera is used if frame size is not specified;
  5050. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  5051. */
  5052. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  5053. if ( frameHeight === undefined ) frameHeight = 24;
  5054. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  5055. this.updateProjectionMatrix();
  5056. }
  5057. /**
  5058. * Sets an offset in a larger frustum. This is useful for multi-window or
  5059. * multi-monitor/multi-machine setups.
  5060. *
  5061. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  5062. * the monitors are in grid like this
  5063. *
  5064. * +---+---+---+
  5065. * | A | B | C |
  5066. * +---+---+---+
  5067. * | D | E | F |
  5068. * +---+---+---+
  5069. *
  5070. * then for each monitor you would call it like this
  5071. *
  5072. * var w = 1920;
  5073. * var h = 1080;
  5074. * var fullWidth = w * 3;
  5075. * var fullHeight = h * 2;
  5076. *
  5077. * --A--
  5078. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  5079. * --B--
  5080. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  5081. * --C--
  5082. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  5083. * --D--
  5084. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  5085. * --E--
  5086. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  5087. * --F--
  5088. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  5089. *
  5090. * Note there is no reason monitors have to be the same size or in a grid.
  5091. */
  5092. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  5093. this.fullWidth = fullWidth;
  5094. this.fullHeight = fullHeight;
  5095. this.x = x;
  5096. this.y = y;
  5097. this.width = width;
  5098. this.height = height;
  5099. this.updateProjectionMatrix();
  5100. };
  5101. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  5102. if ( this.fullWidth ) {
  5103. var aspect = this.fullWidth / this.fullHeight;
  5104. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  5105. var bottom = -top;
  5106. var left = aspect * bottom;
  5107. var right = aspect * top;
  5108. var width = Math.abs( right - left );
  5109. var height = Math.abs( top - bottom );
  5110. this.projectionMatrix.makeFrustum(
  5111. left + this.x * width / this.fullWidth,
  5112. left + ( this.x + this.width ) * width / this.fullWidth,
  5113. top - ( this.y + this.height ) * height / this.fullHeight,
  5114. top - this.y * height / this.fullHeight,
  5115. this.near,
  5116. this.far
  5117. );
  5118. } else {
  5119. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  5120. }
  5121. };
  5122. /**
  5123. * @author mrdoob / http://mrdoob.com/
  5124. * @author alteredq / http://alteredqualia.com/
  5125. */
  5126. THREE.Light = function ( hex ) {
  5127. THREE.Object3D.call( this );
  5128. this.color = new THREE.Color( hex );
  5129. };
  5130. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  5131. /**
  5132. * @author mrdoob / http://mrdoob.com/
  5133. */
  5134. THREE.AmbientLight = function ( hex ) {
  5135. THREE.Light.call( this, hex );
  5136. };
  5137. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  5138. /**
  5139. * @author MPanknin / http://www.redplant.de/
  5140. * @author alteredq / http://alteredqualia.com/
  5141. */
  5142. THREE.AreaLight = function ( hex, intensity ) {
  5143. THREE.Light.call( this, hex );
  5144. this.normal = new THREE.Vector3( 0, -1, 0 );
  5145. this.right = new THREE.Vector3( 1, 0, 0 );
  5146. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5147. this.width = 1.0;
  5148. this.height = 1.0;
  5149. this.constantAttenuation = 1.5;
  5150. this.linearAttenuation = 0.5;
  5151. this.quadraticAttenuation = 0.1;
  5152. };
  5153. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  5154. /**
  5155. * @author mrdoob / http://mrdoob.com/
  5156. * @author alteredq / http://alteredqualia.com/
  5157. */
  5158. THREE.DirectionalLight = function ( hex, intensity ) {
  5159. THREE.Light.call( this, hex );
  5160. this.position = new THREE.Vector3( 0, 1, 0 );
  5161. this.target = new THREE.Object3D();
  5162. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5163. this.castShadow = false;
  5164. this.onlyShadow = false;
  5165. //
  5166. this.shadowCameraNear = 50;
  5167. this.shadowCameraFar = 5000;
  5168. this.shadowCameraLeft = -500;
  5169. this.shadowCameraRight = 500;
  5170. this.shadowCameraTop = 500;
  5171. this.shadowCameraBottom = -500;
  5172. this.shadowCameraVisible = false;
  5173. this.shadowBias = 0;
  5174. this.shadowDarkness = 0.5;
  5175. this.shadowMapWidth = 512;
  5176. this.shadowMapHeight = 512;
  5177. //
  5178. this.shadowCascade = false;
  5179. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  5180. this.shadowCascadeCount = 2;
  5181. this.shadowCascadeBias = [ 0, 0, 0 ];
  5182. this.shadowCascadeWidth = [ 512, 512, 512 ];
  5183. this.shadowCascadeHeight = [ 512, 512, 512 ];
  5184. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  5185. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  5186. this.shadowCascadeArray = [];
  5187. //
  5188. this.shadowMap = null;
  5189. this.shadowMapSize = null;
  5190. this.shadowCamera = null;
  5191. this.shadowMatrix = null;
  5192. };
  5193. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  5194. /**
  5195. * @author alteredq / http://alteredqualia.com/
  5196. */
  5197. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  5198. THREE.Light.call( this, skyColorHex );
  5199. this.groundColor = new THREE.Color( groundColorHex );
  5200. this.position = new THREE.Vector3( 0, 100, 0 );
  5201. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5202. };
  5203. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  5204. /**
  5205. * @author mrdoob / http://mrdoob.com/
  5206. */
  5207. THREE.PointLight = function ( hex, intensity, distance ) {
  5208. THREE.Light.call( this, hex );
  5209. this.position = new THREE.Vector3( 0, 0, 0 );
  5210. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5211. this.distance = ( distance !== undefined ) ? distance : 0;
  5212. };
  5213. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  5214. /**
  5215. * @author alteredq / http://alteredqualia.com/
  5216. */
  5217. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  5218. THREE.Light.call( this, hex );
  5219. this.position = new THREE.Vector3( 0, 1, 0 );
  5220. this.target = new THREE.Object3D();
  5221. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5222. this.distance = ( distance !== undefined ) ? distance : 0;
  5223. this.angle = ( angle !== undefined ) ? angle : Math.PI / 2;
  5224. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  5225. this.castShadow = false;
  5226. this.onlyShadow = false;
  5227. //
  5228. this.shadowCameraNear = 50;
  5229. this.shadowCameraFar = 5000;
  5230. this.shadowCameraFov = 50;
  5231. this.shadowCameraVisible = false;
  5232. this.shadowBias = 0;
  5233. this.shadowDarkness = 0.5;
  5234. this.shadowMapWidth = 512;
  5235. this.shadowMapHeight = 512;
  5236. //
  5237. this.shadowMap = null;
  5238. this.shadowMapSize = null;
  5239. this.shadowCamera = null;
  5240. this.shadowMatrix = null;
  5241. };
  5242. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  5243. /**
  5244. * @author alteredq / http://alteredqualia.com/
  5245. */
  5246. THREE.Loader = function ( showStatus ) {
  5247. this.showStatus = showStatus;
  5248. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  5249. this.onLoadStart = function () {};
  5250. this.onLoadProgress = function () {};
  5251. this.onLoadComplete = function () {};
  5252. };
  5253. THREE.Loader.prototype = {
  5254. constructor: THREE.Loader,
  5255. crossOrigin: 'anonymous',
  5256. addStatusElement: function () {
  5257. var e = document.createElement( "div" );
  5258. e.style.position = "absolute";
  5259. e.style.right = "0px";
  5260. e.style.top = "0px";
  5261. e.style.fontSize = "0.8em";
  5262. e.style.textAlign = "left";
  5263. e.style.background = "rgba(0,0,0,0.25)";
  5264. e.style.color = "#fff";
  5265. e.style.width = "120px";
  5266. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  5267. e.style.zIndex = 1000;
  5268. e.innerHTML = "Loading ...";
  5269. return e;
  5270. },
  5271. updateProgress: function ( progress ) {
  5272. var message = "Loaded ";
  5273. if ( progress.total ) {
  5274. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  5275. } else {
  5276. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  5277. }
  5278. this.statusDomElement.innerHTML = message;
  5279. },
  5280. extractUrlBase: function ( url ) {
  5281. var parts = url.split( '/' );
  5282. parts.pop();
  5283. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  5284. },
  5285. initMaterials: function ( materials, texturePath ) {
  5286. var array = [];
  5287. for ( var i = 0; i < materials.length; ++ i ) {
  5288. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  5289. }
  5290. return array;
  5291. },
  5292. needsTangents: function ( materials ) {
  5293. for( var i = 0, il = materials.length; i < il; i ++ ) {
  5294. var m = materials[ i ];
  5295. if ( m instanceof THREE.ShaderMaterial ) return true;
  5296. }
  5297. return false;
  5298. },
  5299. createMaterial: function ( m, texturePath ) {
  5300. var _this = this;
  5301. function is_pow2( n ) {
  5302. var l = Math.log( n ) / Math.LN2;
  5303. return Math.floor( l ) == l;
  5304. }
  5305. function nearest_pow2( n ) {
  5306. var l = Math.log( n ) / Math.LN2;
  5307. return Math.pow( 2, Math.round( l ) );
  5308. }
  5309. function load_image( where, url ) {
  5310. var image = new Image();
  5311. image.onload = function () {
  5312. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  5313. var width = nearest_pow2( this.width );
  5314. var height = nearest_pow2( this.height );
  5315. where.image.width = width;
  5316. where.image.height = height;
  5317. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  5318. } else {
  5319. where.image = this;
  5320. }
  5321. where.needsUpdate = true;
  5322. };
  5323. image.crossOrigin = _this.crossOrigin;
  5324. image.src = url;
  5325. }
  5326. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  5327. var isCompressed = sourceFile.toLowerCase().endsWith( ".dds" );
  5328. var fullPath = texturePath + "/" + sourceFile;
  5329. if ( isCompressed ) {
  5330. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  5331. where[ name ] = texture;
  5332. } else {
  5333. var texture = document.createElement( 'canvas' );
  5334. where[ name ] = new THREE.Texture( texture );
  5335. }
  5336. where[ name ].sourceFile = sourceFile;
  5337. if( repeat ) {
  5338. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  5339. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  5340. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  5341. }
  5342. if ( offset ) {
  5343. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  5344. }
  5345. if ( wrap ) {
  5346. var wrapMap = {
  5347. "repeat": THREE.RepeatWrapping,
  5348. "mirror": THREE.MirroredRepeatWrapping
  5349. }
  5350. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  5351. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  5352. }
  5353. if ( anisotropy ) {
  5354. where[ name ].anisotropy = anisotropy;
  5355. }
  5356. if ( ! isCompressed ) {
  5357. load_image( where[ name ], fullPath );
  5358. }
  5359. }
  5360. function rgb2hex( rgb ) {
  5361. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  5362. }
  5363. // defaults
  5364. var mtype = "MeshLambertMaterial";
  5365. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  5366. // parameters from model file
  5367. if ( m.shading ) {
  5368. var shading = m.shading.toLowerCase();
  5369. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  5370. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  5371. }
  5372. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  5373. mpars.blending = THREE[ m.blending ];
  5374. }
  5375. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  5376. mpars.transparent = m.transparent;
  5377. }
  5378. if ( m.depthTest !== undefined ) {
  5379. mpars.depthTest = m.depthTest;
  5380. }
  5381. if ( m.depthWrite !== undefined ) {
  5382. mpars.depthWrite = m.depthWrite;
  5383. }
  5384. if ( m.visible !== undefined ) {
  5385. mpars.visible = m.visible;
  5386. }
  5387. if ( m.flipSided !== undefined ) {
  5388. mpars.side = THREE.BackSide;
  5389. }
  5390. if ( m.doubleSided !== undefined ) {
  5391. mpars.side = THREE.DoubleSide;
  5392. }
  5393. if ( m.wireframe !== undefined ) {
  5394. mpars.wireframe = m.wireframe;
  5395. }
  5396. if ( m.vertexColors !== undefined ) {
  5397. if ( m.vertexColors === "face" ) {
  5398. mpars.vertexColors = THREE.FaceColors;
  5399. } else if ( m.vertexColors ) {
  5400. mpars.vertexColors = THREE.VertexColors;
  5401. }
  5402. }
  5403. // colors
  5404. if ( m.colorDiffuse ) {
  5405. mpars.color = rgb2hex( m.colorDiffuse );
  5406. } else if ( m.DbgColor ) {
  5407. mpars.color = m.DbgColor;
  5408. }
  5409. if ( m.colorSpecular ) {
  5410. mpars.specular = rgb2hex( m.colorSpecular );
  5411. }
  5412. if ( m.colorAmbient ) {
  5413. mpars.ambient = rgb2hex( m.colorAmbient );
  5414. }
  5415. // modifiers
  5416. if ( m.transparency ) {
  5417. mpars.opacity = m.transparency;
  5418. }
  5419. if ( m.specularCoef ) {
  5420. mpars.shininess = m.specularCoef;
  5421. }
  5422. // textures
  5423. if ( m.mapDiffuse && texturePath ) {
  5424. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  5425. }
  5426. if ( m.mapLight && texturePath ) {
  5427. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  5428. }
  5429. if ( m.mapBump && texturePath ) {
  5430. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  5431. }
  5432. if ( m.mapNormal && texturePath ) {
  5433. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  5434. }
  5435. if ( m.mapSpecular && texturePath ) {
  5436. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  5437. }
  5438. //
  5439. if ( m.mapBumpScale ) {
  5440. mpars.bumpScale = m.mapBumpScale;
  5441. }
  5442. // special case for normal mapped material
  5443. if ( m.mapNormal ) {
  5444. var shader = THREE.ShaderUtils.lib[ "normal" ];
  5445. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5446. uniforms[ "tNormal" ].value = mpars.normalMap;
  5447. if ( m.mapNormalFactor ) {
  5448. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  5449. }
  5450. if ( mpars.map ) {
  5451. uniforms[ "tDiffuse" ].value = mpars.map;
  5452. uniforms[ "enableDiffuse" ].value = true;
  5453. }
  5454. if ( mpars.specularMap ) {
  5455. uniforms[ "tSpecular" ].value = mpars.specularMap;
  5456. uniforms[ "enableSpecular" ].value = true;
  5457. }
  5458. if ( mpars.lightMap ) {
  5459. uniforms[ "tAO" ].value = mpars.lightMap;
  5460. uniforms[ "enableAO" ].value = true;
  5461. }
  5462. // for the moment don't handle displacement texture
  5463. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  5464. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  5465. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  5466. uniforms[ "uShininess" ].value = mpars.shininess;
  5467. if ( mpars.opacity !== undefined ) {
  5468. uniforms[ "uOpacity" ].value = mpars.opacity;
  5469. }
  5470. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5471. var material = new THREE.ShaderMaterial( parameters );
  5472. if ( mpars.transparent ) {
  5473. material.transparent = true;
  5474. }
  5475. } else {
  5476. var material = new THREE[ mtype ]( mpars );
  5477. }
  5478. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  5479. return material;
  5480. }
  5481. };
  5482. /**
  5483. * @author mrdoob / http://mrdoob.com/
  5484. */
  5485. THREE.ImageLoader = function () {
  5486. THREE.EventDispatcher.call( this );
  5487. this.crossOrigin = null;
  5488. };
  5489. THREE.ImageLoader.prototype = {
  5490. constructor: THREE.ImageLoader,
  5491. load: function ( url, image ) {
  5492. var scope = this;
  5493. if ( image === undefined ) image = new Image();
  5494. image.addEventListener( 'load', function () {
  5495. scope.dispatchEvent( { type: 'load', content: image } );
  5496. }, false );
  5497. image.addEventListener( 'error', function () {
  5498. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  5499. }, false );
  5500. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  5501. image.src = url;
  5502. }
  5503. }
  5504. /**
  5505. * @author mrdoob / http://mrdoob.com/
  5506. * @author alteredq / http://alteredqualia.com/
  5507. */
  5508. THREE.JSONLoader = function ( showStatus ) {
  5509. THREE.Loader.call( this, showStatus );
  5510. this.withCredentials = false;
  5511. };
  5512. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  5513. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  5514. var scope = this;
  5515. // todo: unify load API to for easier SceneLoader use
  5516. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  5517. this.onLoadStart();
  5518. this.loadAjaxJSON( this, url, callback, texturePath );
  5519. };
  5520. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  5521. var xhr = new XMLHttpRequest();
  5522. var length = 0;
  5523. xhr.withCredentials = this.withCredentials;
  5524. xhr.onreadystatechange = function () {
  5525. if ( xhr.readyState === xhr.DONE ) {
  5526. if ( xhr.status === 200 || xhr.status === 0 ) {
  5527. if ( xhr.responseText ) {
  5528. var json = JSON.parse( xhr.responseText );
  5529. context.createModel( json, callback, texturePath );
  5530. } else {
  5531. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  5532. }
  5533. // in context of more complex asset initialization
  5534. // do not block on single failed file
  5535. // maybe should go even one more level up
  5536. context.onLoadComplete();
  5537. } else {
  5538. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5539. }
  5540. } else if ( xhr.readyState === xhr.LOADING ) {
  5541. if ( callbackProgress ) {
  5542. if ( length === 0 ) {
  5543. length = xhr.getResponseHeader( "Content-Length" );
  5544. }
  5545. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  5546. }
  5547. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  5548. length = xhr.getResponseHeader( "Content-Length" );
  5549. }
  5550. };
  5551. xhr.open( "GET", url, true );
  5552. xhr.send( null );
  5553. };
  5554. THREE.JSONLoader.prototype.createModel = function ( json, callback, texturePath ) {
  5555. var scope = this,
  5556. geometry = new THREE.Geometry(),
  5557. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  5558. parseModel( scale );
  5559. parseSkin();
  5560. parseMorphing( scale );
  5561. geometry.computeCentroids();
  5562. geometry.computeFaceNormals();
  5563. function parseModel( scale ) {
  5564. function isBitSet( value, position ) {
  5565. return value & ( 1 << position );
  5566. }
  5567. var i, j, fi,
  5568. offset, zLength, nVertices,
  5569. colorIndex, normalIndex, uvIndex, materialIndex,
  5570. type,
  5571. isQuad,
  5572. hasMaterial,
  5573. hasFaceUv, hasFaceVertexUv,
  5574. hasFaceNormal, hasFaceVertexNormal,
  5575. hasFaceColor, hasFaceVertexColor,
  5576. vertex, face, color, normal,
  5577. uvLayer, uvs, u, v,
  5578. faces = json.faces,
  5579. vertices = json.vertices,
  5580. normals = json.normals,
  5581. colors = json.colors,
  5582. nUvLayers = 0;
  5583. // disregard empty arrays
  5584. for ( i = 0; i < json.uvs.length; i++ ) {
  5585. if ( json.uvs[ i ].length ) nUvLayers ++;
  5586. }
  5587. for ( i = 0; i < nUvLayers; i++ ) {
  5588. geometry.faceUvs[ i ] = [];
  5589. geometry.faceVertexUvs[ i ] = [];
  5590. }
  5591. offset = 0;
  5592. zLength = vertices.length;
  5593. while ( offset < zLength ) {
  5594. vertex = new THREE.Vector3();
  5595. vertex.x = vertices[ offset ++ ] * scale;
  5596. vertex.y = vertices[ offset ++ ] * scale;
  5597. vertex.z = vertices[ offset ++ ] * scale;
  5598. geometry.vertices.push( vertex );
  5599. }
  5600. offset = 0;
  5601. zLength = faces.length;
  5602. while ( offset < zLength ) {
  5603. type = faces[ offset ++ ];
  5604. isQuad = isBitSet( type, 0 );
  5605. hasMaterial = isBitSet( type, 1 );
  5606. hasFaceUv = isBitSet( type, 2 );
  5607. hasFaceVertexUv = isBitSet( type, 3 );
  5608. hasFaceNormal = isBitSet( type, 4 );
  5609. hasFaceVertexNormal = isBitSet( type, 5 );
  5610. hasFaceColor = isBitSet( type, 6 );
  5611. hasFaceVertexColor = isBitSet( type, 7 );
  5612. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  5613. if ( isQuad ) {
  5614. face = new THREE.Face4();
  5615. face.a = faces[ offset ++ ];
  5616. face.b = faces[ offset ++ ];
  5617. face.c = faces[ offset ++ ];
  5618. face.d = faces[ offset ++ ];
  5619. nVertices = 4;
  5620. } else {
  5621. face = new THREE.Face3();
  5622. face.a = faces[ offset ++ ];
  5623. face.b = faces[ offset ++ ];
  5624. face.c = faces[ offset ++ ];
  5625. nVertices = 3;
  5626. }
  5627. if ( hasMaterial ) {
  5628. materialIndex = faces[ offset ++ ];
  5629. face.materialIndex = materialIndex;
  5630. }
  5631. // to get face <=> uv index correspondence
  5632. fi = geometry.faces.length;
  5633. if ( hasFaceUv ) {
  5634. for ( i = 0; i < nUvLayers; i++ ) {
  5635. uvLayer = json.uvs[ i ];
  5636. uvIndex = faces[ offset ++ ];
  5637. u = uvLayer[ uvIndex * 2 ];
  5638. v = uvLayer[ uvIndex * 2 + 1 ];
  5639. geometry.faceUvs[ i ][ fi ] = new THREE.Vector2( u, v );
  5640. }
  5641. }
  5642. if ( hasFaceVertexUv ) {
  5643. for ( i = 0; i < nUvLayers; i++ ) {
  5644. uvLayer = json.uvs[ i ];
  5645. uvs = [];
  5646. for ( j = 0; j < nVertices; j ++ ) {
  5647. uvIndex = faces[ offset ++ ];
  5648. u = uvLayer[ uvIndex * 2 ];
  5649. v = uvLayer[ uvIndex * 2 + 1 ];
  5650. uvs[ j ] = new THREE.Vector2( u, v );
  5651. }
  5652. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  5653. }
  5654. }
  5655. if ( hasFaceNormal ) {
  5656. normalIndex = faces[ offset ++ ] * 3;
  5657. normal = new THREE.Vector3();
  5658. normal.x = normals[ normalIndex ++ ];
  5659. normal.y = normals[ normalIndex ++ ];
  5660. normal.z = normals[ normalIndex ];
  5661. face.normal = normal;
  5662. }
  5663. if ( hasFaceVertexNormal ) {
  5664. for ( i = 0; i < nVertices; i++ ) {
  5665. normalIndex = faces[ offset ++ ] * 3;
  5666. normal = new THREE.Vector3();
  5667. normal.x = normals[ normalIndex ++ ];
  5668. normal.y = normals[ normalIndex ++ ];
  5669. normal.z = normals[ normalIndex ];
  5670. face.vertexNormals.push( normal );
  5671. }
  5672. }
  5673. if ( hasFaceColor ) {
  5674. colorIndex = faces[ offset ++ ];
  5675. color = new THREE.Color( colors[ colorIndex ] );
  5676. face.color = color;
  5677. }
  5678. if ( hasFaceVertexColor ) {
  5679. for ( i = 0; i < nVertices; i++ ) {
  5680. colorIndex = faces[ offset ++ ];
  5681. color = new THREE.Color( colors[ colorIndex ] );
  5682. face.vertexColors.push( color );
  5683. }
  5684. }
  5685. geometry.faces.push( face );
  5686. }
  5687. };
  5688. function parseSkin() {
  5689. var i, l, x, y, z, w, a, b, c, d;
  5690. if ( json.skinWeights ) {
  5691. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  5692. x = json.skinWeights[ i ];
  5693. y = json.skinWeights[ i + 1 ];
  5694. z = 0;
  5695. w = 0;
  5696. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  5697. }
  5698. }
  5699. if ( json.skinIndices ) {
  5700. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  5701. a = json.skinIndices[ i ];
  5702. b = json.skinIndices[ i + 1 ];
  5703. c = 0;
  5704. d = 0;
  5705. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  5706. }
  5707. }
  5708. geometry.bones = json.bones;
  5709. geometry.animation = json.animation;
  5710. };
  5711. function parseMorphing( scale ) {
  5712. if ( json.morphTargets !== undefined ) {
  5713. var i, l, v, vl, dstVertices, srcVertices;
  5714. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  5715. geometry.morphTargets[ i ] = {};
  5716. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  5717. geometry.morphTargets[ i ].vertices = [];
  5718. dstVertices = geometry.morphTargets[ i ].vertices;
  5719. srcVertices = json.morphTargets [ i ].vertices;
  5720. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  5721. var vertex = new THREE.Vector3();
  5722. vertex.x = srcVertices[ v ] * scale;
  5723. vertex.y = srcVertices[ v + 1 ] * scale;
  5724. vertex.z = srcVertices[ v + 2 ] * scale;
  5725. dstVertices.push( vertex );
  5726. }
  5727. }
  5728. }
  5729. if ( json.morphColors !== undefined ) {
  5730. var i, l, c, cl, dstColors, srcColors, color;
  5731. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  5732. geometry.morphColors[ i ] = {};
  5733. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  5734. geometry.morphColors[ i ].colors = [];
  5735. dstColors = geometry.morphColors[ i ].colors;
  5736. srcColors = json.morphColors [ i ].colors;
  5737. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  5738. color = new THREE.Color( 0xffaa00 );
  5739. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  5740. dstColors.push( color );
  5741. }
  5742. }
  5743. }
  5744. };
  5745. var materials = this.initMaterials( json.materials, texturePath );
  5746. if ( this.needsTangents( materials ) ) geometry.computeTangents();
  5747. callback( geometry, materials );
  5748. };
  5749. /**
  5750. * @author mrdoob / http://mrdoob.com/
  5751. */
  5752. THREE.LoadingMonitor = function () {
  5753. THREE.EventDispatcher.call( this );
  5754. var scope = this;
  5755. var loaded = 0;
  5756. var total = 0;
  5757. var onLoad = function ( event ) {
  5758. loaded ++;
  5759. scope.dispatchEvent( { type: 'progress', loaded: loaded, total: total } );
  5760. if ( loaded === total ) {
  5761. scope.dispatchEvent( { type: 'load' } );
  5762. }
  5763. };
  5764. this.add = function ( loader ) {
  5765. total ++;
  5766. loader.addEventListener( 'load', onLoad, false );
  5767. };
  5768. };
  5769. /**
  5770. * @author alteredq / http://alteredqualia.com/
  5771. */
  5772. THREE.SceneLoader = function () {
  5773. this.onLoadStart = function () {};
  5774. this.onLoadProgress = function() {};
  5775. this.onLoadComplete = function () {};
  5776. this.callbackSync = function () {};
  5777. this.callbackProgress = function () {};
  5778. this.geometryHandlerMap = {};
  5779. this.hierarchyHandlerMap = {};
  5780. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  5781. };
  5782. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  5783. THREE.SceneLoader.prototype.load = function ( url, callbackFinished ) {
  5784. var scope = this;
  5785. var xhr = new XMLHttpRequest();
  5786. xhr.onreadystatechange = function () {
  5787. if ( xhr.readyState === 4 ) {
  5788. if ( xhr.status === 200 || xhr.status === 0 ) {
  5789. var json = JSON.parse( xhr.responseText );
  5790. scope.parse( json, callbackFinished, url );
  5791. } else {
  5792. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5793. }
  5794. }
  5795. };
  5796. xhr.open( "GET", url, true );
  5797. xhr.send( null );
  5798. };
  5799. THREE.SceneLoader.prototype.addGeometryHandler = function ( typeID, loaderClass ) {
  5800. this.geometryHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5801. };
  5802. THREE.SceneLoader.prototype.addHierarchyHandler = function ( typeID, loaderClass ) {
  5803. this.hierarchyHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5804. };
  5805. THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
  5806. var scope = this;
  5807. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  5808. var geometry, material, camera, fog,
  5809. texture, images, color,
  5810. light, hex, intensity,
  5811. counter_models, counter_textures,
  5812. total_models, total_textures,
  5813. result;
  5814. var target_array = [];
  5815. var data = json;
  5816. // async geometry loaders
  5817. for ( var typeID in this.geometryHandlerMap ) {
  5818. var loaderClass = this.geometryHandlerMap[ typeID ][ "loaderClass" ];
  5819. this.geometryHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5820. }
  5821. // async hierachy loaders
  5822. for ( var typeID in this.hierarchyHandlerMap ) {
  5823. var loaderClass = this.hierarchyHandlerMap[ typeID ][ "loaderClass" ];
  5824. this.hierarchyHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5825. }
  5826. counter_models = 0;
  5827. counter_textures = 0;
  5828. result = {
  5829. scene: new THREE.Scene(),
  5830. geometries: {},
  5831. face_materials: {},
  5832. materials: {},
  5833. textures: {},
  5834. objects: {},
  5835. cameras: {},
  5836. lights: {},
  5837. fogs: {},
  5838. empties: {}
  5839. };
  5840. if ( data.transform ) {
  5841. var position = data.transform.position,
  5842. rotation = data.transform.rotation,
  5843. scale = data.transform.scale;
  5844. if ( position )
  5845. result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
  5846. if ( rotation )
  5847. result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
  5848. if ( scale )
  5849. result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
  5850. if ( position || rotation || scale ) {
  5851. result.scene.updateMatrix();
  5852. result.scene.updateMatrixWorld();
  5853. }
  5854. }
  5855. function get_url( source_url, url_type ) {
  5856. if ( url_type == "relativeToHTML" ) {
  5857. return source_url;
  5858. } else {
  5859. return urlBase + "/" + source_url;
  5860. }
  5861. };
  5862. // toplevel loader function, delegates to handle_children
  5863. function handle_objects() {
  5864. handle_children( result.scene, data.objects );
  5865. }
  5866. // handle all the children from the loaded json and attach them to given parent
  5867. function handle_children( parent, children ) {
  5868. var mat, dst, pos, rot, scl, quat;
  5869. for ( var objID in children ) {
  5870. // check by id if child has already been handled,
  5871. // if not, create new object
  5872. if ( result.objects[ objID ] === undefined ) {
  5873. var objJSON = children[ objID ];
  5874. var object = null;
  5875. // meshes
  5876. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlerMap ) ) {
  5877. if ( objJSON.loading === undefined ) {
  5878. var reservedTypes = { "type": 1, "url": 1, "material": 1,
  5879. "position": 1, "rotation": 1, "scale" : 1,
  5880. "visible": 1, "children": 1, "properties": 1,
  5881. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1 };
  5882. var loaderParameters = {};
  5883. for ( var parType in objJSON ) {
  5884. if ( ! ( parType in reservedTypes ) ) {
  5885. loaderParameters[ parType ] = objJSON[ parType ];
  5886. }
  5887. }
  5888. material = result.materials[ objJSON.material ];
  5889. objJSON.loading = true;
  5890. var loader = scope.hierarchyHandlerMap[ objJSON.type ][ "loaderObject" ];
  5891. // ColladaLoader
  5892. if ( loader.options ) {
  5893. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  5894. // UTF8Loader
  5895. // OBJLoader
  5896. } else {
  5897. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  5898. }
  5899. }
  5900. } else if ( objJSON.geometry !== undefined ) {
  5901. geometry = result.geometries[ objJSON.geometry ];
  5902. // geometry already loaded
  5903. if ( geometry ) {
  5904. var needsTangents = false;
  5905. material = result.materials[ objJSON.material ];
  5906. needsTangents = material instanceof THREE.ShaderMaterial;
  5907. pos = objJSON.position;
  5908. rot = objJSON.rotation;
  5909. scl = objJSON.scale;
  5910. mat = objJSON.matrix;
  5911. quat = objJSON.quaternion;
  5912. // use materials from the model file
  5913. // if there is no material specified in the object
  5914. if ( ! objJSON.material ) {
  5915. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  5916. }
  5917. // use materials from the model file
  5918. // if there is just empty face material
  5919. // (must create new material as each model has its own face material)
  5920. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  5921. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  5922. }
  5923. if ( material instanceof THREE.MeshFaceMaterial ) {
  5924. for ( var i = 0; i < material.materials.length; i ++ ) {
  5925. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  5926. }
  5927. }
  5928. if ( needsTangents ) {
  5929. geometry.computeTangents();
  5930. }
  5931. if ( objJSON.skin ) {
  5932. object = new THREE.SkinnedMesh( geometry, material );
  5933. } else if ( objJSON.morph ) {
  5934. object = new THREE.MorphAnimMesh( geometry, material );
  5935. if ( objJSON.duration !== undefined ) {
  5936. object.duration = objJSON.duration;
  5937. }
  5938. if ( objJSON.time !== undefined ) {
  5939. object.time = objJSON.time;
  5940. }
  5941. if ( objJSON.mirroredLoop !== undefined ) {
  5942. object.mirroredLoop = objJSON.mirroredLoop;
  5943. }
  5944. if ( material.morphNormals ) {
  5945. geometry.computeMorphNormals();
  5946. }
  5947. } else {
  5948. object = new THREE.Mesh( geometry, material );
  5949. }
  5950. object.name = objID;
  5951. if ( mat ) {
  5952. object.matrixAutoUpdate = false;
  5953. object.matrix.set(
  5954. mat[0], mat[1], mat[2], mat[3],
  5955. mat[4], mat[5], mat[6], mat[7],
  5956. mat[8], mat[9], mat[10], mat[11],
  5957. mat[12], mat[13], mat[14], mat[15]
  5958. );
  5959. } else {
  5960. object.position.set( pos[0], pos[1], pos[2] );
  5961. if ( quat ) {
  5962. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  5963. object.useQuaternion = true;
  5964. } else {
  5965. object.rotation.set( rot[0], rot[1], rot[2] );
  5966. }
  5967. object.scale.set( scl[0], scl[1], scl[2] );
  5968. }
  5969. object.visible = objJSON.visible;
  5970. object.castShadow = objJSON.castShadow;
  5971. object.receiveShadow = objJSON.receiveShadow;
  5972. parent.add( object );
  5973. result.objects[ objID ] = object;
  5974. }
  5975. // lights
  5976. } else if ( objJSON.type === "DirectionalLight" || objJSON.type === "PointLight" || objJSON.type === "AmbientLight" ) {
  5977. hex = ( objJSON.color !== undefined ) ? objJSON.color : 0xffffff;
  5978. intensity = ( objJSON.intensity !== undefined ) ? objJSON.intensity : 1;
  5979. if ( objJSON.type === "DirectionalLight" ) {
  5980. pos = objJSON.direction;
  5981. light = new THREE.DirectionalLight( hex, intensity );
  5982. light.position.set( pos[0], pos[1], pos[2] );
  5983. if ( objJSON.target ) {
  5984. target_array.push( { "object": light, "targetName" : objJSON.target } );
  5985. // kill existing default target
  5986. // otherwise it gets added to scene when parent gets added
  5987. light.target = null;
  5988. }
  5989. } else if ( objJSON.type === "PointLight" ) {
  5990. pos = objJSON.position;
  5991. dst = objJSON.distance;
  5992. light = new THREE.PointLight( hex, intensity, dst );
  5993. light.position.set( pos[0], pos[1], pos[2] );
  5994. } else if ( objJSON.type === "AmbientLight" ) {
  5995. light = new THREE.AmbientLight( hex );
  5996. }
  5997. parent.add( light );
  5998. light.name = objID;
  5999. result.lights[ objID ] = light;
  6000. result.objects[ objID ] = light;
  6001. // cameras
  6002. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  6003. if ( objJSON.type === "PerspectiveCamera" ) {
  6004. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  6005. } else if ( objJSON.type === "OrthographicCamera" ) {
  6006. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  6007. }
  6008. pos = objJSON.position;
  6009. camera.position.set( pos[0], pos[1], pos[2] );
  6010. parent.add( camera );
  6011. camera.name = objID;
  6012. result.cameras[ objID ] = camera;
  6013. result.objects[ objID ] = camera;
  6014. // pure Object3D
  6015. } else {
  6016. pos = objJSON.position;
  6017. rot = objJSON.rotation;
  6018. scl = objJSON.scale;
  6019. quat = objJSON.quaternion;
  6020. object = new THREE.Object3D();
  6021. object.name = objID;
  6022. object.position.set( pos[0], pos[1], pos[2] );
  6023. if ( quat ) {
  6024. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  6025. object.useQuaternion = true;
  6026. } else {
  6027. object.rotation.set( rot[0], rot[1], rot[2] );
  6028. }
  6029. object.scale.set( scl[0], scl[1], scl[2] );
  6030. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  6031. parent.add( object );
  6032. result.objects[ objID ] = object;
  6033. result.empties[ objID ] = object;
  6034. }
  6035. if ( object ) {
  6036. if ( objJSON.properties !== undefined ) {
  6037. for ( var key in objJSON.properties ) {
  6038. var value = objJSON.properties[ key ];
  6039. object.properties[ key ] = value;
  6040. }
  6041. }
  6042. if ( objJSON.children !== undefined ) {
  6043. handle_children( object, objJSON.children );
  6044. }
  6045. }
  6046. }
  6047. }
  6048. };
  6049. function handle_mesh( geo, mat, id ) {
  6050. result.geometries[ id ] = geo;
  6051. result.face_materials[ id ] = mat;
  6052. handle_objects();
  6053. };
  6054. function handle_hierarchy( node, id, parent, material, obj ) {
  6055. var p = obj.position;
  6056. var r = obj.rotation;
  6057. var q = obj.quaternion;
  6058. var s = obj.scale;
  6059. node.position.set( p[0], p[1], p[2] );
  6060. if ( q ) {
  6061. node.quaternion.set( q[0], q[1], q[2], q[3] );
  6062. node.useQuaternion = true;
  6063. } else {
  6064. node.rotation.set( r[0], r[1], r[2] );
  6065. }
  6066. node.scale.set( s[0], s[1], s[2] );
  6067. // override children materials
  6068. // if object material was specified in JSON explicitly
  6069. if ( material ) {
  6070. node.traverse( function ( child ) {
  6071. child.material = material;
  6072. } );
  6073. }
  6074. // override children visibility
  6075. // with root node visibility as specified in JSON
  6076. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  6077. node.traverse( function ( child ) {
  6078. child.visible = visible;
  6079. } );
  6080. parent.add( node );
  6081. node.name = id;
  6082. result.objects[ id ] = node;
  6083. handle_objects();
  6084. };
  6085. function create_callback_geometry( id ) {
  6086. return function( geo, mat ) {
  6087. handle_mesh( geo, mat, id );
  6088. counter_models -= 1;
  6089. scope.onLoadComplete();
  6090. async_callback_gate();
  6091. }
  6092. };
  6093. function create_callback_hierachy( id, parent, material, obj ) {
  6094. return function( event ) {
  6095. var result;
  6096. // loaders which use EventDispatcher
  6097. if ( event.content ) {
  6098. result = event.content;
  6099. // ColladaLoader
  6100. } else if ( event.dae ) {
  6101. result = event.scene;
  6102. // UTF8Loader
  6103. } else {
  6104. result = event;
  6105. }
  6106. handle_hierarchy( result, id, parent, material, obj );
  6107. counter_models -= 1;
  6108. scope.onLoadComplete();
  6109. async_callback_gate();
  6110. }
  6111. };
  6112. function create_callback_embed( id ) {
  6113. return function( geo, mat ) {
  6114. result.geometries[ id ] = geo;
  6115. result.face_materials[ id ] = mat;
  6116. }
  6117. };
  6118. function async_callback_gate() {
  6119. var progress = {
  6120. totalModels : total_models,
  6121. totalTextures : total_textures,
  6122. loadedModels : total_models - counter_models,
  6123. loadedTextures : total_textures - counter_textures
  6124. };
  6125. scope.callbackProgress( progress, result );
  6126. scope.onLoadProgress();
  6127. if ( counter_models === 0 && counter_textures === 0 ) {
  6128. finalize();
  6129. callbackFinished( result );
  6130. }
  6131. };
  6132. function finalize() {
  6133. // take care of targets which could be asynchronously loaded objects
  6134. for ( var i = 0; i < target_array.length; i ++ ) {
  6135. var ta = target_array[ i ];
  6136. var target = result.objects[ ta.targetName ];
  6137. if ( target ) {
  6138. ta.object.target = target;
  6139. } else {
  6140. // if there was error and target of specified name doesn't exist in the scene file
  6141. // create instead dummy target
  6142. // (target must be added to scene explicitly as parent is already added)
  6143. ta.object.target = new THREE.Object3D();
  6144. result.scene.add( ta.object.target );
  6145. }
  6146. ta.object.target.properties.targetInverse = ta.object;
  6147. }
  6148. };
  6149. var callbackTexture = function ( count ) {
  6150. counter_textures -= count;
  6151. async_callback_gate();
  6152. scope.onLoadComplete();
  6153. };
  6154. // must use this instead of just directly calling callbackTexture
  6155. // because of closure in the calling context loop
  6156. var generateTextureCallback = function ( count ) {
  6157. return function() {
  6158. callbackTexture( count );
  6159. };
  6160. };
  6161. // first go synchronous elements
  6162. // fogs
  6163. var fogID, fogJSON;
  6164. for ( fogID in data.fogs ) {
  6165. fogJSON = data.fogs[ fogID ];
  6166. if ( fogJSON.type === "linear" ) {
  6167. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  6168. } else if ( fogJSON.type === "exp2" ) {
  6169. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  6170. }
  6171. color = fogJSON.color;
  6172. fog.color.setRGB( color[0], color[1], color[2] );
  6173. result.fogs[ fogID ] = fog;
  6174. }
  6175. // now come potentially asynchronous elements
  6176. // geometries
  6177. // count how many geometries will be loaded asynchronously
  6178. var geoID, geoJSON;
  6179. for ( geoID in data.geometries ) {
  6180. geoJSON = data.geometries[ geoID ];
  6181. if ( geoJSON.type in this.geometryHandlerMap ) {
  6182. counter_models += 1;
  6183. scope.onLoadStart();
  6184. }
  6185. }
  6186. // count how many hierarchies will be loaded asynchronously
  6187. var objID, objJSON;
  6188. for ( objID in data.objects ) {
  6189. objJSON = data.objects[ objID ];
  6190. if ( objJSON.type && ( objJSON.type in this.hierarchyHandlerMap ) ) {
  6191. counter_models += 1;
  6192. scope.onLoadStart();
  6193. }
  6194. }
  6195. total_models = counter_models;
  6196. for ( geoID in data.geometries ) {
  6197. geoJSON = data.geometries[ geoID ];
  6198. if ( geoJSON.type === "cube" ) {
  6199. geometry = new THREE.CubeGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  6200. result.geometries[ geoID ] = geometry;
  6201. } else if ( geoJSON.type === "plane" ) {
  6202. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  6203. result.geometries[ geoID ] = geometry;
  6204. } else if ( geoJSON.type === "sphere" ) {
  6205. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  6206. result.geometries[ geoID ] = geometry;
  6207. } else if ( geoJSON.type === "cylinder" ) {
  6208. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  6209. result.geometries[ geoID ] = geometry;
  6210. } else if ( geoJSON.type === "torus" ) {
  6211. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  6212. result.geometries[ geoID ] = geometry;
  6213. } else if ( geoJSON.type === "icosahedron" ) {
  6214. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  6215. result.geometries[ geoID ] = geometry;
  6216. } else if ( geoJSON.type in this.geometryHandlerMap ) {
  6217. var loaderParameters = {};
  6218. for ( var parType in geoJSON ) {
  6219. if ( parType !== "type" && parType !== "url" ) {
  6220. loaderParameters[ parType ] = geoJSON[ parType ];
  6221. }
  6222. }
  6223. var loader = this.geometryHandlerMap[ geoJSON.type ][ "loaderObject" ];
  6224. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  6225. } else if ( geoJSON.type === "embedded" ) {
  6226. var modelJson = data.embeds[ geoJSON.id ],
  6227. texture_path = "";
  6228. // pass metadata along to jsonLoader so it knows the format version
  6229. modelJson.metadata = data.metadata;
  6230. if ( modelJson ) {
  6231. var jsonLoader = this.geometryHandlerMap[ "ascii" ][ "loaderObject" ];
  6232. jsonLoader.createModel( modelJson, create_callback_embed( geoID ), texture_path );
  6233. }
  6234. }
  6235. }
  6236. // textures
  6237. // count how many textures will be loaded asynchronously
  6238. var textureID, textureJSON;
  6239. for ( textureID in data.textures ) {
  6240. textureJSON = data.textures[ textureID ];
  6241. if ( textureJSON.url instanceof Array ) {
  6242. counter_textures += textureJSON.url.length;
  6243. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  6244. scope.onLoadStart();
  6245. }
  6246. } else {
  6247. counter_textures += 1;
  6248. scope.onLoadStart();
  6249. }
  6250. }
  6251. total_textures = counter_textures;
  6252. for ( textureID in data.textures ) {
  6253. textureJSON = data.textures[ textureID ];
  6254. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  6255. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  6256. }
  6257. if ( textureJSON.url instanceof Array ) {
  6258. var count = textureJSON.url.length;
  6259. var url_array = [];
  6260. for( var i = 0; i < count; i ++ ) {
  6261. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  6262. }
  6263. var isCompressed = url_array[ 0 ].endsWith( ".dds" );
  6264. if ( isCompressed ) {
  6265. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6266. } else {
  6267. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6268. }
  6269. } else {
  6270. var isCompressed = textureJSON.url.toLowerCase().endsWith( ".dds" );
  6271. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  6272. var textureCallback = generateTextureCallback( 1 );
  6273. if ( isCompressed ) {
  6274. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  6275. } else {
  6276. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  6277. }
  6278. if ( THREE[ textureJSON.minFilter ] !== undefined )
  6279. texture.minFilter = THREE[ textureJSON.minFilter ];
  6280. if ( THREE[ textureJSON.magFilter ] !== undefined )
  6281. texture.magFilter = THREE[ textureJSON.magFilter ];
  6282. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  6283. if ( textureJSON.repeat ) {
  6284. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  6285. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  6286. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  6287. }
  6288. if ( textureJSON.offset ) {
  6289. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  6290. }
  6291. // handle wrap after repeat so that default repeat can be overriden
  6292. if ( textureJSON.wrap ) {
  6293. var wrapMap = {
  6294. "repeat" : THREE.RepeatWrapping,
  6295. "mirror" : THREE.MirroredRepeatWrapping
  6296. }
  6297. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  6298. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  6299. }
  6300. }
  6301. result.textures[ textureID ] = texture;
  6302. }
  6303. // materials
  6304. var matID, matJSON;
  6305. var parID;
  6306. for ( matID in data.materials ) {
  6307. matJSON = data.materials[ matID ];
  6308. for ( parID in matJSON.parameters ) {
  6309. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  6310. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  6311. } else if ( parID === "shading" ) {
  6312. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  6313. } else if ( parID === "side" ) {
  6314. if ( matJSON.parameters[ parID ] == "double" ) {
  6315. matJSON.parameters[ parID ] = THREE.DoubleSide;
  6316. } else if ( matJSON.parameters[ parID ] == "back" ) {
  6317. matJSON.parameters[ parID ] = THREE.BackSide;
  6318. } else {
  6319. matJSON.parameters[ parID ] = THREE.FrontSide;
  6320. }
  6321. } else if ( parID === "blending" ) {
  6322. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  6323. } else if ( parID === "combine" ) {
  6324. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  6325. } else if ( parID === "vertexColors" ) {
  6326. if ( matJSON.parameters[ parID ] == "face" ) {
  6327. matJSON.parameters[ parID ] = THREE.FaceColors;
  6328. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  6329. } else if ( matJSON.parameters[ parID ] ) {
  6330. matJSON.parameters[ parID ] = THREE.VertexColors;
  6331. }
  6332. } else if ( parID === "wrapRGB" ) {
  6333. var v3 = matJSON.parameters[ parID ];
  6334. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  6335. }
  6336. }
  6337. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  6338. matJSON.parameters.transparent = true;
  6339. }
  6340. if ( matJSON.parameters.normalMap ) {
  6341. var shader = THREE.ShaderUtils.lib[ "normal" ];
  6342. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6343. var diffuse = matJSON.parameters.color;
  6344. var specular = matJSON.parameters.specular;
  6345. var ambient = matJSON.parameters.ambient;
  6346. var shininess = matJSON.parameters.shininess;
  6347. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  6348. if ( matJSON.parameters.normalScale ) {
  6349. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  6350. }
  6351. if ( matJSON.parameters.map ) {
  6352. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  6353. uniforms[ "enableDiffuse" ].value = true;
  6354. }
  6355. if ( matJSON.parameters.envMap ) {
  6356. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  6357. uniforms[ "enableReflection" ].value = true;
  6358. uniforms[ "uReflectivity" ].value = matJSON.parameters.reflectivity;
  6359. }
  6360. if ( matJSON.parameters.lightMap ) {
  6361. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  6362. uniforms[ "enableAO" ].value = true;
  6363. }
  6364. if ( matJSON.parameters.specularMap ) {
  6365. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  6366. uniforms[ "enableSpecular" ].value = true;
  6367. }
  6368. if ( matJSON.parameters.displacementMap ) {
  6369. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  6370. uniforms[ "enableDisplacement" ].value = true;
  6371. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  6372. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  6373. }
  6374. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  6375. uniforms[ "uSpecularColor" ].value.setHex( specular );
  6376. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  6377. uniforms[ "uShininess" ].value = shininess;
  6378. if ( matJSON.parameters.opacity ) {
  6379. uniforms[ "uOpacity" ].value = matJSON.parameters.opacity;
  6380. }
  6381. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6382. material = new THREE.ShaderMaterial( parameters );
  6383. } else {
  6384. material = new THREE[ matJSON.type ]( matJSON.parameters );
  6385. }
  6386. result.materials[ matID ] = material;
  6387. }
  6388. // second pass through all materials to initialize MeshFaceMaterials
  6389. // that could be referring to other materials out of order
  6390. for ( matID in data.materials ) {
  6391. matJSON = data.materials[ matID ];
  6392. if ( matJSON.parameters.materials ) {
  6393. var materialArray = [];
  6394. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  6395. var label = matJSON.parameters.materials[ i ];
  6396. materialArray.push( result.materials[ label ] );
  6397. }
  6398. result.materials[ matID ].materials = materialArray;
  6399. }
  6400. }
  6401. // objects ( synchronous init of procedural primitives )
  6402. handle_objects();
  6403. // defaults
  6404. if ( result.cameras && data.defaults.camera ) {
  6405. result.currentCamera = result.cameras[ data.defaults.camera ];
  6406. }
  6407. if ( result.fogs && data.defaults.fog ) {
  6408. result.scene.fog = result.fogs[ data.defaults.fog ];
  6409. }
  6410. color = data.defaults.bgcolor;
  6411. result.bgColor = new THREE.Color();
  6412. result.bgColor.setRGB( color[0], color[1], color[2] );
  6413. result.bgColorAlpha = data.defaults.bgalpha;
  6414. // synchronous callback
  6415. scope.callbackSync( result );
  6416. // just in case there are no async elements
  6417. async_callback_gate();
  6418. };
  6419. /**
  6420. * @author mrdoob / http://mrdoob.com/
  6421. */
  6422. THREE.TextureLoader = function () {
  6423. THREE.EventDispatcher.call( this );
  6424. this.crossOrigin = null;
  6425. };
  6426. THREE.TextureLoader.prototype = {
  6427. constructor: THREE.TextureLoader,
  6428. load: function ( url ) {
  6429. var scope = this;
  6430. var image = new Image();
  6431. image.addEventListener( 'load', function () {
  6432. var texture = new THREE.Texture( image );
  6433. texture.needsUpdate = true;
  6434. scope.dispatchEvent( { type: 'load', content: texture } );
  6435. }, false );
  6436. image.addEventListener( 'error', function () {
  6437. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  6438. }, false );
  6439. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  6440. image.src = url;
  6441. }
  6442. }
  6443. /**
  6444. * @author mrdoob / http://mrdoob.com/
  6445. * @author alteredq / http://alteredqualia.com/
  6446. */
  6447. THREE.Material = function () {
  6448. THREE.EventDispatcher.call( this );
  6449. this.id = THREE.MaterialIdCount ++;
  6450. this.name = '';
  6451. this.side = THREE.FrontSide;
  6452. this.opacity = 1;
  6453. this.transparent = false;
  6454. this.blending = THREE.NormalBlending;
  6455. this.blendSrc = THREE.SrcAlphaFactor;
  6456. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  6457. this.blendEquation = THREE.AddEquation;
  6458. this.depthTest = true;
  6459. this.depthWrite = true;
  6460. this.polygonOffset = false;
  6461. this.polygonOffsetFactor = 0;
  6462. this.polygonOffsetUnits = 0;
  6463. this.alphaTest = 0;
  6464. this.overdraw = false; // Boolean for fixing antialiasing gaps in CanvasRenderer
  6465. this.visible = true;
  6466. this.needsUpdate = true;
  6467. };
  6468. THREE.Material.prototype.setValues = function ( values ) {
  6469. if ( values === undefined ) return;
  6470. for ( var key in values ) {
  6471. var newValue = values[ key ];
  6472. if ( newValue === undefined ) {
  6473. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  6474. continue;
  6475. }
  6476. if ( key in this ) {
  6477. var currentValue = this[ key ];
  6478. if ( currentValue instanceof THREE.Color && newValue instanceof THREE.Color ) {
  6479. currentValue.copy( newValue );
  6480. } else if ( currentValue instanceof THREE.Color ) {
  6481. currentValue.set( newValue );
  6482. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  6483. currentValue.copy( newValue );
  6484. } else {
  6485. this[ key ] = newValue;
  6486. }
  6487. }
  6488. }
  6489. };
  6490. THREE.Material.prototype.clone = function ( material ) {
  6491. if ( material === undefined ) material = new THREE.Material();
  6492. material.name = this.name;
  6493. material.side = this.side;
  6494. material.opacity = this.opacity;
  6495. material.transparent = this.transparent;
  6496. material.blending = this.blending;
  6497. material.blendSrc = this.blendSrc;
  6498. material.blendDst = this.blendDst;
  6499. material.blendEquation = this.blendEquation;
  6500. material.depthTest = this.depthTest;
  6501. material.depthWrite = this.depthWrite;
  6502. material.polygonOffset = this.polygonOffset;
  6503. material.polygonOffsetFactor = this.polygonOffsetFactor;
  6504. material.polygonOffsetUnits = this.polygonOffsetUnits;
  6505. material.alphaTest = this.alphaTest;
  6506. material.overdraw = this.overdraw;
  6507. material.visible = this.visible;
  6508. return material;
  6509. };
  6510. THREE.Material.prototype.dispose = function () {
  6511. this.dispatchEvent( { type: 'dispose' } );
  6512. };
  6513. THREE.MaterialIdCount = 0;
  6514. /**
  6515. * @author mrdoob / http://mrdoob.com/
  6516. * @author alteredq / http://alteredqualia.com/
  6517. *
  6518. * parameters = {
  6519. * color: <hex>,
  6520. * opacity: <float>,
  6521. *
  6522. * blending: THREE.NormalBlending,
  6523. * depthTest: <bool>,
  6524. * depthWrite: <bool>,
  6525. *
  6526. * linewidth: <float>,
  6527. * linecap: "round",
  6528. * linejoin: "round",
  6529. *
  6530. * vertexColors: <bool>
  6531. *
  6532. * fog: <bool>
  6533. * }
  6534. */
  6535. THREE.LineBasicMaterial = function ( parameters ) {
  6536. THREE.Material.call( this );
  6537. this.color = new THREE.Color( 0xffffff );
  6538. this.linewidth = 1;
  6539. this.linecap = 'round';
  6540. this.linejoin = 'round';
  6541. this.vertexColors = false;
  6542. this.fog = true;
  6543. this.setValues( parameters );
  6544. };
  6545. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6546. THREE.LineBasicMaterial.prototype.clone = function () {
  6547. var material = new THREE.LineBasicMaterial();
  6548. THREE.Material.prototype.clone.call( this, material );
  6549. material.color.copy( this.color );
  6550. material.linewidth = this.linewidth;
  6551. material.linecap = this.linecap;
  6552. material.linejoin = this.linejoin;
  6553. material.vertexColors = this.vertexColors;
  6554. material.fog = this.fog;
  6555. return material;
  6556. };
  6557. /**
  6558. * @author alteredq / http://alteredqualia.com/
  6559. *
  6560. * parameters = {
  6561. * color: <hex>,
  6562. * opacity: <float>,
  6563. *
  6564. * blending: THREE.NormalBlending,
  6565. * depthTest: <bool>,
  6566. * depthWrite: <bool>,
  6567. *
  6568. * linewidth: <float>,
  6569. *
  6570. * scale: <float>,
  6571. * dashSize: <float>,
  6572. * gapSize: <float>,
  6573. *
  6574. * vertexColors: <bool>
  6575. *
  6576. * fog: <bool>
  6577. * }
  6578. */
  6579. THREE.LineDashedMaterial = function ( parameters ) {
  6580. THREE.Material.call( this );
  6581. this.color = new THREE.Color( 0xffffff );
  6582. this.linewidth = 1;
  6583. this.scale = 1;
  6584. this.dashSize = 3;
  6585. this.gapSize = 1;
  6586. this.vertexColors = false;
  6587. this.fog = true;
  6588. this.setValues( parameters );
  6589. };
  6590. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  6591. THREE.LineDashedMaterial.prototype.clone = function () {
  6592. var material = new THREE.LineDashedMaterial();
  6593. THREE.Material.prototype.clone.call( this, material );
  6594. material.color.copy( this.color );
  6595. material.linewidth = this.linewidth;
  6596. material.scale = this.scale;
  6597. material.dashSize = this.dashSize;
  6598. material.gapSize = this.gapSize;
  6599. material.vertexColors = this.vertexColors;
  6600. material.fog = this.fog;
  6601. return material;
  6602. };
  6603. /**
  6604. * @author mrdoob / http://mrdoob.com/
  6605. * @author alteredq / http://alteredqualia.com/
  6606. *
  6607. * parameters = {
  6608. * color: <hex>,
  6609. * opacity: <float>,
  6610. * map: new THREE.Texture( <Image> ),
  6611. *
  6612. * lightMap: new THREE.Texture( <Image> ),
  6613. *
  6614. * specularMap: new THREE.Texture( <Image> ),
  6615. *
  6616. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6617. * combine: THREE.Multiply,
  6618. * reflectivity: <float>,
  6619. * refractionRatio: <float>,
  6620. *
  6621. * shading: THREE.SmoothShading,
  6622. * blending: THREE.NormalBlending,
  6623. * depthTest: <bool>,
  6624. * depthWrite: <bool>,
  6625. *
  6626. * wireframe: <boolean>,
  6627. * wireframeLinewidth: <float>,
  6628. *
  6629. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6630. *
  6631. * skinning: <bool>,
  6632. * morphTargets: <bool>,
  6633. *
  6634. * fog: <bool>
  6635. * }
  6636. */
  6637. THREE.MeshBasicMaterial = function ( parameters ) {
  6638. THREE.Material.call( this );
  6639. this.color = new THREE.Color( 0xffffff ); // emissive
  6640. this.map = null;
  6641. this.lightMap = null;
  6642. this.specularMap = null;
  6643. this.envMap = null;
  6644. this.combine = THREE.MultiplyOperation;
  6645. this.reflectivity = 1;
  6646. this.refractionRatio = 0.98;
  6647. this.fog = true;
  6648. this.shading = THREE.SmoothShading;
  6649. this.wireframe = false;
  6650. this.wireframeLinewidth = 1;
  6651. this.wireframeLinecap = 'round';
  6652. this.wireframeLinejoin = 'round';
  6653. this.vertexColors = THREE.NoColors;
  6654. this.skinning = false;
  6655. this.morphTargets = false;
  6656. this.setValues( parameters );
  6657. };
  6658. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6659. THREE.MeshBasicMaterial.prototype.clone = function () {
  6660. var material = new THREE.MeshBasicMaterial();
  6661. THREE.Material.prototype.clone.call( this, material );
  6662. material.color.copy( this.color );
  6663. material.map = this.map;
  6664. material.lightMap = this.lightMap;
  6665. material.specularMap = this.specularMap;
  6666. material.envMap = this.envMap;
  6667. material.combine = this.combine;
  6668. material.reflectivity = this.reflectivity;
  6669. material.refractionRatio = this.refractionRatio;
  6670. material.fog = this.fog;
  6671. material.shading = this.shading;
  6672. material.wireframe = this.wireframe;
  6673. material.wireframeLinewidth = this.wireframeLinewidth;
  6674. material.wireframeLinecap = this.wireframeLinecap;
  6675. material.wireframeLinejoin = this.wireframeLinejoin;
  6676. material.vertexColors = this.vertexColors;
  6677. material.skinning = this.skinning;
  6678. material.morphTargets = this.morphTargets;
  6679. return material;
  6680. };
  6681. /**
  6682. * @author mrdoob / http://mrdoob.com/
  6683. * @author alteredq / http://alteredqualia.com/
  6684. *
  6685. * parameters = {
  6686. * color: <hex>,
  6687. * ambient: <hex>,
  6688. * emissive: <hex>,
  6689. * opacity: <float>,
  6690. *
  6691. * map: new THREE.Texture( <Image> ),
  6692. *
  6693. * lightMap: new THREE.Texture( <Image> ),
  6694. *
  6695. * specularMap: new THREE.Texture( <Image> ),
  6696. *
  6697. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6698. * combine: THREE.Multiply,
  6699. * reflectivity: <float>,
  6700. * refractionRatio: <float>,
  6701. *
  6702. * shading: THREE.SmoothShading,
  6703. * blending: THREE.NormalBlending,
  6704. * depthTest: <bool>,
  6705. * depthWrite: <bool>,
  6706. *
  6707. * wireframe: <boolean>,
  6708. * wireframeLinewidth: <float>,
  6709. *
  6710. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6711. *
  6712. * skinning: <bool>,
  6713. * morphTargets: <bool>,
  6714. * morphNormals: <bool>,
  6715. *
  6716. * fog: <bool>
  6717. * }
  6718. */
  6719. THREE.MeshLambertMaterial = function ( parameters ) {
  6720. THREE.Material.call( this );
  6721. this.color = new THREE.Color( 0xffffff ); // diffuse
  6722. this.ambient = new THREE.Color( 0xffffff );
  6723. this.emissive = new THREE.Color( 0x000000 );
  6724. this.wrapAround = false;
  6725. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6726. this.map = null;
  6727. this.lightMap = null;
  6728. this.specularMap = null;
  6729. this.envMap = null;
  6730. this.combine = THREE.MultiplyOperation;
  6731. this.reflectivity = 1;
  6732. this.refractionRatio = 0.98;
  6733. this.fog = true;
  6734. this.shading = THREE.SmoothShading;
  6735. this.wireframe = false;
  6736. this.wireframeLinewidth = 1;
  6737. this.wireframeLinecap = 'round';
  6738. this.wireframeLinejoin = 'round';
  6739. this.vertexColors = THREE.NoColors;
  6740. this.skinning = false;
  6741. this.morphTargets = false;
  6742. this.morphNormals = false;
  6743. this.setValues( parameters );
  6744. };
  6745. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  6746. THREE.MeshLambertMaterial.prototype.clone = function () {
  6747. var material = new THREE.MeshLambertMaterial();
  6748. THREE.Material.prototype.clone.call( this, material );
  6749. material.color.copy( this.color );
  6750. material.ambient.copy( this.ambient );
  6751. material.emissive.copy( this.emissive );
  6752. material.wrapAround = this.wrapAround;
  6753. material.wrapRGB.copy( this.wrapRGB );
  6754. material.map = this.map;
  6755. material.lightMap = this.lightMap;
  6756. material.specularMap = this.specularMap;
  6757. material.envMap = this.envMap;
  6758. material.combine = this.combine;
  6759. material.reflectivity = this.reflectivity;
  6760. material.refractionRatio = this.refractionRatio;
  6761. material.fog = this.fog;
  6762. material.shading = this.shading;
  6763. material.wireframe = this.wireframe;
  6764. material.wireframeLinewidth = this.wireframeLinewidth;
  6765. material.wireframeLinecap = this.wireframeLinecap;
  6766. material.wireframeLinejoin = this.wireframeLinejoin;
  6767. material.vertexColors = this.vertexColors;
  6768. material.skinning = this.skinning;
  6769. material.morphTargets = this.morphTargets;
  6770. material.morphNormals = this.morphNormals;
  6771. return material;
  6772. };
  6773. /**
  6774. * @author mrdoob / http://mrdoob.com/
  6775. * @author alteredq / http://alteredqualia.com/
  6776. *
  6777. * parameters = {
  6778. * color: <hex>,
  6779. * ambient: <hex>,
  6780. * emissive: <hex>,
  6781. * specular: <hex>,
  6782. * shininess: <float>,
  6783. * opacity: <float>,
  6784. *
  6785. * map: new THREE.Texture( <Image> ),
  6786. *
  6787. * lightMap: new THREE.Texture( <Image> ),
  6788. *
  6789. * bumpMap: new THREE.Texture( <Image> ),
  6790. * bumpScale: <float>,
  6791. *
  6792. * normalMap: new THREE.Texture( <Image> ),
  6793. * normalScale: <Vector2>,
  6794. *
  6795. * specularMap: new THREE.Texture( <Image> ),
  6796. *
  6797. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6798. * combine: THREE.Multiply,
  6799. * reflectivity: <float>,
  6800. * refractionRatio: <float>,
  6801. *
  6802. * shading: THREE.SmoothShading,
  6803. * blending: THREE.NormalBlending,
  6804. * depthTest: <bool>,
  6805. * depthWrite: <bool>,
  6806. *
  6807. * wireframe: <boolean>,
  6808. * wireframeLinewidth: <float>,
  6809. *
  6810. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6811. *
  6812. * skinning: <bool>,
  6813. * morphTargets: <bool>,
  6814. * morphNormals: <bool>,
  6815. *
  6816. * fog: <bool>
  6817. * }
  6818. */
  6819. THREE.MeshPhongMaterial = function ( parameters ) {
  6820. THREE.Material.call( this );
  6821. this.color = new THREE.Color( 0xffffff ); // diffuse
  6822. this.ambient = new THREE.Color( 0xffffff );
  6823. this.emissive = new THREE.Color( 0x000000 );
  6824. this.specular = new THREE.Color( 0x111111 );
  6825. this.shininess = 30;
  6826. this.metal = false;
  6827. this.perPixel = true;
  6828. this.wrapAround = false;
  6829. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6830. this.map = null;
  6831. this.lightMap = null;
  6832. this.bumpMap = null;
  6833. this.bumpScale = 1;
  6834. this.normalMap = null;
  6835. this.normalScale = new THREE.Vector2( 1, 1 );
  6836. this.specularMap = null;
  6837. this.envMap = null;
  6838. this.combine = THREE.MultiplyOperation;
  6839. this.reflectivity = 1;
  6840. this.refractionRatio = 0.98;
  6841. this.fog = true;
  6842. this.shading = THREE.SmoothShading;
  6843. this.wireframe = false;
  6844. this.wireframeLinewidth = 1;
  6845. this.wireframeLinecap = 'round';
  6846. this.wireframeLinejoin = 'round';
  6847. this.vertexColors = THREE.NoColors;
  6848. this.skinning = false;
  6849. this.morphTargets = false;
  6850. this.morphNormals = false;
  6851. this.setValues( parameters );
  6852. };
  6853. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  6854. THREE.MeshPhongMaterial.prototype.clone = function () {
  6855. var material = new THREE.MeshPhongMaterial();
  6856. THREE.Material.prototype.clone.call( this, material );
  6857. material.color.copy( this.color );
  6858. material.ambient.copy( this.ambient );
  6859. material.emissive.copy( this.emissive );
  6860. material.specular.copy( this.specular );
  6861. material.shininess = this.shininess;
  6862. material.metal = this.metal;
  6863. material.perPixel = this.perPixel;
  6864. material.wrapAround = this.wrapAround;
  6865. material.wrapRGB.copy( this.wrapRGB );
  6866. material.map = this.map;
  6867. material.lightMap = this.lightMap;
  6868. material.bumpMap = this.bumpMap;
  6869. material.bumpScale = this.bumpScale;
  6870. material.normalMap = this.normalMap;
  6871. material.normalScale.copy( this.normalScale );
  6872. material.specularMap = this.specularMap;
  6873. material.envMap = this.envMap;
  6874. material.combine = this.combine;
  6875. material.reflectivity = this.reflectivity;
  6876. material.refractionRatio = this.refractionRatio;
  6877. material.fog = this.fog;
  6878. material.shading = this.shading;
  6879. material.wireframe = this.wireframe;
  6880. material.wireframeLinewidth = this.wireframeLinewidth;
  6881. material.wireframeLinecap = this.wireframeLinecap;
  6882. material.wireframeLinejoin = this.wireframeLinejoin;
  6883. material.vertexColors = this.vertexColors;
  6884. material.skinning = this.skinning;
  6885. material.morphTargets = this.morphTargets;
  6886. material.morphNormals = this.morphNormals;
  6887. return material;
  6888. };
  6889. /**
  6890. * @author mrdoob / http://mrdoob.com/
  6891. * @author alteredq / http://alteredqualia.com/
  6892. *
  6893. * parameters = {
  6894. * opacity: <float>,
  6895. *
  6896. * blending: THREE.NormalBlending,
  6897. * depthTest: <bool>,
  6898. * depthWrite: <bool>,
  6899. *
  6900. * wireframe: <boolean>,
  6901. * wireframeLinewidth: <float>
  6902. * }
  6903. */
  6904. THREE.MeshDepthMaterial = function ( parameters ) {
  6905. THREE.Material.call( this );
  6906. this.wireframe = false;
  6907. this.wireframeLinewidth = 1;
  6908. this.setValues( parameters );
  6909. };
  6910. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  6911. THREE.MeshDepthMaterial.prototype.clone = function () {
  6912. var material = new THREE.LineBasicMaterial();
  6913. THREE.Material.prototype.clone.call( this, material );
  6914. material.wireframe = this.wireframe;
  6915. material.wireframeLinewidth = this.wireframeLinewidth;
  6916. return material;
  6917. };
  6918. /**
  6919. * @author mrdoob / http://mrdoob.com/
  6920. *
  6921. * parameters = {
  6922. * opacity: <float>,
  6923. *
  6924. * shading: THREE.FlatShading,
  6925. * blending: THREE.NormalBlending,
  6926. * depthTest: <bool>,
  6927. * depthWrite: <bool>,
  6928. *
  6929. * wireframe: <boolean>,
  6930. * wireframeLinewidth: <float>
  6931. * }
  6932. */
  6933. THREE.MeshNormalMaterial = function ( parameters ) {
  6934. THREE.Material.call( this, parameters );
  6935. this.shading = THREE.FlatShading;
  6936. this.wireframe = false;
  6937. this.wireframeLinewidth = 1;
  6938. this.setValues( parameters );
  6939. };
  6940. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  6941. THREE.MeshNormalMaterial.prototype.clone = function () {
  6942. var material = new THREE.MeshNormalMaterial();
  6943. THREE.Material.prototype.clone.call( this, material );
  6944. material.shading = this.shading;
  6945. material.wireframe = this.wireframe;
  6946. material.wireframeLinewidth = this.wireframeLinewidth;
  6947. return material;
  6948. };
  6949. /**
  6950. * @author mrdoob / http://mrdoob.com/
  6951. */
  6952. THREE.MeshFaceMaterial = function ( materials ) {
  6953. this.materials = materials instanceof Array ? materials : [];
  6954. };
  6955. THREE.MeshFaceMaterial.prototype.clone = function () {
  6956. return new THREE.MeshFaceMaterial( this.materials.slice( 0 ) );
  6957. };
  6958. /**
  6959. * @author mrdoob / http://mrdoob.com/
  6960. * @author alteredq / http://alteredqualia.com/
  6961. *
  6962. * parameters = {
  6963. * color: <hex>,
  6964. * opacity: <float>,
  6965. * map: new THREE.Texture( <Image> ),
  6966. *
  6967. * size: <float>,
  6968. *
  6969. * blending: THREE.NormalBlending,
  6970. * depthTest: <bool>,
  6971. * depthWrite: <bool>,
  6972. *
  6973. * vertexColors: <bool>,
  6974. *
  6975. * fog: <bool>
  6976. * }
  6977. */
  6978. THREE.ParticleBasicMaterial = function ( parameters ) {
  6979. THREE.Material.call( this );
  6980. this.color = new THREE.Color( 0xffffff );
  6981. this.map = null;
  6982. this.size = 1;
  6983. this.sizeAttenuation = true;
  6984. this.vertexColors = false;
  6985. this.fog = true;
  6986. this.setValues( parameters );
  6987. };
  6988. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6989. THREE.ParticleBasicMaterial.prototype.clone = function () {
  6990. var material = new THREE.ParticleBasicMaterial();
  6991. THREE.Material.prototype.clone.call( this, material );
  6992. material.color.copy( this.color );
  6993. material.map = this.map;
  6994. material.size = this.size;
  6995. material.sizeAttenuation = this.sizeAttenuation;
  6996. material.vertexColors = this.vertexColors;
  6997. material.fog = this.fog;
  6998. return material;
  6999. };
  7000. /**
  7001. * @author mrdoob / http://mrdoob.com/
  7002. *
  7003. * parameters = {
  7004. * color: <hex>,
  7005. * program: <function>,
  7006. * opacity: <float>,
  7007. * blending: THREE.NormalBlending
  7008. * }
  7009. */
  7010. THREE.ParticleCanvasMaterial = function ( parameters ) {
  7011. THREE.Material.call( this );
  7012. this.color = new THREE.Color( 0xffffff );
  7013. this.program = function ( context, color ) {};
  7014. this.setValues( parameters );
  7015. };
  7016. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  7017. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  7018. var material = new THREE.ParticleCanvasMaterial();
  7019. THREE.Material.prototype.clone.call( this, material );
  7020. material.color.copy( this.color );
  7021. material.program = this.program;
  7022. return material;
  7023. };
  7024. /**
  7025. * @author alteredq / http://alteredqualia.com/
  7026. *
  7027. * parameters = {
  7028. * fragmentShader: <string>,
  7029. * vertexShader: <string>,
  7030. *
  7031. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  7032. *
  7033. * defines: { "label" : "value" },
  7034. *
  7035. * shading: THREE.SmoothShading,
  7036. * blending: THREE.NormalBlending,
  7037. * depthTest: <bool>,
  7038. * depthWrite: <bool>,
  7039. *
  7040. * wireframe: <boolean>,
  7041. * wireframeLinewidth: <float>,
  7042. *
  7043. * lights: <bool>,
  7044. *
  7045. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7046. *
  7047. * skinning: <bool>,
  7048. * morphTargets: <bool>,
  7049. * morphNormals: <bool>,
  7050. *
  7051. * fog: <bool>
  7052. * }
  7053. */
  7054. THREE.ShaderMaterial = function ( parameters ) {
  7055. THREE.Material.call( this );
  7056. this.fragmentShader = "void main() {}";
  7057. this.vertexShader = "void main() {}";
  7058. this.uniforms = {};
  7059. this.defines = {};
  7060. this.attributes = null;
  7061. this.shading = THREE.SmoothShading;
  7062. this.wireframe = false;
  7063. this.wireframeLinewidth = 1;
  7064. this.fog = false; // set to use scene fog
  7065. this.lights = false; // set to use scene lights
  7066. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  7067. this.skinning = false; // set to use skinning attribute streams
  7068. this.morphTargets = false; // set to use morph targets
  7069. this.morphNormals = false; // set to use morph normals
  7070. this.setValues( parameters );
  7071. };
  7072. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  7073. THREE.ShaderMaterial.prototype.clone = function () {
  7074. var material = new THREE.ShaderMaterial();
  7075. THREE.Material.prototype.clone.call( this, material );
  7076. material.fragmentShader = this.fragmentShader;
  7077. material.vertexShader = this.vertexShader;
  7078. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  7079. material.attributes = this.attributes;
  7080. material.defines = this.defines;
  7081. material.shading = this.shading;
  7082. material.wireframe = this.wireframe;
  7083. material.wireframeLinewidth = this.wireframeLinewidth;
  7084. material.fog = this.fog;
  7085. material.lights = this.lights;
  7086. material.vertexColors = this.vertexColors;
  7087. material.skinning = this.skinning;
  7088. material.morphTargets = this.morphTargets;
  7089. material.morphNormals = this.morphNormals;
  7090. return material;
  7091. };
  7092. /**
  7093. * @author alteredq / http://alteredqualia.com/
  7094. *
  7095. * parameters = {
  7096. * color: <hex>,
  7097. * opacity: <float>,
  7098. * map: new THREE.Texture( <Image> ),
  7099. *
  7100. * blending: THREE.NormalBlending,
  7101. * depthTest: <bool>,
  7102. * depthWrite: <bool>,
  7103. *
  7104. * useScreenCoordinates: <bool>,
  7105. * sizeAttenuation: <bool>,
  7106. * scaleByViewport: <bool>,
  7107. * alignment: THREE.SpriteAlignment.center,
  7108. *
  7109. * uvOffset: new THREE.Vector2(),
  7110. * uvScale: new THREE.Vector2(),
  7111. *
  7112. * fog: <bool>
  7113. * }
  7114. */
  7115. THREE.SpriteMaterial = function ( parameters ) {
  7116. THREE.Material.call( this );
  7117. // defaults
  7118. this.color = new THREE.Color( 0xffffff );
  7119. this.map = new THREE.Texture();
  7120. this.useScreenCoordinates = true;
  7121. this.depthTest = !this.useScreenCoordinates;
  7122. this.sizeAttenuation = !this.useScreenCoordinates;
  7123. this.scaleByViewport = !this.sizeAttenuation;
  7124. this.alignment = THREE.SpriteAlignment.center.clone();
  7125. this.fog = false;
  7126. this.uvOffset = new THREE.Vector2( 0, 0 );
  7127. this.uvScale = new THREE.Vector2( 1, 1 );
  7128. // set parameters
  7129. this.setValues( parameters );
  7130. // override coupled defaults if not specified explicitly by parameters
  7131. parameters = parameters || {};
  7132. if ( parameters.depthTest === undefined ) this.depthTest = !this.useScreenCoordinates;
  7133. if ( parameters.sizeAttenuation === undefined ) this.sizeAttenuation = !this.useScreenCoordinates;
  7134. if ( parameters.scaleByViewport === undefined ) this.scaleByViewport = !this.sizeAttenuation;
  7135. };
  7136. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  7137. THREE.SpriteMaterial.prototype.clone = function () {
  7138. var material = new THREE.SpriteMaterial();
  7139. THREE.Material.prototype.clone.call( this, material );
  7140. material.color.copy( this.color );
  7141. material.map = this.map;
  7142. material.useScreenCoordinates = this.useScreenCoordinates;
  7143. material.sizeAttenuation = this.sizeAttenuation;
  7144. material.scaleByViewport = this.scaleByViewport;
  7145. material.alignment.copy( this.alignment );
  7146. material.uvOffset.copy( this.uvOffset );
  7147. material.uvScale.copy( this.uvScale );
  7148. material.fog = this.fog;
  7149. return material;
  7150. };
  7151. // Alignment enums
  7152. THREE.SpriteAlignment = {};
  7153. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  7154. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  7155. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  7156. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  7157. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  7158. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  7159. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  7160. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  7161. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  7162. /**
  7163. * @author mrdoob / http://mrdoob.com/
  7164. * @author alteredq / http://alteredqualia.com/
  7165. * @author szimek / https://github.com/szimek/
  7166. */
  7167. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  7168. THREE.EventDispatcher.call( this );
  7169. this.id = THREE.TextureIdCount ++;
  7170. this.name = '';
  7171. this.image = image;
  7172. this.mipmaps = [];
  7173. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  7174. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  7175. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  7176. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  7177. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  7178. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  7179. this.format = format !== undefined ? format : THREE.RGBAFormat;
  7180. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  7181. this.offset = new THREE.Vector2( 0, 0 );
  7182. this.repeat = new THREE.Vector2( 1, 1 );
  7183. this.generateMipmaps = true;
  7184. this.premultiplyAlpha = false;
  7185. this.flipY = true;
  7186. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  7187. this.needsUpdate = false;
  7188. this.onUpdate = null;
  7189. };
  7190. THREE.Texture.prototype = {
  7191. constructor: THREE.Texture,
  7192. clone: function ( texture ) {
  7193. if ( texture === undefined ) texture = new THREE.Texture();
  7194. texture.image = this.image;
  7195. texture.mipmaps = this.mipmaps.slice(0);
  7196. texture.mapping = this.mapping;
  7197. texture.wrapS = this.wrapS;
  7198. texture.wrapT = this.wrapT;
  7199. texture.magFilter = this.magFilter;
  7200. texture.minFilter = this.minFilter;
  7201. texture.anisotropy = this.anisotropy;
  7202. texture.format = this.format;
  7203. texture.type = this.type;
  7204. texture.offset.copy( this.offset );
  7205. texture.repeat.copy( this.repeat );
  7206. texture.generateMipmaps = this.generateMipmaps;
  7207. texture.premultiplyAlpha = this.premultiplyAlpha;
  7208. texture.flipY = this.flipY;
  7209. texture.unpackAlignment = this.unpackAlignment;
  7210. return texture;
  7211. },
  7212. dispose: function () {
  7213. this.dispatchEvent( { type: 'dispose' } );
  7214. }
  7215. };
  7216. THREE.TextureIdCount = 0;
  7217. /**
  7218. * @author alteredq / http://alteredqualia.com/
  7219. */
  7220. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7221. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7222. this.image = { width: width, height: height };
  7223. this.mipmaps = mipmaps;
  7224. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  7225. };
  7226. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  7227. THREE.CompressedTexture.prototype.clone = function () {
  7228. var texture = new THREE.CompressedTexture();
  7229. THREE.Texture.prototype.clone.call( this, texture );
  7230. return texture;
  7231. };
  7232. /**
  7233. * @author alteredq / http://alteredqualia.com/
  7234. */
  7235. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7236. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7237. this.image = { data: data, width: width, height: height };
  7238. };
  7239. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  7240. THREE.DataTexture.prototype.clone = function () {
  7241. var texture = new THREE.DataTexture();
  7242. THREE.Texture.prototype.clone.call( this, texture );
  7243. return texture;
  7244. };
  7245. /**
  7246. * @author mrdoob / http://mrdoob.com/
  7247. */
  7248. THREE.Particle = function ( material ) {
  7249. THREE.Object3D.call( this );
  7250. this.material = material;
  7251. };
  7252. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  7253. THREE.Particle.prototype.clone = function ( object ) {
  7254. if ( object === undefined ) object = new THREE.Particle( this.material );
  7255. THREE.Object3D.prototype.clone.call( this, object );
  7256. return object;
  7257. };
  7258. /**
  7259. * @author alteredq / http://alteredqualia.com/
  7260. */
  7261. THREE.ParticleSystem = function ( geometry, material ) {
  7262. THREE.Object3D.call( this );
  7263. this.geometry = geometry;
  7264. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  7265. this.sortParticles = false;
  7266. if ( this.geometry ) {
  7267. // calc bound radius
  7268. if( this.geometry.boundingSphere === null ) {
  7269. this.geometry.computeBoundingSphere();
  7270. }
  7271. }
  7272. this.frustumCulled = false;
  7273. };
  7274. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  7275. THREE.ParticleSystem.prototype.clone = function ( object ) {
  7276. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  7277. object.sortParticles = this.sortParticles;
  7278. THREE.Object3D.prototype.clone.call( this, object );
  7279. return object;
  7280. };
  7281. /**
  7282. * @author mrdoob / http://mrdoob.com/
  7283. */
  7284. THREE.Line = function ( geometry, material, type ) {
  7285. THREE.Object3D.call( this );
  7286. this.geometry = geometry;
  7287. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  7288. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  7289. if ( this.geometry ) {
  7290. if ( ! this.geometry.boundingSphere ) {
  7291. this.geometry.computeBoundingSphere();
  7292. }
  7293. }
  7294. };
  7295. THREE.LineStrip = 0;
  7296. THREE.LinePieces = 1;
  7297. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  7298. THREE.Line.prototype.clone = function ( object ) {
  7299. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  7300. THREE.Object3D.prototype.clone.call( this, object );
  7301. return object;
  7302. };
  7303. /**
  7304. * @author mrdoob / http://mrdoob.com/
  7305. * @author alteredq / http://alteredqualia.com/
  7306. * @author mikael emtinger / http://gomo.se/
  7307. * @author jonobr1 / http://jonobr1.com/
  7308. */
  7309. THREE.Mesh = function ( geometry, material ) {
  7310. THREE.Object3D.call( this );
  7311. this.geometry = geometry;
  7312. this.material = ( material !== undefined ) ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  7313. if ( this.geometry !== undefined ) {
  7314. if ( this.geometry.boundingSphere === null ) {
  7315. this.geometry.computeBoundingSphere();
  7316. }
  7317. this.updateMorphTargets();
  7318. }
  7319. };
  7320. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  7321. THREE.Mesh.prototype.updateMorphTargets = function () {
  7322. if ( this.geometry.morphTargets.length > 0 ) {
  7323. this.morphTargetBase = -1;
  7324. this.morphTargetForcedOrder = [];
  7325. this.morphTargetInfluences = [];
  7326. this.morphTargetDictionary = {};
  7327. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  7328. this.morphTargetInfluences.push( 0 );
  7329. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  7330. }
  7331. }
  7332. };
  7333. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  7334. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  7335. return this.morphTargetDictionary[ name ];
  7336. }
  7337. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  7338. return 0;
  7339. };
  7340. THREE.Mesh.prototype.clone = function ( object ) {
  7341. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  7342. THREE.Object3D.prototype.clone.call( this, object );
  7343. return object;
  7344. };
  7345. /**
  7346. * @author mikael emtinger / http://gomo.se/
  7347. * @author alteredq / http://alteredqualia.com/
  7348. */
  7349. THREE.Bone = function( belongsToSkin ) {
  7350. THREE.Object3D.call( this );
  7351. this.skin = belongsToSkin;
  7352. this.skinMatrix = new THREE.Matrix4();
  7353. };
  7354. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  7355. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  7356. // update local
  7357. if ( this.matrixAutoUpdate ) {
  7358. forceUpdate |= this.updateMatrix();
  7359. }
  7360. // update skin matrix
  7361. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  7362. if( parentSkinMatrix ) {
  7363. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  7364. } else {
  7365. this.skinMatrix.copy( this.matrix );
  7366. }
  7367. this.matrixWorldNeedsUpdate = false;
  7368. forceUpdate = true;
  7369. }
  7370. // update children
  7371. var child, i, l = this.children.length;
  7372. for ( i = 0; i < l; i ++ ) {
  7373. this.children[ i ].update( this.skinMatrix, forceUpdate );
  7374. }
  7375. };
  7376. /**
  7377. * @author mikael emtinger / http://gomo.se/
  7378. * @author alteredq / http://alteredqualia.com/
  7379. */
  7380. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  7381. THREE.Mesh.call( this, geometry, material );
  7382. //
  7383. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  7384. // init bones
  7385. this.identityMatrix = new THREE.Matrix4();
  7386. this.bones = [];
  7387. this.boneMatrices = [];
  7388. var b, bone, gbone, p, q, s;
  7389. if ( this.geometry && this.geometry.bones !== undefined ) {
  7390. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  7391. gbone = this.geometry.bones[ b ];
  7392. p = gbone.pos;
  7393. q = gbone.rotq;
  7394. s = gbone.scl;
  7395. bone = this.addBone();
  7396. bone.name = gbone.name;
  7397. bone.position.set( p[0], p[1], p[2] );
  7398. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  7399. bone.useQuaternion = true;
  7400. if ( s !== undefined ) {
  7401. bone.scale.set( s[0], s[1], s[2] );
  7402. } else {
  7403. bone.scale.set( 1, 1, 1 );
  7404. }
  7405. }
  7406. for ( b = 0; b < this.bones.length; b ++ ) {
  7407. gbone = this.geometry.bones[ b ];
  7408. bone = this.bones[ b ];
  7409. if ( gbone.parent === -1 ) {
  7410. this.add( bone );
  7411. } else {
  7412. this.bones[ gbone.parent ].add( bone );
  7413. }
  7414. }
  7415. //
  7416. var nBones = this.bones.length;
  7417. if ( this.useVertexTexture ) {
  7418. // layout (1 matrix = 4 pixels)
  7419. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  7420. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  7421. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  7422. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  7423. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  7424. var size;
  7425. if ( nBones > 256 )
  7426. size = 64;
  7427. else if ( nBones > 64 )
  7428. size = 32;
  7429. else if ( nBones > 16 )
  7430. size = 16;
  7431. else
  7432. size = 8;
  7433. this.boneTextureWidth = size;
  7434. this.boneTextureHeight = size;
  7435. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  7436. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  7437. this.boneTexture.minFilter = THREE.NearestFilter;
  7438. this.boneTexture.magFilter = THREE.NearestFilter;
  7439. this.boneTexture.generateMipmaps = false;
  7440. this.boneTexture.flipY = false;
  7441. } else {
  7442. this.boneMatrices = new Float32Array( 16 * nBones );
  7443. }
  7444. this.pose();
  7445. }
  7446. };
  7447. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  7448. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  7449. if ( bone === undefined ) {
  7450. bone = new THREE.Bone( this );
  7451. }
  7452. this.bones.push( bone );
  7453. return bone;
  7454. };
  7455. THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
  7456. this.matrixAutoUpdate && this.updateMatrix();
  7457. // update matrixWorld
  7458. if ( this.matrixWorldNeedsUpdate || force ) {
  7459. if ( this.parent ) {
  7460. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  7461. } else {
  7462. this.matrixWorld.copy( this.matrix );
  7463. }
  7464. this.matrixWorldNeedsUpdate = false;
  7465. force = true;
  7466. }
  7467. // update children
  7468. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  7469. var child = this.children[ i ];
  7470. if ( child instanceof THREE.Bone ) {
  7471. child.update( this.identityMatrix, false );
  7472. } else {
  7473. child.updateMatrixWorld( true );
  7474. }
  7475. }
  7476. // make a snapshot of the bones' rest position
  7477. if ( this.boneInverses == undefined ) {
  7478. this.boneInverses = [];
  7479. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7480. var inverse = new THREE.Matrix4();
  7481. inverse.getInverse( this.bones[ b ].skinMatrix );
  7482. this.boneInverses.push( inverse );
  7483. }
  7484. }
  7485. // flatten bone matrices to array
  7486. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7487. // compute the offset between the current and the original transform;
  7488. //TODO: we could get rid of this multiplication step if the skinMatrix
  7489. // was already representing the offset; however, this requires some
  7490. // major changes to the animation system
  7491. THREE.SkinnedMesh.offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  7492. THREE.SkinnedMesh.offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  7493. }
  7494. if ( this.useVertexTexture ) {
  7495. this.boneTexture.needsUpdate = true;
  7496. }
  7497. };
  7498. THREE.SkinnedMesh.prototype.pose = function () {
  7499. this.updateMatrixWorld( true );
  7500. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  7501. // normalize weights
  7502. var sw = this.geometry.skinWeights[ i ];
  7503. var scale = 1.0 / sw.lengthManhattan();
  7504. if ( scale !== Infinity ) {
  7505. sw.multiplyScalar( scale );
  7506. } else {
  7507. sw.set( 1 ); // this will be normalized by the shader anyway
  7508. }
  7509. }
  7510. };
  7511. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  7512. if ( object === undefined ) object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  7513. THREE.Mesh.prototype.clone.call( this, object );
  7514. return object;
  7515. };
  7516. THREE.SkinnedMesh.offsetMatrix = new THREE.Matrix4();
  7517. /**
  7518. * @author alteredq / http://alteredqualia.com/
  7519. */
  7520. THREE.MorphAnimMesh = function ( geometry, material ) {
  7521. THREE.Mesh.call( this, geometry, material );
  7522. // API
  7523. this.duration = 1000; // milliseconds
  7524. this.mirroredLoop = false;
  7525. this.time = 0;
  7526. // internals
  7527. this.lastKeyframe = 0;
  7528. this.currentKeyframe = 0;
  7529. this.direction = 1;
  7530. this.directionBackwards = false;
  7531. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  7532. };
  7533. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  7534. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  7535. this.startKeyframe = start;
  7536. this.endKeyframe = end;
  7537. this.length = this.endKeyframe - this.startKeyframe + 1;
  7538. };
  7539. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  7540. this.direction = 1;
  7541. this.directionBackwards = false;
  7542. };
  7543. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  7544. this.direction = -1;
  7545. this.directionBackwards = true;
  7546. };
  7547. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  7548. var geometry = this.geometry;
  7549. if ( ! geometry.animations ) geometry.animations = {};
  7550. var firstAnimation, animations = geometry.animations;
  7551. var pattern = /([a-z]+)(\d+)/;
  7552. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  7553. var morph = geometry.morphTargets[ i ];
  7554. var parts = morph.name.match( pattern );
  7555. if ( parts && parts.length > 1 ) {
  7556. var label = parts[ 1 ];
  7557. var num = parts[ 2 ];
  7558. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  7559. var animation = animations[ label ];
  7560. if ( i < animation.start ) animation.start = i;
  7561. if ( i > animation.end ) animation.end = i;
  7562. if ( ! firstAnimation ) firstAnimation = label;
  7563. }
  7564. }
  7565. geometry.firstAnimation = firstAnimation;
  7566. };
  7567. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  7568. if ( ! this.geometry.animations ) this.geometry.animations = {};
  7569. this.geometry.animations[ label ] = { start: start, end: end };
  7570. };
  7571. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  7572. var animation = this.geometry.animations[ label ];
  7573. if ( animation ) {
  7574. this.setFrameRange( animation.start, animation.end );
  7575. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  7576. this.time = 0;
  7577. } else {
  7578. console.warn( "animation[" + label + "] undefined" );
  7579. }
  7580. };
  7581. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  7582. var frameTime = this.duration / this.length;
  7583. this.time += this.direction * delta;
  7584. if ( this.mirroredLoop ) {
  7585. if ( this.time > this.duration || this.time < 0 ) {
  7586. this.direction *= -1;
  7587. if ( this.time > this.duration ) {
  7588. this.time = this.duration;
  7589. this.directionBackwards = true;
  7590. }
  7591. if ( this.time < 0 ) {
  7592. this.time = 0;
  7593. this.directionBackwards = false;
  7594. }
  7595. }
  7596. } else {
  7597. this.time = this.time % this.duration;
  7598. if ( this.time < 0 ) this.time += this.duration;
  7599. }
  7600. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  7601. if ( keyframe !== this.currentKeyframe ) {
  7602. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  7603. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  7604. this.morphTargetInfluences[ keyframe ] = 0;
  7605. this.lastKeyframe = this.currentKeyframe;
  7606. this.currentKeyframe = keyframe;
  7607. }
  7608. var mix = ( this.time % frameTime ) / frameTime;
  7609. if ( this.directionBackwards ) {
  7610. mix = 1 - mix;
  7611. }
  7612. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  7613. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  7614. };
  7615. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  7616. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  7617. object.duration = this.duration;
  7618. object.mirroredLoop = this.mirroredLoop;
  7619. object.time = this.time;
  7620. object.lastKeyframe = this.lastKeyframe;
  7621. object.currentKeyframe = this.currentKeyframe;
  7622. object.direction = this.direction;
  7623. object.directionBackwards = this.directionBackwards;
  7624. THREE.Mesh.prototype.clone.call( this, object );
  7625. return object;
  7626. };
  7627. /**
  7628. * @author alteredq / http://alteredqualia.com/
  7629. */
  7630. THREE.Ribbon = function ( geometry, material ) {
  7631. THREE.Object3D.call( this );
  7632. this.geometry = geometry;
  7633. this.material = material;
  7634. };
  7635. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  7636. THREE.Ribbon.prototype.clone = function ( object ) {
  7637. if ( object === undefined ) object = new THREE.Ribbon( this.geometry, this.material );
  7638. THREE.Object3D.prototype.clone.call( this, object );
  7639. return object;
  7640. };
  7641. /**
  7642. * @author mikael emtinger / http://gomo.se/
  7643. * @author alteredq / http://alteredqualia.com/
  7644. * @author mrdoob / http://mrdoob.com/
  7645. */
  7646. THREE.LOD = function () {
  7647. THREE.Object3D.call( this );
  7648. this.LODs = [];
  7649. };
  7650. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  7651. THREE.LOD.prototype.addLevel = function ( object3D, visibleAtDistance ) {
  7652. if ( visibleAtDistance === undefined ) {
  7653. visibleAtDistance = 0;
  7654. }
  7655. visibleAtDistance = Math.abs( visibleAtDistance );
  7656. for ( var l = 0; l < this.LODs.length; l ++ ) {
  7657. if ( visibleAtDistance < this.LODs[ l ].visibleAtDistance ) {
  7658. break;
  7659. }
  7660. }
  7661. this.LODs.splice( l, 0, { visibleAtDistance: visibleAtDistance, object3D: object3D } );
  7662. this.add( object3D );
  7663. };
  7664. THREE.LOD.prototype.update = function ( camera ) {
  7665. if ( this.LODs.length > 1 ) {
  7666. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  7667. var inverse = camera.matrixWorldInverse;
  7668. 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] );
  7669. this.LODs[ 0 ].object3D.visible = true;
  7670. for ( var l = 1; l < this.LODs.length; l ++ ) {
  7671. if( distance >= this.LODs[ l ].visibleAtDistance ) {
  7672. this.LODs[ l - 1 ].object3D.visible = false;
  7673. this.LODs[ l ].object3D.visible = true;
  7674. } else {
  7675. break;
  7676. }
  7677. }
  7678. for( ; l < this.LODs.length; l ++ ) {
  7679. this.LODs[ l ].object3D.visible = false;
  7680. }
  7681. }
  7682. };
  7683. THREE.LOD.prototype.clone = function () {
  7684. // TODO
  7685. };
  7686. /**
  7687. * @author mikael emtinger / http://gomo.se/
  7688. * @author alteredq / http://alteredqualia.com/
  7689. */
  7690. THREE.Sprite = function ( material ) {
  7691. THREE.Object3D.call( this );
  7692. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  7693. this.rotation3d = this.rotation;
  7694. this.rotation = 0;
  7695. };
  7696. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  7697. /*
  7698. * Custom update matrix
  7699. */
  7700. THREE.Sprite.prototype.updateMatrix = function () {
  7701. this.matrix.setPosition( this.position );
  7702. this.rotation3d.set( 0, 0, this.rotation );
  7703. this.matrix.setRotationFromEuler( this.rotation3d );
  7704. if ( this.scale.x !== 1 || this.scale.y !== 1 ) {
  7705. this.matrix.scale( this.scale );
  7706. }
  7707. this.matrixWorldNeedsUpdate = true;
  7708. };
  7709. THREE.Sprite.prototype.clone = function ( object ) {
  7710. if ( object === undefined ) object = new THREE.Sprite( this.material );
  7711. THREE.Object3D.prototype.clone.call( this, object );
  7712. return object;
  7713. };
  7714. /**
  7715. * @author mrdoob / http://mrdoob.com/
  7716. */
  7717. THREE.Scene = function () {
  7718. THREE.Object3D.call( this );
  7719. this.fog = null;
  7720. this.overrideMaterial = null;
  7721. this.matrixAutoUpdate = false;
  7722. this.__objects = [];
  7723. this.__lights = [];
  7724. this.__objectsAdded = [];
  7725. this.__objectsRemoved = [];
  7726. };
  7727. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  7728. THREE.Scene.prototype.__addObject = function ( object ) {
  7729. if ( object instanceof THREE.Light ) {
  7730. if ( this.__lights.indexOf( object ) === - 1 ) {
  7731. this.__lights.push( object );
  7732. }
  7733. if ( object.target && object.target.parent === undefined ) {
  7734. this.add( object.target );
  7735. }
  7736. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  7737. if ( this.__objects.indexOf( object ) === - 1 ) {
  7738. this.__objects.push( object );
  7739. this.__objectsAdded.push( object );
  7740. // check if previously removed
  7741. var i = this.__objectsRemoved.indexOf( object );
  7742. if ( i !== -1 ) {
  7743. this.__objectsRemoved.splice( i, 1 );
  7744. }
  7745. }
  7746. }
  7747. for ( var c = 0; c < object.children.length; c ++ ) {
  7748. this.__addObject( object.children[ c ] );
  7749. }
  7750. };
  7751. THREE.Scene.prototype.__removeObject = function ( object ) {
  7752. if ( object instanceof THREE.Light ) {
  7753. var i = this.__lights.indexOf( object );
  7754. if ( i !== -1 ) {
  7755. this.__lights.splice( i, 1 );
  7756. }
  7757. } else if ( !( object instanceof THREE.Camera ) ) {
  7758. var i = this.__objects.indexOf( object );
  7759. if( i !== -1 ) {
  7760. this.__objects.splice( i, 1 );
  7761. this.__objectsRemoved.push( object );
  7762. // check if previously added
  7763. var ai = this.__objectsAdded.indexOf( object );
  7764. if ( ai !== -1 ) {
  7765. this.__objectsAdded.splice( ai, 1 );
  7766. }
  7767. }
  7768. }
  7769. for ( var c = 0; c < object.children.length; c ++ ) {
  7770. this.__removeObject( object.children[ c ] );
  7771. }
  7772. };
  7773. /**
  7774. * @author mrdoob / http://mrdoob.com/
  7775. * @author alteredq / http://alteredqualia.com/
  7776. */
  7777. THREE.Fog = function ( hex, near, far ) {
  7778. this.name = '';
  7779. this.color = new THREE.Color( hex );
  7780. this.near = ( near !== undefined ) ? near : 1;
  7781. this.far = ( far !== undefined ) ? far : 1000;
  7782. };
  7783. THREE.Fog.prototype.clone = function () {
  7784. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  7785. };
  7786. /**
  7787. * @author mrdoob / http://mrdoob.com/
  7788. * @author alteredq / http://alteredqualia.com/
  7789. */
  7790. THREE.FogExp2 = function ( hex, density ) {
  7791. this.name = '';
  7792. this.color = new THREE.Color( hex );
  7793. this.density = ( density !== undefined ) ? density : 0.00025;
  7794. };
  7795. THREE.FogExp2.prototype.clone = function () {
  7796. return new THREE.FogExp2( this.color.getHex(), this.density );
  7797. };
  7798. /**
  7799. * @author mrdoob / http://mrdoob.com/
  7800. */
  7801. THREE.CanvasRenderer = function ( parameters ) {
  7802. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  7803. parameters = parameters || {};
  7804. var _this = this,
  7805. _renderData, _elements, _lights,
  7806. _projector = new THREE.Projector(),
  7807. _canvas = parameters.canvas !== undefined
  7808. ? parameters.canvas
  7809. : document.createElement( 'canvas' ),
  7810. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  7811. _context = _canvas.getContext( '2d' ),
  7812. _clearColor = new THREE.Color( 0x000000 ),
  7813. _clearOpacity = 0,
  7814. _contextGlobalAlpha = 1,
  7815. _contextGlobalCompositeOperation = 0,
  7816. _contextStrokeStyle = null,
  7817. _contextFillStyle = null,
  7818. _contextLineWidth = null,
  7819. _contextLineCap = null,
  7820. _contextLineJoin = null,
  7821. _v1, _v2, _v3, _v4,
  7822. _v5 = new THREE.RenderableVertex(),
  7823. _v6 = new THREE.RenderableVertex(),
  7824. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  7825. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  7826. _color = new THREE.Color(),
  7827. _color1 = new THREE.Color(),
  7828. _color2 = new THREE.Color(),
  7829. _color3 = new THREE.Color(),
  7830. _color4 = new THREE.Color(),
  7831. _diffuseColor = new THREE.Color(),
  7832. _emissiveColor = new THREE.Color(),
  7833. _lightColor = new THREE.Color(),
  7834. _patterns = {}, _imagedatas = {},
  7835. _near, _far,
  7836. _image, _uvs,
  7837. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  7838. _clipBox = new THREE.Box2(),
  7839. _clearBox = new THREE.Box2(),
  7840. _elemBox = new THREE.Box2(),
  7841. _enableLighting = false,
  7842. _ambientLight = new THREE.Color(),
  7843. _directionalLights = new THREE.Color(),
  7844. _pointLights = new THREE.Color(),
  7845. _pi2 = Math.PI * 2,
  7846. _vector3 = new THREE.Vector3(), // Needed for PointLight
  7847. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  7848. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  7849. _pixelMap = document.createElement( 'canvas' );
  7850. _pixelMap.width = _pixelMap.height = 2;
  7851. _pixelMapContext = _pixelMap.getContext( '2d' );
  7852. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  7853. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  7854. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  7855. _pixelMapData = _pixelMapImage.data;
  7856. _gradientMap = document.createElement( 'canvas' );
  7857. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  7858. _gradientMapContext = _gradientMap.getContext( '2d' );
  7859. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  7860. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  7861. _gradientMapQuality --; // Fix UVs
  7862. this.domElement = _canvas;
  7863. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  7864. ? parameters.devicePixelRatio
  7865. : window.devicePixelRatio !== undefined
  7866. ? window.devicePixelRatio
  7867. : 1;
  7868. this.autoClear = true;
  7869. this.sortObjects = true;
  7870. this.sortElements = true;
  7871. this.info = {
  7872. render: {
  7873. vertices: 0,
  7874. faces: 0
  7875. }
  7876. }
  7877. this.setSize = function ( width, height ) {
  7878. _canvasWidth = width * this.devicePixelRatio;
  7879. _canvasHeight = height * this.devicePixelRatio;
  7880. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  7881. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  7882. _canvas.width = _canvasWidth;
  7883. _canvas.height = _canvasHeight;
  7884. _canvas.style.width = width + 'px';
  7885. _canvas.style.height = height + 'px';
  7886. _clipBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  7887. _clipBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  7888. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  7889. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  7890. _contextGlobalAlpha = 1;
  7891. _contextGlobalCompositeOperation = 0;
  7892. _contextStrokeStyle = null;
  7893. _contextFillStyle = null;
  7894. _contextLineWidth = null;
  7895. _contextLineCap = null;
  7896. _contextLineJoin = null;
  7897. };
  7898. this.setClearColor = function ( color, opacity ) {
  7899. _clearColor.copy( color );
  7900. _clearOpacity = opacity !== undefined ? opacity : 1;
  7901. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  7902. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  7903. };
  7904. this.setClearColorHex = function ( hex, opacity ) {
  7905. _clearColor.setHex( hex );
  7906. _clearOpacity = opacity !== undefined ? opacity : 1;
  7907. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  7908. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  7909. };
  7910. this.getMaxAnisotropy = function () {
  7911. return 0;
  7912. };
  7913. this.clear = function () {
  7914. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  7915. if ( _clearBox.empty() === false ) {
  7916. _clearBox.intersect( _clipBox );
  7917. _clearBox.expandByScalar( 2 );
  7918. if ( _clearOpacity < 1 ) {
  7919. _context.clearRect( _clearBox.min.x | 0, _clearBox.min.y | 0, ( _clearBox.max.x - _clearBox.min.x ) | 0, ( _clearBox.max.y - _clearBox.min.y ) | 0 );
  7920. }
  7921. if ( _clearOpacity > 0 ) {
  7922. setBlending( THREE.NormalBlending );
  7923. setOpacity( 1 );
  7924. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearOpacity + ')' );
  7925. _context.fillRect( _clearBox.min.x | 0, _clearBox.min.y | 0, ( _clearBox.max.x - _clearBox.min.x ) | 0, ( _clearBox.max.y - _clearBox.min.y ) | 0 );
  7926. }
  7927. _clearBox.makeEmpty();
  7928. }
  7929. };
  7930. this.render = function ( scene, camera ) {
  7931. if ( camera instanceof THREE.Camera === false ) {
  7932. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  7933. return;
  7934. }
  7935. if ( this.autoClear === true ) {
  7936. this.clear();
  7937. }
  7938. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  7939. _this.info.render.vertices = 0;
  7940. _this.info.render.faces = 0;
  7941. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  7942. _elements = _renderData.elements;
  7943. _lights = _renderData.lights;
  7944. /* DEBUG
  7945. _context.fillStyle = 'rgba( 0, 255, 255, 0.5 )';
  7946. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  7947. */
  7948. _enableLighting = _lights.length > 0;
  7949. if ( _enableLighting === true ) {
  7950. calculateLights();
  7951. }
  7952. for ( var e = 0, el = _elements.length; e < el; e++ ) {
  7953. var element = _elements[ e ];
  7954. var material = element.material;
  7955. if ( material === undefined || material.visible === false ) continue;
  7956. _elemBox.makeEmpty();
  7957. if ( element instanceof THREE.RenderableParticle ) {
  7958. _v1 = element;
  7959. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  7960. renderParticle( _v1, element, material, scene );
  7961. } else if ( element instanceof THREE.RenderableLine ) {
  7962. _v1 = element.v1; _v2 = element.v2;
  7963. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7964. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7965. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen ] );
  7966. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  7967. renderLine( _v1, _v2, element, material, scene );
  7968. }
  7969. } else if ( element instanceof THREE.RenderableFace3 ) {
  7970. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  7971. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7972. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7973. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  7974. if ( material.overdraw === true ) {
  7975. expand( _v1.positionScreen, _v2.positionScreen );
  7976. expand( _v2.positionScreen, _v3.positionScreen );
  7977. expand( _v3.positionScreen, _v1.positionScreen );
  7978. }
  7979. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen, _v3.positionScreen ] );
  7980. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  7981. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material, scene );
  7982. }
  7983. } else if ( element instanceof THREE.RenderableFace4 ) {
  7984. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  7985. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7986. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7987. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  7988. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  7989. _v5.positionScreen.copy( _v2.positionScreen );
  7990. _v6.positionScreen.copy( _v4.positionScreen );
  7991. if ( material.overdraw === true ) {
  7992. expand( _v1.positionScreen, _v2.positionScreen );
  7993. expand( _v2.positionScreen, _v4.positionScreen );
  7994. expand( _v4.positionScreen, _v1.positionScreen );
  7995. expand( _v3.positionScreen, _v5.positionScreen );
  7996. expand( _v3.positionScreen, _v6.positionScreen );
  7997. }
  7998. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen, _v3.positionScreen, _v4.positionScreen ] );
  7999. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8000. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material, scene );
  8001. }
  8002. }
  8003. /* DEBUG
  8004. _context.lineWidth = 1;
  8005. _context.strokeStyle = 'rgba( 0, 255, 0, 0.5 )';
  8006. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  8007. */
  8008. _clearBox.union( _elemBox );
  8009. }
  8010. /* DEBUG
  8011. _context.lineWidth = 1;
  8012. _context.strokeStyle = 'rgba( 255, 0, 0, 0.5 )';
  8013. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  8014. */
  8015. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  8016. //
  8017. function calculateLights() {
  8018. _ambientLight.setRGB( 0, 0, 0 );
  8019. _directionalLights.setRGB( 0, 0, 0 );
  8020. _pointLights.setRGB( 0, 0, 0 );
  8021. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8022. var light = _lights[ l ];
  8023. var lightColor = light.color;
  8024. if ( light instanceof THREE.AmbientLight ) {
  8025. _ambientLight.add( lightColor );
  8026. } else if ( light instanceof THREE.DirectionalLight ) {
  8027. // for particles
  8028. _directionalLights.add( lightColor );
  8029. } else if ( light instanceof THREE.PointLight ) {
  8030. // for particles
  8031. _pointLights.add( lightColor );
  8032. }
  8033. }
  8034. }
  8035. function calculateLight( position, normal, color ) {
  8036. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8037. var light = _lights[ l ];
  8038. _lightColor.copy( light.color );
  8039. if ( light instanceof THREE.DirectionalLight ) {
  8040. var lightPosition = light.matrixWorld.getPosition().normalize();
  8041. var amount = normal.dot( lightPosition );
  8042. if ( amount <= 0 ) continue;
  8043. amount *= light.intensity;
  8044. color.add( _lightColor.multiplyScalar( amount ) );
  8045. } else if ( light instanceof THREE.PointLight ) {
  8046. var lightPosition = light.matrixWorld.getPosition();
  8047. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  8048. if ( amount <= 0 ) continue;
  8049. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  8050. if ( amount == 0 ) continue;
  8051. amount *= light.intensity;
  8052. color.add( _lightColor.multiplyScalar( amount ) );
  8053. }
  8054. }
  8055. }
  8056. function renderParticle( v1, element, material, scene ) {
  8057. setOpacity( material.opacity );
  8058. setBlending( material.blending );
  8059. var width, height, scaleX, scaleY,
  8060. bitmap, bitmapWidth, bitmapHeight;
  8061. if ( material instanceof THREE.ParticleBasicMaterial ) {
  8062. if ( material.map === null ) {
  8063. scaleX = element.object.scale.x;
  8064. scaleY = element.object.scale.y;
  8065. // TODO: Be able to disable this
  8066. scaleX *= element.scale.x * _canvasWidthHalf;
  8067. scaleY *= element.scale.y * _canvasHeightHalf;
  8068. _elemBox.min.set( v1.x - scaleX, v1.y - scaleY );
  8069. _elemBox.max.set( v1.x + scaleX, v1.y + scaleY );
  8070. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8071. return;
  8072. }
  8073. setFillStyle( material.color.getStyle() );
  8074. _context.save();
  8075. _context.translate( v1.x, v1.y );
  8076. _context.rotate( - element.rotation );
  8077. _context.scale( scaleX, scaleY );
  8078. _context.fillRect( -1, -1, 2, 2 );
  8079. _context.restore();
  8080. } else {
  8081. bitmap = material.map.image;
  8082. bitmapWidth = bitmap.width >> 1;
  8083. bitmapHeight = bitmap.height >> 1;
  8084. scaleX = element.scale.x * _canvasWidthHalf;
  8085. scaleY = element.scale.y * _canvasHeightHalf;
  8086. width = scaleX * bitmapWidth;
  8087. height = scaleY * bitmapHeight;
  8088. // TODO: Rotations break this...
  8089. _elemBox.min.set( v1.x - width, v1.y - height );
  8090. _elemBox.max.set( v1.x + width, v1.y + height );
  8091. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8092. return;
  8093. }
  8094. _context.save();
  8095. _context.translate( v1.x, v1.y );
  8096. _context.rotate( - element.rotation );
  8097. _context.scale( scaleX, - scaleY );
  8098. _context.translate( - bitmapWidth, - bitmapHeight );
  8099. _context.drawImage( bitmap, 0, 0 );
  8100. _context.restore();
  8101. }
  8102. /* DEBUG
  8103. setStrokeStyle( 'rgb(255,255,0)' );
  8104. _context.beginPath();
  8105. _context.moveTo( v1.x - 10, v1.y );
  8106. _context.lineTo( v1.x + 10, v1.y );
  8107. _context.moveTo( v1.x, v1.y - 10 );
  8108. _context.lineTo( v1.x, v1.y + 10 );
  8109. _context.stroke();
  8110. */
  8111. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  8112. width = element.scale.x * _canvasWidthHalf;
  8113. height = element.scale.y * _canvasHeightHalf;
  8114. _elemBox.min.set( v1.x - width, v1.y - height );
  8115. _elemBox.max.set( v1.x + width, v1.y + height );
  8116. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8117. return;
  8118. }
  8119. setStrokeStyle( material.color.getStyle() );
  8120. setFillStyle( material.color.getStyle() );
  8121. _context.save();
  8122. _context.translate( v1.x, v1.y );
  8123. _context.rotate( - element.rotation );
  8124. _context.scale( width, height );
  8125. material.program( _context );
  8126. _context.restore();
  8127. }
  8128. }
  8129. function renderLine( v1, v2, element, material, scene ) {
  8130. setOpacity( material.opacity );
  8131. setBlending( material.blending );
  8132. _context.beginPath();
  8133. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  8134. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  8135. if ( material instanceof THREE.LineBasicMaterial ) {
  8136. setLineWidth( material.linewidth );
  8137. setLineCap( material.linecap );
  8138. setLineJoin( material.linejoin );
  8139. setStrokeStyle( material.color.getStyle() );
  8140. _context.stroke();
  8141. _elemBox.expandByScalar( material.linewidth * 2 );
  8142. }
  8143. }
  8144. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material, scene ) {
  8145. _this.info.render.vertices += 3;
  8146. _this.info.render.faces ++;
  8147. setOpacity( material.opacity );
  8148. setBlending( material.blending );
  8149. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8150. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8151. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8152. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  8153. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null && material.map === null ) {
  8154. _diffuseColor.copy( material.color );
  8155. _emissiveColor.copy( material.emissive );
  8156. if ( material.vertexColors === THREE.FaceColors ) {
  8157. _diffuseColor.multiply( element.color );
  8158. }
  8159. if ( _enableLighting === true ) {
  8160. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  8161. _color1.copy( _ambientLight );
  8162. _color2.copy( _ambientLight );
  8163. _color3.copy( _ambientLight );
  8164. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  8165. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  8166. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color3 );
  8167. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  8168. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  8169. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  8170. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8171. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8172. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8173. } else {
  8174. _color.copy( _ambientLight );
  8175. calculateLight( element.centroidModel, element.normalModel, _color );
  8176. _color.multiply( _diffuseColor ).add( _emissiveColor );
  8177. material.wireframe === true
  8178. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8179. : fillPath( _color );
  8180. }
  8181. } else {
  8182. material.wireframe === true
  8183. ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8184. : fillPath( material.color );
  8185. }
  8186. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8187. if ( material.map !== null ) {
  8188. if ( material.map.mapping instanceof THREE.UVMapping ) {
  8189. _uvs = element.uvs[ 0 ];
  8190. 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 );
  8191. }
  8192. } else if ( material.envMap !== null ) {
  8193. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  8194. _vector3.copy( element.vertexNormalsModelView[ uv1 ] );
  8195. _uv1x = 0.5 * _vector3.x + 0.5;
  8196. _uv1y = 0.5 * _vector3.y + 0.5;
  8197. _vector3.copy( element.vertexNormalsModelView[ uv2 ] );
  8198. _uv2x = 0.5 * _vector3.x + 0.5;
  8199. _uv2y = 0.5 * _vector3.y + 0.5;
  8200. _vector3.copy( element.vertexNormalsModelView[ uv3 ] );
  8201. _uv3x = 0.5 * _vector3.x + 0.5;
  8202. _uv3y = 0.5 * _vector3.y + 0.5;
  8203. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  8204. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  8205. }*/
  8206. } else {
  8207. _color.copy( material.color );
  8208. if ( material.vertexColors === THREE.FaceColors ) {
  8209. _color.multiply( element.color );
  8210. }
  8211. material.wireframe === true
  8212. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8213. : fillPath( _color );
  8214. }
  8215. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8216. _near = camera.near;
  8217. _far = camera.far;
  8218. var depth;
  8219. depth = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  8220. _color1.setRGB( depth, depth, depth );
  8221. depth = 1 - smoothstep( v2.positionScreen.z, _near, _far )
  8222. _color2.setRGB( depth, depth, depth );
  8223. depth = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  8224. _color3.setRGB( depth, depth, depth );
  8225. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8226. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8227. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8228. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8229. var normal;
  8230. if ( material.shading == THREE.FlatShading ) {
  8231. normal = element.normalModelView;
  8232. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8233. material.wireframe === true
  8234. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8235. : fillPath( _color );
  8236. } else if ( material.shading == THREE.SmoothShading ) {
  8237. normal = element.vertexNormalsModelView[ uv1 ];
  8238. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8239. normal = element.vertexNormalsModelView[ uv2 ];
  8240. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8241. normal = element.vertexNormalsModelView[ uv3 ];
  8242. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8243. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8244. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8245. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8246. }
  8247. }
  8248. }
  8249. function renderFace4( v1, v2, v3, v4, v5, v6, element, material, scene ) {
  8250. _this.info.render.vertices += 4;
  8251. _this.info.render.faces ++;
  8252. setOpacity( material.opacity );
  8253. setBlending( material.blending );
  8254. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  8255. // Let renderFace3() handle this
  8256. renderFace3( v1, v2, v4, 0, 1, 3, element, material, scene );
  8257. renderFace3( v5, v3, v6, 1, 2, 3, element, material, scene );
  8258. return;
  8259. }
  8260. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8261. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8262. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8263. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  8264. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  8265. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  8266. if ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8267. _diffuseColor.copy( material.color );
  8268. _emissiveColor.copy( material.emissive );
  8269. if ( material.vertexColors === THREE.FaceColors ) {
  8270. _diffuseColor.multiply( element.color );
  8271. }
  8272. if ( _enableLighting === true ) {
  8273. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  8274. _color1.copy( _ambientLight );
  8275. _color2.copy( _ambientLight );
  8276. _color3.copy( _ambientLight );
  8277. _color4.copy( _ambientLight );
  8278. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  8279. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  8280. calculateLight( element.v4.positionWorld, element.vertexNormalsModel[ 3 ], _color3 );
  8281. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color4 );
  8282. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  8283. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  8284. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  8285. _color4.multiply( _diffuseColor ).add( _emissiveColor );
  8286. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8287. // TODO: UVs are incorrect, v4->v3?
  8288. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8289. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8290. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8291. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8292. } else {
  8293. _color.copy( _ambientLight );
  8294. calculateLight( element.centroidModel, element.normalModel, _color );
  8295. _color.multiply( _diffuseColor ).add( _emissiveColor );
  8296. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8297. material.wireframe === true
  8298. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8299. : fillPath( _color );
  8300. }
  8301. } else {
  8302. _color.addColors( _diffuseColor, _emissiveColor );
  8303. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8304. material.wireframe === true
  8305. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8306. : fillPath( _color );
  8307. }
  8308. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  8309. _color.copy( material.color );
  8310. if ( material.vertexColors === THREE.FaceColors ) {
  8311. _color.multiply( element.color );
  8312. }
  8313. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8314. material.wireframe === true
  8315. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8316. : fillPath( _color );
  8317. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8318. var normal;
  8319. if ( material.shading == THREE.FlatShading ) {
  8320. normal = element.normalModelView;
  8321. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8322. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8323. material.wireframe === true
  8324. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8325. : fillPath( _color );
  8326. } else if ( material.shading == THREE.SmoothShading ) {
  8327. normal = element.vertexNormalsModelView[ 0 ];
  8328. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8329. normal = element.vertexNormalsModelView[ 1 ];
  8330. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8331. normal = element.vertexNormalsModelView[ 3 ];
  8332. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8333. normal = element.vertexNormalsModelView[ 2 ];
  8334. _color4.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8335. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8336. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8337. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8338. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8339. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8340. }
  8341. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8342. _near = camera.near;
  8343. _far = camera.far;
  8344. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  8345. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  8346. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z, _near, _far );
  8347. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  8348. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8349. // TODO: UVs are incorrect, v4->v3?
  8350. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8351. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8352. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8353. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8354. }
  8355. }
  8356. //
  8357. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  8358. _context.beginPath();
  8359. _context.moveTo( x0, y0 );
  8360. _context.lineTo( x1, y1 );
  8361. _context.lineTo( x2, y2 );
  8362. _context.closePath();
  8363. }
  8364. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  8365. _context.beginPath();
  8366. _context.moveTo( x0, y0 );
  8367. _context.lineTo( x1, y1 );
  8368. _context.lineTo( x2, y2 );
  8369. _context.lineTo( x3, y3 );
  8370. _context.closePath();
  8371. }
  8372. function strokePath( color, linewidth, linecap, linejoin ) {
  8373. setLineWidth( linewidth );
  8374. setLineCap( linecap );
  8375. setLineJoin( linejoin );
  8376. setStrokeStyle( color.getStyle() );
  8377. _context.stroke();
  8378. _elemBox.expandByScalar( linewidth * 2 );
  8379. }
  8380. function fillPath( color ) {
  8381. setFillStyle( color.getStyle() );
  8382. _context.fill();
  8383. }
  8384. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  8385. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  8386. if ( texture.needsUpdate === true ) {
  8387. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  8388. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  8389. _patterns[ texture.id ] = _context.createPattern(
  8390. texture.image, repeatX === true && repeatY === true
  8391. ? 'repeat'
  8392. : repeatX === true && repeatY === false
  8393. ? 'repeat-x'
  8394. : repeatX === false && repeatY === true
  8395. ? 'repeat-y'
  8396. : 'no-repeat'
  8397. );
  8398. texture.needsUpdate = false;
  8399. }
  8400. _patterns[ texture.id ] === undefined
  8401. ? setFillStyle( 'rgba(0,0,0,1)' )
  8402. : setFillStyle( _patterns[ texture.id ] );
  8403. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8404. var a, b, c, d, e, f, det, idet,
  8405. offsetX = texture.offset.x / texture.repeat.x,
  8406. offsetY = texture.offset.y / texture.repeat.y,
  8407. width = texture.image.width * texture.repeat.x,
  8408. height = texture.image.height * texture.repeat.y;
  8409. u0 = ( u0 + offsetX ) * width;
  8410. v0 = ( 1.0 - v0 + offsetY ) * height;
  8411. u1 = ( u1 + offsetX ) * width;
  8412. v1 = ( 1.0 - v1 + offsetY ) * height;
  8413. u2 = ( u2 + offsetX ) * width;
  8414. v2 = ( 1.0 - v2 + offsetY ) * height;
  8415. x1 -= x0; y1 -= y0;
  8416. x2 -= x0; y2 -= y0;
  8417. u1 -= u0; v1 -= v0;
  8418. u2 -= u0; v2 -= v0;
  8419. det = u1 * v2 - u2 * v1;
  8420. if ( det === 0 ) {
  8421. if ( _imagedatas[ texture.id ] === undefined ) {
  8422. var canvas = document.createElement( 'canvas' )
  8423. canvas.width = texture.image.width;
  8424. canvas.height = texture.image.height;
  8425. var context = canvas.getContext( '2d' );
  8426. context.drawImage( texture.image, 0, 0 );
  8427. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  8428. }
  8429. var data = _imagedatas[ texture.id ];
  8430. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  8431. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  8432. fillPath( _color );
  8433. return;
  8434. }
  8435. idet = 1 / det;
  8436. a = ( v2 * x1 - v1 * x2 ) * idet;
  8437. b = ( v2 * y1 - v1 * y2 ) * idet;
  8438. c = ( u1 * x2 - u2 * x1 ) * idet;
  8439. d = ( u1 * y2 - u2 * y1 ) * idet;
  8440. e = x0 - a * u0 - c * v0;
  8441. f = y0 - b * u0 - d * v0;
  8442. _context.save();
  8443. _context.transform( a, b, c, d, e, f );
  8444. _context.fill();
  8445. _context.restore();
  8446. }
  8447. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  8448. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8449. var a, b, c, d, e, f, det, idet,
  8450. width = image.width - 1,
  8451. height = image.height - 1;
  8452. u0 *= width; v0 *= height;
  8453. u1 *= width; v1 *= height;
  8454. u2 *= width; v2 *= height;
  8455. x1 -= x0; y1 -= y0;
  8456. x2 -= x0; y2 -= y0;
  8457. u1 -= u0; v1 -= v0;
  8458. u2 -= u0; v2 -= v0;
  8459. det = u1 * v2 - u2 * v1;
  8460. idet = 1 / det;
  8461. a = ( v2 * x1 - v1 * x2 ) * idet;
  8462. b = ( v2 * y1 - v1 * y2 ) * idet;
  8463. c = ( u1 * x2 - u2 * x1 ) * idet;
  8464. d = ( u1 * y2 - u2 * y1 ) * idet;
  8465. e = x0 - a * u0 - c * v0;
  8466. f = y0 - b * u0 - d * v0;
  8467. _context.save();
  8468. _context.transform( a, b, c, d, e, f );
  8469. _context.clip();
  8470. _context.drawImage( image, 0, 0 );
  8471. _context.restore();
  8472. }
  8473. function getGradientTexture( color1, color2, color3, color4 ) {
  8474. // http://mrdoob.com/blog/post/710
  8475. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  8476. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  8477. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  8478. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  8479. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  8480. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  8481. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  8482. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  8483. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  8484. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  8485. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  8486. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  8487. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  8488. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  8489. return _gradientMap;
  8490. }
  8491. function smoothstep( value, min, max ) {
  8492. var x = ( value - min ) / ( max - min );
  8493. return x * x * ( 3 - 2 * x );
  8494. }
  8495. // Hide anti-alias gaps
  8496. function expand( v1, v2 ) {
  8497. var x = v2.x - v1.x, y = v2.y - v1.y,
  8498. det = x * x + y * y, idet;
  8499. if ( det === 0 ) return;
  8500. idet = 1 / Math.sqrt( det );
  8501. x *= idet; y *= idet;
  8502. v2.x += x; v2.y += y;
  8503. v1.x -= x; v1.y -= y;
  8504. }
  8505. };
  8506. // Context cached methods.
  8507. function setOpacity( value ) {
  8508. if ( _contextGlobalAlpha !== value ) {
  8509. _context.globalAlpha = value;
  8510. _contextGlobalAlpha = value;
  8511. }
  8512. }
  8513. function setBlending( value ) {
  8514. if ( _contextGlobalCompositeOperation !== value ) {
  8515. if ( value === THREE.NormalBlending ) {
  8516. _context.globalCompositeOperation = 'source-over';
  8517. } else if ( value === THREE.AdditiveBlending ) {
  8518. _context.globalCompositeOperation = 'lighter';
  8519. } else if ( value === THREE.SubtractiveBlending ) {
  8520. _context.globalCompositeOperation = 'darker';
  8521. }
  8522. _contextGlobalCompositeOperation = value;
  8523. }
  8524. }
  8525. function setLineWidth( value ) {
  8526. if ( _contextLineWidth !== value ) {
  8527. _context.lineWidth = value;
  8528. _contextLineWidth = value;
  8529. }
  8530. }
  8531. function setLineCap( value ) {
  8532. // "butt", "round", "square"
  8533. if ( _contextLineCap !== value ) {
  8534. _context.lineCap = value;
  8535. _contextLineCap = value;
  8536. }
  8537. }
  8538. function setLineJoin( value ) {
  8539. // "round", "bevel", "miter"
  8540. if ( _contextLineJoin !== value ) {
  8541. _context.lineJoin = value;
  8542. _contextLineJoin = value;
  8543. }
  8544. }
  8545. function setStrokeStyle( value ) {
  8546. if ( _contextStrokeStyle !== value ) {
  8547. _context.strokeStyle = value;
  8548. _contextStrokeStyle = value;
  8549. }
  8550. }
  8551. function setFillStyle( value ) {
  8552. if ( _contextFillStyle !== value ) {
  8553. _context.fillStyle = value;
  8554. _contextFillStyle = value;
  8555. }
  8556. }
  8557. };
  8558. /**
  8559. * @author alteredq / http://alteredqualia.com/
  8560. * @author mrdoob / http://mrdoob.com/
  8561. * @author mikael emtinger / http://gomo.se/
  8562. */
  8563. THREE.ShaderChunk = {
  8564. // FOG
  8565. fog_pars_fragment: [
  8566. "#ifdef USE_FOG",
  8567. "uniform vec3 fogColor;",
  8568. "#ifdef FOG_EXP2",
  8569. "uniform float fogDensity;",
  8570. "#else",
  8571. "uniform float fogNear;",
  8572. "uniform float fogFar;",
  8573. "#endif",
  8574. "#endif"
  8575. ].join("\n"),
  8576. fog_fragment: [
  8577. "#ifdef USE_FOG",
  8578. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  8579. "#ifdef FOG_EXP2",
  8580. "const float LOG2 = 1.442695;",
  8581. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  8582. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  8583. "#else",
  8584. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  8585. "#endif",
  8586. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  8587. "#endif"
  8588. ].join("\n"),
  8589. // ENVIRONMENT MAP
  8590. envmap_pars_fragment: [
  8591. "#ifdef USE_ENVMAP",
  8592. "uniform float reflectivity;",
  8593. "uniform samplerCube envMap;",
  8594. "uniform float flipEnvMap;",
  8595. "uniform int combine;",
  8596. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8597. "uniform bool useRefract;",
  8598. "uniform float refractionRatio;",
  8599. "#else",
  8600. "varying vec3 vReflect;",
  8601. "#endif",
  8602. "#endif"
  8603. ].join("\n"),
  8604. envmap_fragment: [
  8605. "#ifdef USE_ENVMAP",
  8606. "vec3 reflectVec;",
  8607. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8608. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  8609. "if ( useRefract ) {",
  8610. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  8611. "} else { ",
  8612. "reflectVec = reflect( cameraToVertex, normal );",
  8613. "}",
  8614. "#else",
  8615. "reflectVec = vReflect;",
  8616. "#endif",
  8617. "#ifdef DOUBLE_SIDED",
  8618. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  8619. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8620. "#else",
  8621. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8622. "#endif",
  8623. "#ifdef GAMMA_INPUT",
  8624. "cubeColor.xyz *= cubeColor.xyz;",
  8625. "#endif",
  8626. "if ( combine == 1 ) {",
  8627. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  8628. "} else if ( combine == 2 ) {",
  8629. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  8630. "} else {",
  8631. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  8632. "}",
  8633. "#endif"
  8634. ].join("\n"),
  8635. envmap_pars_vertex: [
  8636. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8637. "varying vec3 vReflect;",
  8638. "uniform float refractionRatio;",
  8639. "uniform bool useRefract;",
  8640. "#endif"
  8641. ].join("\n"),
  8642. worldpos_vertex : [
  8643. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  8644. "#ifdef USE_SKINNING",
  8645. "vec4 worldPosition = modelMatrix * skinned;",
  8646. "#endif",
  8647. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8648. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  8649. "#endif",
  8650. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8651. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  8652. "#endif",
  8653. "#endif"
  8654. ].join("\n"),
  8655. envmap_vertex : [
  8656. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8657. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  8658. "worldNormal = normalize( worldNormal );",
  8659. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  8660. "if ( useRefract ) {",
  8661. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  8662. "} else {",
  8663. "vReflect = reflect( cameraToVertex, worldNormal );",
  8664. "}",
  8665. "#endif"
  8666. ].join("\n"),
  8667. // COLOR MAP (particles)
  8668. map_particle_pars_fragment: [
  8669. "#ifdef USE_MAP",
  8670. "uniform sampler2D map;",
  8671. "#endif"
  8672. ].join("\n"),
  8673. map_particle_fragment: [
  8674. "#ifdef USE_MAP",
  8675. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  8676. "#endif"
  8677. ].join("\n"),
  8678. // COLOR MAP (triangles)
  8679. map_pars_vertex: [
  8680. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8681. "varying vec2 vUv;",
  8682. "uniform vec4 offsetRepeat;",
  8683. "#endif"
  8684. ].join("\n"),
  8685. map_pars_fragment: [
  8686. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8687. "varying vec2 vUv;",
  8688. "#endif",
  8689. "#ifdef USE_MAP",
  8690. "uniform sampler2D map;",
  8691. "#endif"
  8692. ].join("\n"),
  8693. map_vertex: [
  8694. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8695. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  8696. "#endif"
  8697. ].join("\n"),
  8698. map_fragment: [
  8699. "#ifdef USE_MAP",
  8700. "vec4 texelColor = texture2D( map, vUv );",
  8701. "#ifdef GAMMA_INPUT",
  8702. "texelColor.xyz *= texelColor.xyz;",
  8703. "#endif",
  8704. "gl_FragColor = gl_FragColor * texelColor;",
  8705. "#endif"
  8706. ].join("\n"),
  8707. // LIGHT MAP
  8708. lightmap_pars_fragment: [
  8709. "#ifdef USE_LIGHTMAP",
  8710. "varying vec2 vUv2;",
  8711. "uniform sampler2D lightMap;",
  8712. "#endif"
  8713. ].join("\n"),
  8714. lightmap_pars_vertex: [
  8715. "#ifdef USE_LIGHTMAP",
  8716. "varying vec2 vUv2;",
  8717. "#endif"
  8718. ].join("\n"),
  8719. lightmap_fragment: [
  8720. "#ifdef USE_LIGHTMAP",
  8721. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  8722. "#endif"
  8723. ].join("\n"),
  8724. lightmap_vertex: [
  8725. "#ifdef USE_LIGHTMAP",
  8726. "vUv2 = uv2;",
  8727. "#endif"
  8728. ].join("\n"),
  8729. // BUMP MAP
  8730. bumpmap_pars_fragment: [
  8731. "#ifdef USE_BUMPMAP",
  8732. "uniform sampler2D bumpMap;",
  8733. "uniform float bumpScale;",
  8734. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  8735. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  8736. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8737. "vec2 dHdxy_fwd() {",
  8738. "vec2 dSTdx = dFdx( vUv );",
  8739. "vec2 dSTdy = dFdy( vUv );",
  8740. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  8741. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  8742. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  8743. "return vec2( dBx, dBy );",
  8744. "}",
  8745. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  8746. "vec3 vSigmaX = dFdx( surf_pos );",
  8747. "vec3 vSigmaY = dFdy( surf_pos );",
  8748. "vec3 vN = surf_norm;", // normalized
  8749. "vec3 R1 = cross( vSigmaY, vN );",
  8750. "vec3 R2 = cross( vN, vSigmaX );",
  8751. "float fDet = dot( vSigmaX, R1 );",
  8752. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  8753. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  8754. "}",
  8755. "#endif"
  8756. ].join("\n"),
  8757. // NORMAL MAP
  8758. normalmap_pars_fragment: [
  8759. "#ifdef USE_NORMALMAP",
  8760. "uniform sampler2D normalMap;",
  8761. "uniform vec2 normalScale;",
  8762. // Per-Pixel Tangent Space Normal Mapping
  8763. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  8764. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  8765. "vec3 q0 = dFdx( eye_pos.xyz );",
  8766. "vec3 q1 = dFdy( eye_pos.xyz );",
  8767. "vec2 st0 = dFdx( vUv.st );",
  8768. "vec2 st1 = dFdy( vUv.st );",
  8769. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  8770. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  8771. "vec3 N = normalize( surf_norm );",
  8772. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  8773. "mapN.xy = normalScale * mapN.xy;",
  8774. "mat3 tsn = mat3( S, T, N );",
  8775. "return normalize( tsn * mapN );",
  8776. "}",
  8777. "#endif"
  8778. ].join("\n"),
  8779. // SPECULAR MAP
  8780. specularmap_pars_fragment: [
  8781. "#ifdef USE_SPECULARMAP",
  8782. "uniform sampler2D specularMap;",
  8783. "#endif"
  8784. ].join("\n"),
  8785. specularmap_fragment: [
  8786. "float specularStrength;",
  8787. "#ifdef USE_SPECULARMAP",
  8788. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  8789. "specularStrength = texelSpecular.r;",
  8790. "#else",
  8791. "specularStrength = 1.0;",
  8792. "#endif"
  8793. ].join("\n"),
  8794. // LIGHTS LAMBERT
  8795. lights_lambert_pars_vertex: [
  8796. "uniform vec3 ambient;",
  8797. "uniform vec3 diffuse;",
  8798. "uniform vec3 emissive;",
  8799. "uniform vec3 ambientLightColor;",
  8800. "#if MAX_DIR_LIGHTS > 0",
  8801. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  8802. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  8803. "#endif",
  8804. "#if MAX_HEMI_LIGHTS > 0",
  8805. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  8806. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  8807. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  8808. "#endif",
  8809. "#if MAX_POINT_LIGHTS > 0",
  8810. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  8811. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8812. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8813. "#endif",
  8814. "#if MAX_SPOT_LIGHTS > 0",
  8815. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  8816. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8817. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  8818. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8819. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  8820. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  8821. "#endif",
  8822. "#ifdef WRAP_AROUND",
  8823. "uniform vec3 wrapRGB;",
  8824. "#endif"
  8825. ].join("\n"),
  8826. lights_lambert_vertex: [
  8827. "vLightFront = vec3( 0.0 );",
  8828. "#ifdef DOUBLE_SIDED",
  8829. "vLightBack = vec3( 0.0 );",
  8830. "#endif",
  8831. "transformedNormal = normalize( transformedNormal );",
  8832. "#if MAX_DIR_LIGHTS > 0",
  8833. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  8834. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  8835. "vec3 dirVector = normalize( lDirection.xyz );",
  8836. "float dotProduct = dot( transformedNormal, dirVector );",
  8837. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8838. "#ifdef DOUBLE_SIDED",
  8839. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8840. "#ifdef WRAP_AROUND",
  8841. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8842. "#endif",
  8843. "#endif",
  8844. "#ifdef WRAP_AROUND",
  8845. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8846. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  8847. "#ifdef DOUBLE_SIDED",
  8848. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  8849. "#endif",
  8850. "#endif",
  8851. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  8852. "#ifdef DOUBLE_SIDED",
  8853. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  8854. "#endif",
  8855. "}",
  8856. "#endif",
  8857. "#if MAX_POINT_LIGHTS > 0",
  8858. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8859. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8860. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8861. "float lDistance = 1.0;",
  8862. "if ( pointLightDistance[ i ] > 0.0 )",
  8863. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8864. "lVector = normalize( lVector );",
  8865. "float dotProduct = dot( transformedNormal, lVector );",
  8866. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8867. "#ifdef DOUBLE_SIDED",
  8868. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8869. "#ifdef WRAP_AROUND",
  8870. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8871. "#endif",
  8872. "#endif",
  8873. "#ifdef WRAP_AROUND",
  8874. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8875. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  8876. "#ifdef DOUBLE_SIDED",
  8877. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  8878. "#endif",
  8879. "#endif",
  8880. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  8881. "#ifdef DOUBLE_SIDED",
  8882. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  8883. "#endif",
  8884. "}",
  8885. "#endif",
  8886. "#if MAX_SPOT_LIGHTS > 0",
  8887. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8888. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8889. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8890. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  8891. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  8892. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  8893. "float lDistance = 1.0;",
  8894. "if ( spotLightDistance[ i ] > 0.0 )",
  8895. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8896. "lVector = normalize( lVector );",
  8897. "float dotProduct = dot( transformedNormal, lVector );",
  8898. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8899. "#ifdef DOUBLE_SIDED",
  8900. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8901. "#ifdef WRAP_AROUND",
  8902. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8903. "#endif",
  8904. "#endif",
  8905. "#ifdef WRAP_AROUND",
  8906. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8907. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  8908. "#ifdef DOUBLE_SIDED",
  8909. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  8910. "#endif",
  8911. "#endif",
  8912. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  8913. "#ifdef DOUBLE_SIDED",
  8914. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  8915. "#endif",
  8916. "}",
  8917. "}",
  8918. "#endif",
  8919. "#if MAX_HEMI_LIGHTS > 0",
  8920. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  8921. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  8922. "vec3 lVector = normalize( lDirection.xyz );",
  8923. "float dotProduct = dot( transformedNormal, lVector );",
  8924. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  8925. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  8926. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  8927. "#ifdef DOUBLE_SIDED",
  8928. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  8929. "#endif",
  8930. "}",
  8931. "#endif",
  8932. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  8933. "#ifdef DOUBLE_SIDED",
  8934. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  8935. "#endif"
  8936. ].join("\n"),
  8937. // LIGHTS PHONG
  8938. lights_phong_pars_vertex: [
  8939. "#ifndef PHONG_PER_PIXEL",
  8940. "#if MAX_POINT_LIGHTS > 0",
  8941. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8942. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8943. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  8944. "#endif",
  8945. "#if MAX_SPOT_LIGHTS > 0",
  8946. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8947. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8948. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  8949. "#endif",
  8950. "#endif",
  8951. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8952. "varying vec3 vWorldPosition;",
  8953. "#endif"
  8954. ].join("\n"),
  8955. lights_phong_vertex: [
  8956. "#ifndef PHONG_PER_PIXEL",
  8957. "#if MAX_POINT_LIGHTS > 0",
  8958. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8959. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8960. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8961. "float lDistance = 1.0;",
  8962. "if ( pointLightDistance[ i ] > 0.0 )",
  8963. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8964. "vPointLight[ i ] = vec4( lVector, lDistance );",
  8965. "}",
  8966. "#endif",
  8967. "#if MAX_SPOT_LIGHTS > 0",
  8968. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8969. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8970. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8971. "float lDistance = 1.0;",
  8972. "if ( spotLightDistance[ i ] > 0.0 )",
  8973. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8974. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  8975. "}",
  8976. "#endif",
  8977. "#endif",
  8978. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8979. "vWorldPosition = worldPosition.xyz;",
  8980. "#endif"
  8981. ].join("\n"),
  8982. lights_phong_pars_fragment: [
  8983. "uniform vec3 ambientLightColor;",
  8984. "#if MAX_DIR_LIGHTS > 0",
  8985. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  8986. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  8987. "#endif",
  8988. "#if MAX_HEMI_LIGHTS > 0",
  8989. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  8990. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  8991. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  8992. "#endif",
  8993. "#if MAX_POINT_LIGHTS > 0",
  8994. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  8995. "#ifdef PHONG_PER_PIXEL",
  8996. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8997. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8998. "#else",
  8999. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9000. "#endif",
  9001. "#endif",
  9002. "#if MAX_SPOT_LIGHTS > 0",
  9003. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9004. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9005. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9006. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9007. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9008. "#ifdef PHONG_PER_PIXEL",
  9009. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9010. "#else",
  9011. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9012. "#endif",
  9013. "#endif",
  9014. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9015. "varying vec3 vWorldPosition;",
  9016. "#endif",
  9017. "#ifdef WRAP_AROUND",
  9018. "uniform vec3 wrapRGB;",
  9019. "#endif",
  9020. "varying vec3 vViewPosition;",
  9021. "varying vec3 vNormal;"
  9022. ].join("\n"),
  9023. lights_phong_fragment: [
  9024. "vec3 normal = normalize( vNormal );",
  9025. "vec3 viewPosition = normalize( vViewPosition );",
  9026. "#ifdef DOUBLE_SIDED",
  9027. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9028. "#endif",
  9029. "#ifdef USE_NORMALMAP",
  9030. "normal = perturbNormal2Arb( -viewPosition, normal );",
  9031. "#elif defined( USE_BUMPMAP )",
  9032. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  9033. "#endif",
  9034. "#if MAX_POINT_LIGHTS > 0",
  9035. "vec3 pointDiffuse = vec3( 0.0 );",
  9036. "vec3 pointSpecular = vec3( 0.0 );",
  9037. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9038. "#ifdef PHONG_PER_PIXEL",
  9039. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9040. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9041. "float lDistance = 1.0;",
  9042. "if ( pointLightDistance[ i ] > 0.0 )",
  9043. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9044. "lVector = normalize( lVector );",
  9045. "#else",
  9046. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  9047. "float lDistance = vPointLight[ i ].w;",
  9048. "#endif",
  9049. // diffuse
  9050. "float dotProduct = dot( normal, lVector );",
  9051. "#ifdef WRAP_AROUND",
  9052. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  9053. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9054. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  9055. "#else",
  9056. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  9057. "#endif",
  9058. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  9059. // specular
  9060. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  9061. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  9062. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  9063. "#ifdef PHYSICALLY_BASED_SHADING",
  9064. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9065. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9066. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  9067. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  9068. "#else",
  9069. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  9070. "#endif",
  9071. "}",
  9072. "#endif",
  9073. "#if MAX_SPOT_LIGHTS > 0",
  9074. "vec3 spotDiffuse = vec3( 0.0 );",
  9075. "vec3 spotSpecular = vec3( 0.0 );",
  9076. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9077. "#ifdef PHONG_PER_PIXEL",
  9078. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9079. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9080. "float lDistance = 1.0;",
  9081. "if ( spotLightDistance[ i ] > 0.0 )",
  9082. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9083. "lVector = normalize( lVector );",
  9084. "#else",
  9085. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  9086. "float lDistance = vSpotLight[ i ].w;",
  9087. "#endif",
  9088. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  9089. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9090. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9091. // diffuse
  9092. "float dotProduct = dot( normal, lVector );",
  9093. "#ifdef WRAP_AROUND",
  9094. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  9095. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9096. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  9097. "#else",
  9098. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  9099. "#endif",
  9100. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  9101. // specular
  9102. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  9103. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  9104. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  9105. "#ifdef PHYSICALLY_BASED_SHADING",
  9106. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9107. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9108. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  9109. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  9110. "#else",
  9111. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  9112. "#endif",
  9113. "}",
  9114. "}",
  9115. "#endif",
  9116. "#if MAX_DIR_LIGHTS > 0",
  9117. "vec3 dirDiffuse = vec3( 0.0 );",
  9118. "vec3 dirSpecular = vec3( 0.0 );" ,
  9119. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9120. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9121. "vec3 dirVector = normalize( lDirection.xyz );",
  9122. // diffuse
  9123. "float dotProduct = dot( normal, dirVector );",
  9124. "#ifdef WRAP_AROUND",
  9125. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  9126. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9127. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  9128. "#else",
  9129. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  9130. "#endif",
  9131. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  9132. // specular
  9133. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  9134. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  9135. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  9136. "#ifdef PHYSICALLY_BASED_SHADING",
  9137. /*
  9138. // fresnel term from skin shader
  9139. "const float F0 = 0.128;",
  9140. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  9141. "float exponential = pow( base, 5.0 );",
  9142. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  9143. */
  9144. /*
  9145. // fresnel term from fresnel shader
  9146. "const float mFresnelBias = 0.08;",
  9147. "const float mFresnelScale = 0.3;",
  9148. "const float mFresnelPower = 5.0;",
  9149. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  9150. */
  9151. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9152. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9153. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  9154. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  9155. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  9156. "#else",
  9157. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  9158. "#endif",
  9159. "}",
  9160. "#endif",
  9161. "#if MAX_HEMI_LIGHTS > 0",
  9162. "vec3 hemiDiffuse = vec3( 0.0 );",
  9163. "vec3 hemiSpecular = vec3( 0.0 );" ,
  9164. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9165. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9166. "vec3 lVector = normalize( lDirection.xyz );",
  9167. // diffuse
  9168. "float dotProduct = dot( normal, lVector );",
  9169. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9170. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9171. "hemiDiffuse += diffuse * hemiColor;",
  9172. // specular (sky light)
  9173. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  9174. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  9175. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  9176. // specular (ground light)
  9177. "vec3 lVectorGround = -lVector;",
  9178. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  9179. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  9180. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  9181. "#ifdef PHYSICALLY_BASED_SHADING",
  9182. "float dotProductGround = dot( normal, lVectorGround );",
  9183. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9184. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9185. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  9186. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  9187. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  9188. "#else",
  9189. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  9190. "#endif",
  9191. "}",
  9192. "#endif",
  9193. "vec3 totalDiffuse = vec3( 0.0 );",
  9194. "vec3 totalSpecular = vec3( 0.0 );",
  9195. "#if MAX_DIR_LIGHTS > 0",
  9196. "totalDiffuse += dirDiffuse;",
  9197. "totalSpecular += dirSpecular;",
  9198. "#endif",
  9199. "#if MAX_HEMI_LIGHTS > 0",
  9200. "totalDiffuse += hemiDiffuse;",
  9201. "totalSpecular += hemiSpecular;",
  9202. "#endif",
  9203. "#if MAX_POINT_LIGHTS > 0",
  9204. "totalDiffuse += pointDiffuse;",
  9205. "totalSpecular += pointSpecular;",
  9206. "#endif",
  9207. "#if MAX_SPOT_LIGHTS > 0",
  9208. "totalDiffuse += spotDiffuse;",
  9209. "totalSpecular += spotSpecular;",
  9210. "#endif",
  9211. "#ifdef METAL",
  9212. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  9213. "#else",
  9214. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  9215. "#endif"
  9216. ].join("\n"),
  9217. // VERTEX COLORS
  9218. color_pars_fragment: [
  9219. "#ifdef USE_COLOR",
  9220. "varying vec3 vColor;",
  9221. "#endif"
  9222. ].join("\n"),
  9223. color_fragment: [
  9224. "#ifdef USE_COLOR",
  9225. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  9226. "#endif"
  9227. ].join("\n"),
  9228. color_pars_vertex: [
  9229. "#ifdef USE_COLOR",
  9230. "varying vec3 vColor;",
  9231. "#endif"
  9232. ].join("\n"),
  9233. color_vertex: [
  9234. "#ifdef USE_COLOR",
  9235. "#ifdef GAMMA_INPUT",
  9236. "vColor = color * color;",
  9237. "#else",
  9238. "vColor = color;",
  9239. "#endif",
  9240. "#endif"
  9241. ].join("\n"),
  9242. // SKINNING
  9243. skinning_pars_vertex: [
  9244. "#ifdef USE_SKINNING",
  9245. "#ifdef BONE_TEXTURE",
  9246. "uniform sampler2D boneTexture;",
  9247. "mat4 getBoneMatrix( const in float i ) {",
  9248. "float j = i * 4.0;",
  9249. "float x = mod( j, N_BONE_PIXEL_X );",
  9250. "float y = floor( j / N_BONE_PIXEL_X );",
  9251. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  9252. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  9253. "y = dy * ( y + 0.5 );",
  9254. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  9255. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  9256. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  9257. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  9258. "mat4 bone = mat4( v1, v2, v3, v4 );",
  9259. "return bone;",
  9260. "}",
  9261. "#else",
  9262. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  9263. "mat4 getBoneMatrix( const in float i ) {",
  9264. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  9265. "return bone;",
  9266. "}",
  9267. "#endif",
  9268. "#endif"
  9269. ].join("\n"),
  9270. skinbase_vertex: [
  9271. "#ifdef USE_SKINNING",
  9272. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  9273. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  9274. "#endif"
  9275. ].join("\n"),
  9276. skinning_vertex: [
  9277. "#ifdef USE_SKINNING",
  9278. "#ifdef USE_MORPHTARGETS",
  9279. "vec4 skinVertex = vec4( morphed, 1.0 );",
  9280. "#else",
  9281. "vec4 skinVertex = vec4( position, 1.0 );",
  9282. "#endif",
  9283. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  9284. "skinned += boneMatY * skinVertex * skinWeight.y;",
  9285. "#endif"
  9286. ].join("\n"),
  9287. // MORPHING
  9288. morphtarget_pars_vertex: [
  9289. "#ifdef USE_MORPHTARGETS",
  9290. "#ifndef USE_MORPHNORMALS",
  9291. "uniform float morphTargetInfluences[ 8 ];",
  9292. "#else",
  9293. "uniform float morphTargetInfluences[ 4 ];",
  9294. "#endif",
  9295. "#endif"
  9296. ].join("\n"),
  9297. morphtarget_vertex: [
  9298. "#ifdef USE_MORPHTARGETS",
  9299. "vec3 morphed = vec3( 0.0 );",
  9300. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  9301. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  9302. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  9303. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  9304. "#ifndef USE_MORPHNORMALS",
  9305. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  9306. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  9307. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  9308. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  9309. "#endif",
  9310. "morphed += position;",
  9311. "#endif"
  9312. ].join("\n"),
  9313. default_vertex : [
  9314. "vec4 mvPosition;",
  9315. "#ifdef USE_SKINNING",
  9316. "mvPosition = modelViewMatrix * skinned;",
  9317. "#endif",
  9318. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  9319. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  9320. "#endif",
  9321. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  9322. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9323. "#endif",
  9324. "gl_Position = projectionMatrix * mvPosition;"
  9325. ].join("\n"),
  9326. morphnormal_vertex: [
  9327. "#ifdef USE_MORPHNORMALS",
  9328. "vec3 morphedNormal = vec3( 0.0 );",
  9329. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  9330. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  9331. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  9332. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  9333. "morphedNormal += normal;",
  9334. "#endif"
  9335. ].join("\n"),
  9336. skinnormal_vertex: [
  9337. "#ifdef USE_SKINNING",
  9338. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  9339. "skinMatrix += skinWeight.y * boneMatY;",
  9340. "#ifdef USE_MORPHNORMALS",
  9341. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  9342. "#else",
  9343. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  9344. "#endif",
  9345. "#endif"
  9346. ].join("\n"),
  9347. defaultnormal_vertex: [
  9348. "vec3 objectNormal;",
  9349. "#ifdef USE_SKINNING",
  9350. "objectNormal = skinnedNormal.xyz;",
  9351. "#endif",
  9352. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  9353. "objectNormal = morphedNormal;",
  9354. "#endif",
  9355. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  9356. "objectNormal = normal;",
  9357. "#endif",
  9358. "#ifdef FLIP_SIDED",
  9359. "objectNormal = -objectNormal;",
  9360. "#endif",
  9361. "vec3 transformedNormal = normalMatrix * objectNormal;"
  9362. ].join("\n"),
  9363. // SHADOW MAP
  9364. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  9365. // http://spidergl.org/example.php?id=6
  9366. // http://fabiensanglard.net/shadowmapping
  9367. shadowmap_pars_fragment: [
  9368. "#ifdef USE_SHADOWMAP",
  9369. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  9370. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  9371. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  9372. "uniform float shadowBias[ MAX_SHADOWS ];",
  9373. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  9374. "float unpackDepth( const in vec4 rgba_depth ) {",
  9375. "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 );",
  9376. "float depth = dot( rgba_depth, bit_shift );",
  9377. "return depth;",
  9378. "}",
  9379. "#endif"
  9380. ].join("\n"),
  9381. shadowmap_fragment: [
  9382. "#ifdef USE_SHADOWMAP",
  9383. "#ifdef SHADOWMAP_DEBUG",
  9384. "vec3 frustumColors[3];",
  9385. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  9386. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  9387. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  9388. "#endif",
  9389. "#ifdef SHADOWMAP_CASCADE",
  9390. "int inFrustumCount = 0;",
  9391. "#endif",
  9392. "float fDepth;",
  9393. "vec3 shadowColor = vec3( 1.0 );",
  9394. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  9395. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  9396. // "if ( something && something )" breaks ATI OpenGL shader compiler
  9397. // "if ( all( something, something ) )" using this instead
  9398. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  9399. "bool inFrustum = all( inFrustumVec );",
  9400. // don't shadow pixels outside of light frustum
  9401. // use just first frustum (for cascades)
  9402. // don't shadow pixels behind far plane of light frustum
  9403. "#ifdef SHADOWMAP_CASCADE",
  9404. "inFrustumCount += int( inFrustum );",
  9405. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  9406. "#else",
  9407. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  9408. "#endif",
  9409. "bool frustumTest = all( frustumTestVec );",
  9410. "if ( frustumTest ) {",
  9411. "shadowCoord.z += shadowBias[ i ];",
  9412. "#if defined( SHADOWMAP_TYPE_PCF )",
  9413. // Percentage-close filtering
  9414. // (9 pixel kernel)
  9415. // http://fabiensanglard.net/shadowmappingPCF/
  9416. "float shadow = 0.0;",
  9417. /*
  9418. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  9419. // must enroll loop manually
  9420. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  9421. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  9422. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  9423. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  9424. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  9425. "float fDepth = unpackDepth( rgbaDepth );",
  9426. "if ( fDepth < shadowCoord.z )",
  9427. "shadow += 1.0;",
  9428. "}",
  9429. "shadow /= 9.0;",
  9430. */
  9431. "const float shadowDelta = 1.0 / 9.0;",
  9432. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  9433. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  9434. "float dx0 = -1.25 * xPixelOffset;",
  9435. "float dy0 = -1.25 * yPixelOffset;",
  9436. "float dx1 = 1.25 * xPixelOffset;",
  9437. "float dy1 = 1.25 * yPixelOffset;",
  9438. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  9439. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9440. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  9441. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9442. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  9443. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9444. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  9445. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9446. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  9447. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9448. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  9449. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9450. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  9451. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9452. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  9453. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9454. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  9455. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9456. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  9457. "#elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  9458. // Percentage-close filtering
  9459. // (9 pixel kernel)
  9460. // http://fabiensanglard.net/shadowmappingPCF/
  9461. "float shadow = 0.0;",
  9462. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  9463. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  9464. "float dx0 = -1.0 * xPixelOffset;",
  9465. "float dy0 = -1.0 * yPixelOffset;",
  9466. "float dx1 = 1.0 * xPixelOffset;",
  9467. "float dy1 = 1.0 * yPixelOffset;",
  9468. "mat3 shadowKernel;",
  9469. "mat3 depthKernel;",
  9470. "depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  9471. "if ( depthKernel[0][0] < shadowCoord.z ) shadowKernel[0][0] = 0.25;",
  9472. "else shadowKernel[0][0] = 0.0;",
  9473. "depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  9474. "if ( depthKernel[0][1] < shadowCoord.z ) shadowKernel[0][1] = 0.25;",
  9475. "else shadowKernel[0][1] = 0.0;",
  9476. "depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  9477. "if ( depthKernel[0][2] < shadowCoord.z ) shadowKernel[0][2] = 0.25;",
  9478. "else shadowKernel[0][2] = 0.0;",
  9479. "depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  9480. "if ( depthKernel[1][0] < shadowCoord.z ) shadowKernel[1][0] = 0.25;",
  9481. "else shadowKernel[1][0] = 0.0;",
  9482. "depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  9483. "if ( depthKernel[1][1] < shadowCoord.z ) shadowKernel[1][1] = 0.25;",
  9484. "else shadowKernel[1][1] = 0.0;",
  9485. "depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  9486. "if ( depthKernel[1][2] < shadowCoord.z ) shadowKernel[1][2] = 0.25;",
  9487. "else shadowKernel[1][2] = 0.0;",
  9488. "depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  9489. "if ( depthKernel[2][0] < shadowCoord.z ) shadowKernel[2][0] = 0.25;",
  9490. "else shadowKernel[2][0] = 0.0;",
  9491. "depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  9492. "if ( depthKernel[2][1] < shadowCoord.z ) shadowKernel[2][1] = 0.25;",
  9493. "else shadowKernel[2][1] = 0.0;",
  9494. "depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  9495. "if ( depthKernel[2][2] < shadowCoord.z ) shadowKernel[2][2] = 0.25;",
  9496. "else shadowKernel[2][2] = 0.0;",
  9497. "vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  9498. "shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  9499. "shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  9500. "vec4 shadowValues;",
  9501. "shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  9502. "shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  9503. "shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  9504. "shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  9505. "shadow = dot( shadowValues, vec4( 1.0 ) );",
  9506. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  9507. "#else",
  9508. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  9509. "float fDepth = unpackDepth( rgbaDepth );",
  9510. "if ( fDepth < shadowCoord.z )",
  9511. // spot with multiple shadows is darker
  9512. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  9513. // spot with multiple shadows has the same color as single shadow spot
  9514. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  9515. "#endif",
  9516. "}",
  9517. "#ifdef SHADOWMAP_DEBUG",
  9518. "#ifdef SHADOWMAP_CASCADE",
  9519. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  9520. "#else",
  9521. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  9522. "#endif",
  9523. "#endif",
  9524. "}",
  9525. "#ifdef GAMMA_OUTPUT",
  9526. "shadowColor *= shadowColor;",
  9527. "#endif",
  9528. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  9529. "#endif"
  9530. ].join("\n"),
  9531. shadowmap_pars_vertex: [
  9532. "#ifdef USE_SHADOWMAP",
  9533. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  9534. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  9535. "#endif"
  9536. ].join("\n"),
  9537. shadowmap_vertex: [
  9538. "#ifdef USE_SHADOWMAP",
  9539. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  9540. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  9541. "}",
  9542. "#endif"
  9543. ].join("\n"),
  9544. // ALPHATEST
  9545. alphatest_fragment: [
  9546. "#ifdef ALPHATEST",
  9547. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  9548. "#endif"
  9549. ].join("\n"),
  9550. // LINEAR SPACE
  9551. linear_to_gamma_fragment: [
  9552. "#ifdef GAMMA_OUTPUT",
  9553. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  9554. "#endif"
  9555. ].join("\n")
  9556. };
  9557. THREE.UniformsUtils = {
  9558. merge: function ( uniforms ) {
  9559. var u, p, tmp, merged = {};
  9560. for ( u = 0; u < uniforms.length; u ++ ) {
  9561. tmp = this.clone( uniforms[ u ] );
  9562. for ( p in tmp ) {
  9563. merged[ p ] = tmp[ p ];
  9564. }
  9565. }
  9566. return merged;
  9567. },
  9568. clone: function ( uniforms_src ) {
  9569. var u, p, parameter, parameter_src, uniforms_dst = {};
  9570. for ( u in uniforms_src ) {
  9571. uniforms_dst[ u ] = {};
  9572. for ( p in uniforms_src[ u ] ) {
  9573. parameter_src = uniforms_src[ u ][ p ];
  9574. if ( parameter_src instanceof THREE.Color ||
  9575. parameter_src instanceof THREE.Vector2 ||
  9576. parameter_src instanceof THREE.Vector3 ||
  9577. parameter_src instanceof THREE.Vector4 ||
  9578. parameter_src instanceof THREE.Matrix4 ||
  9579. parameter_src instanceof THREE.Texture ) {
  9580. uniforms_dst[ u ][ p ] = parameter_src.clone();
  9581. } else if ( parameter_src instanceof Array ) {
  9582. uniforms_dst[ u ][ p ] = parameter_src.slice();
  9583. } else {
  9584. uniforms_dst[ u ][ p ] = parameter_src;
  9585. }
  9586. }
  9587. }
  9588. return uniforms_dst;
  9589. }
  9590. };
  9591. THREE.UniformsLib = {
  9592. common: {
  9593. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9594. "opacity" : { type: "f", value: 1.0 },
  9595. "map" : { type: "t", value: null },
  9596. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  9597. "lightMap" : { type: "t", value: null },
  9598. "specularMap" : { type: "t", value: null },
  9599. "envMap" : { type: "t", value: null },
  9600. "flipEnvMap" : { type: "f", value: -1 },
  9601. "useRefract" : { type: "i", value: 0 },
  9602. "reflectivity" : { type: "f", value: 1.0 },
  9603. "refractionRatio" : { type: "f", value: 0.98 },
  9604. "combine" : { type: "i", value: 0 },
  9605. "morphTargetInfluences" : { type: "f", value: 0 }
  9606. },
  9607. bump: {
  9608. "bumpMap" : { type: "t", value: null },
  9609. "bumpScale" : { type: "f", value: 1 }
  9610. },
  9611. normalmap: {
  9612. "normalMap" : { type: "t", value: null },
  9613. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  9614. },
  9615. fog : {
  9616. "fogDensity" : { type: "f", value: 0.00025 },
  9617. "fogNear" : { type: "f", value: 1 },
  9618. "fogFar" : { type: "f", value: 2000 },
  9619. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9620. },
  9621. lights: {
  9622. "ambientLightColor" : { type: "fv", value: [] },
  9623. "directionalLightDirection" : { type: "fv", value: [] },
  9624. "directionalLightColor" : { type: "fv", value: [] },
  9625. "hemisphereLightDirection" : { type: "fv", value: [] },
  9626. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  9627. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  9628. "pointLightColor" : { type: "fv", value: [] },
  9629. "pointLightPosition" : { type: "fv", value: [] },
  9630. "pointLightDistance" : { type: "fv1", value: [] },
  9631. "spotLightColor" : { type: "fv", value: [] },
  9632. "spotLightPosition" : { type: "fv", value: [] },
  9633. "spotLightDirection" : { type: "fv", value: [] },
  9634. "spotLightDistance" : { type: "fv1", value: [] },
  9635. "spotLightAngleCos" : { type: "fv1", value: [] },
  9636. "spotLightExponent" : { type: "fv1", value: [] }
  9637. },
  9638. particle: {
  9639. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9640. "opacity" : { type: "f", value: 1.0 },
  9641. "size" : { type: "f", value: 1.0 },
  9642. "scale" : { type: "f", value: 1.0 },
  9643. "map" : { type: "t", value: null },
  9644. "fogDensity" : { type: "f", value: 0.00025 },
  9645. "fogNear" : { type: "f", value: 1 },
  9646. "fogFar" : { type: "f", value: 2000 },
  9647. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9648. },
  9649. shadowmap: {
  9650. "shadowMap": { type: "tv", value: [] },
  9651. "shadowMapSize": { type: "v2v", value: [] },
  9652. "shadowBias" : { type: "fv1", value: [] },
  9653. "shadowDarkness": { type: "fv1", value: [] },
  9654. "shadowMatrix" : { type: "m4v", value: [] }
  9655. }
  9656. };
  9657. THREE.ShaderLib = {
  9658. 'depth': {
  9659. uniforms: {
  9660. "mNear": { type: "f", value: 1.0 },
  9661. "mFar" : { type: "f", value: 2000.0 },
  9662. "opacity" : { type: "f", value: 1.0 }
  9663. },
  9664. vertexShader: [
  9665. "void main() {",
  9666. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  9667. "}"
  9668. ].join("\n"),
  9669. fragmentShader: [
  9670. "uniform float mNear;",
  9671. "uniform float mFar;",
  9672. "uniform float opacity;",
  9673. "void main() {",
  9674. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  9675. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  9676. "gl_FragColor = vec4( vec3( color ), opacity );",
  9677. "}"
  9678. ].join("\n")
  9679. },
  9680. 'normal': {
  9681. uniforms: {
  9682. "opacity" : { type: "f", value: 1.0 }
  9683. },
  9684. vertexShader: [
  9685. "varying vec3 vNormal;",
  9686. "void main() {",
  9687. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9688. "vNormal = normalize( normalMatrix * normal );",
  9689. "gl_Position = projectionMatrix * mvPosition;",
  9690. "}"
  9691. ].join("\n"),
  9692. fragmentShader: [
  9693. "uniform float opacity;",
  9694. "varying vec3 vNormal;",
  9695. "void main() {",
  9696. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  9697. "}"
  9698. ].join("\n")
  9699. },
  9700. 'basic': {
  9701. uniforms: THREE.UniformsUtils.merge( [
  9702. THREE.UniformsLib[ "common" ],
  9703. THREE.UniformsLib[ "fog" ],
  9704. THREE.UniformsLib[ "shadowmap" ]
  9705. ] ),
  9706. vertexShader: [
  9707. THREE.ShaderChunk[ "map_pars_vertex" ],
  9708. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9709. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9710. THREE.ShaderChunk[ "color_pars_vertex" ],
  9711. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9712. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9713. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9714. "void main() {",
  9715. THREE.ShaderChunk[ "map_vertex" ],
  9716. THREE.ShaderChunk[ "lightmap_vertex" ],
  9717. THREE.ShaderChunk[ "color_vertex" ],
  9718. THREE.ShaderChunk[ "skinbase_vertex" ],
  9719. "#ifdef USE_ENVMAP",
  9720. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9721. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9722. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9723. "#endif",
  9724. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9725. THREE.ShaderChunk[ "skinning_vertex" ],
  9726. THREE.ShaderChunk[ "default_vertex" ],
  9727. THREE.ShaderChunk[ "worldpos_vertex" ],
  9728. THREE.ShaderChunk[ "envmap_vertex" ],
  9729. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9730. "}"
  9731. ].join("\n"),
  9732. fragmentShader: [
  9733. "uniform vec3 diffuse;",
  9734. "uniform float opacity;",
  9735. THREE.ShaderChunk[ "color_pars_fragment" ],
  9736. THREE.ShaderChunk[ "map_pars_fragment" ],
  9737. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9738. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9739. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9740. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9741. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9742. "void main() {",
  9743. "gl_FragColor = vec4( diffuse, opacity );",
  9744. THREE.ShaderChunk[ "map_fragment" ],
  9745. THREE.ShaderChunk[ "alphatest_fragment" ],
  9746. THREE.ShaderChunk[ "specularmap_fragment" ],
  9747. THREE.ShaderChunk[ "lightmap_fragment" ],
  9748. THREE.ShaderChunk[ "color_fragment" ],
  9749. THREE.ShaderChunk[ "envmap_fragment" ],
  9750. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9751. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9752. THREE.ShaderChunk[ "fog_fragment" ],
  9753. "}"
  9754. ].join("\n")
  9755. },
  9756. 'lambert': {
  9757. uniforms: THREE.UniformsUtils.merge( [
  9758. THREE.UniformsLib[ "common" ],
  9759. THREE.UniformsLib[ "fog" ],
  9760. THREE.UniformsLib[ "lights" ],
  9761. THREE.UniformsLib[ "shadowmap" ],
  9762. {
  9763. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9764. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9765. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9766. }
  9767. ] ),
  9768. vertexShader: [
  9769. "#define LAMBERT",
  9770. "varying vec3 vLightFront;",
  9771. "#ifdef DOUBLE_SIDED",
  9772. "varying vec3 vLightBack;",
  9773. "#endif",
  9774. THREE.ShaderChunk[ "map_pars_vertex" ],
  9775. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9776. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9777. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  9778. THREE.ShaderChunk[ "color_pars_vertex" ],
  9779. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9780. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9781. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9782. "void main() {",
  9783. THREE.ShaderChunk[ "map_vertex" ],
  9784. THREE.ShaderChunk[ "lightmap_vertex" ],
  9785. THREE.ShaderChunk[ "color_vertex" ],
  9786. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9787. THREE.ShaderChunk[ "skinbase_vertex" ],
  9788. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9789. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9790. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9791. THREE.ShaderChunk[ "skinning_vertex" ],
  9792. THREE.ShaderChunk[ "default_vertex" ],
  9793. THREE.ShaderChunk[ "worldpos_vertex" ],
  9794. THREE.ShaderChunk[ "envmap_vertex" ],
  9795. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  9796. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9797. "}"
  9798. ].join("\n"),
  9799. fragmentShader: [
  9800. "uniform float opacity;",
  9801. "varying vec3 vLightFront;",
  9802. "#ifdef DOUBLE_SIDED",
  9803. "varying vec3 vLightBack;",
  9804. "#endif",
  9805. THREE.ShaderChunk[ "color_pars_fragment" ],
  9806. THREE.ShaderChunk[ "map_pars_fragment" ],
  9807. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9808. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9809. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9810. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9811. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9812. "void main() {",
  9813. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  9814. THREE.ShaderChunk[ "map_fragment" ],
  9815. THREE.ShaderChunk[ "alphatest_fragment" ],
  9816. THREE.ShaderChunk[ "specularmap_fragment" ],
  9817. "#ifdef DOUBLE_SIDED",
  9818. //"float isFront = float( gl_FrontFacing );",
  9819. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  9820. "if ( gl_FrontFacing )",
  9821. "gl_FragColor.xyz *= vLightFront;",
  9822. "else",
  9823. "gl_FragColor.xyz *= vLightBack;",
  9824. "#else",
  9825. "gl_FragColor.xyz *= vLightFront;",
  9826. "#endif",
  9827. THREE.ShaderChunk[ "lightmap_fragment" ],
  9828. THREE.ShaderChunk[ "color_fragment" ],
  9829. THREE.ShaderChunk[ "envmap_fragment" ],
  9830. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9831. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9832. THREE.ShaderChunk[ "fog_fragment" ],
  9833. "}"
  9834. ].join("\n")
  9835. },
  9836. 'phong': {
  9837. uniforms: THREE.UniformsUtils.merge( [
  9838. THREE.UniformsLib[ "common" ],
  9839. THREE.UniformsLib[ "bump" ],
  9840. THREE.UniformsLib[ "normalmap" ],
  9841. THREE.UniformsLib[ "fog" ],
  9842. THREE.UniformsLib[ "lights" ],
  9843. THREE.UniformsLib[ "shadowmap" ],
  9844. {
  9845. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9846. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9847. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  9848. "shininess": { type: "f", value: 30 },
  9849. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9850. }
  9851. ] ),
  9852. vertexShader: [
  9853. "#define PHONG",
  9854. "varying vec3 vViewPosition;",
  9855. "varying vec3 vNormal;",
  9856. THREE.ShaderChunk[ "map_pars_vertex" ],
  9857. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9858. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9859. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  9860. THREE.ShaderChunk[ "color_pars_vertex" ],
  9861. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9862. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9863. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9864. "void main() {",
  9865. THREE.ShaderChunk[ "map_vertex" ],
  9866. THREE.ShaderChunk[ "lightmap_vertex" ],
  9867. THREE.ShaderChunk[ "color_vertex" ],
  9868. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9869. THREE.ShaderChunk[ "skinbase_vertex" ],
  9870. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9871. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9872. "vNormal = normalize( transformedNormal );",
  9873. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9874. THREE.ShaderChunk[ "skinning_vertex" ],
  9875. THREE.ShaderChunk[ "default_vertex" ],
  9876. "vViewPosition = -mvPosition.xyz;",
  9877. THREE.ShaderChunk[ "worldpos_vertex" ],
  9878. THREE.ShaderChunk[ "envmap_vertex" ],
  9879. THREE.ShaderChunk[ "lights_phong_vertex" ],
  9880. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9881. "}"
  9882. ].join("\n"),
  9883. fragmentShader: [
  9884. "uniform vec3 diffuse;",
  9885. "uniform float opacity;",
  9886. "uniform vec3 ambient;",
  9887. "uniform vec3 emissive;",
  9888. "uniform vec3 specular;",
  9889. "uniform float shininess;",
  9890. THREE.ShaderChunk[ "color_pars_fragment" ],
  9891. THREE.ShaderChunk[ "map_pars_fragment" ],
  9892. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9893. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9894. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9895. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  9896. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9897. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  9898. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  9899. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9900. "void main() {",
  9901. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  9902. THREE.ShaderChunk[ "map_fragment" ],
  9903. THREE.ShaderChunk[ "alphatest_fragment" ],
  9904. THREE.ShaderChunk[ "specularmap_fragment" ],
  9905. THREE.ShaderChunk[ "lights_phong_fragment" ],
  9906. THREE.ShaderChunk[ "lightmap_fragment" ],
  9907. THREE.ShaderChunk[ "color_fragment" ],
  9908. THREE.ShaderChunk[ "envmap_fragment" ],
  9909. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9910. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9911. THREE.ShaderChunk[ "fog_fragment" ],
  9912. "}"
  9913. ].join("\n")
  9914. },
  9915. 'particle_basic': {
  9916. uniforms: THREE.UniformsUtils.merge( [
  9917. THREE.UniformsLib[ "particle" ],
  9918. THREE.UniformsLib[ "shadowmap" ]
  9919. ] ),
  9920. vertexShader: [
  9921. "uniform float size;",
  9922. "uniform float scale;",
  9923. THREE.ShaderChunk[ "color_pars_vertex" ],
  9924. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9925. "void main() {",
  9926. THREE.ShaderChunk[ "color_vertex" ],
  9927. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9928. "#ifdef USE_SIZEATTENUATION",
  9929. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  9930. "#else",
  9931. "gl_PointSize = size;",
  9932. "#endif",
  9933. "gl_Position = projectionMatrix * mvPosition;",
  9934. THREE.ShaderChunk[ "worldpos_vertex" ],
  9935. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9936. "}"
  9937. ].join("\n"),
  9938. fragmentShader: [
  9939. "uniform vec3 psColor;",
  9940. "uniform float opacity;",
  9941. THREE.ShaderChunk[ "color_pars_fragment" ],
  9942. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  9943. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9944. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9945. "void main() {",
  9946. "gl_FragColor = vec4( psColor, opacity );",
  9947. THREE.ShaderChunk[ "map_particle_fragment" ],
  9948. THREE.ShaderChunk[ "alphatest_fragment" ],
  9949. THREE.ShaderChunk[ "color_fragment" ],
  9950. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9951. THREE.ShaderChunk[ "fog_fragment" ],
  9952. "}"
  9953. ].join("\n")
  9954. },
  9955. 'dashed': {
  9956. uniforms: THREE.UniformsUtils.merge( [
  9957. THREE.UniformsLib[ "common" ],
  9958. THREE.UniformsLib[ "fog" ],
  9959. {
  9960. "scale": { type: "f", value: 1 },
  9961. "dashSize": { type: "f", value: 1 },
  9962. "totalSize": { type: "f", value: 2 }
  9963. }
  9964. ] ),
  9965. vertexShader: [
  9966. "uniform float scale;",
  9967. "attribute float lineDistance;",
  9968. "varying float vLineDistance;",
  9969. THREE.ShaderChunk[ "color_pars_vertex" ],
  9970. "void main() {",
  9971. THREE.ShaderChunk[ "color_vertex" ],
  9972. "vLineDistance = scale * lineDistance;",
  9973. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9974. "gl_Position = projectionMatrix * mvPosition;",
  9975. "}"
  9976. ].join("\n"),
  9977. fragmentShader: [
  9978. "uniform vec3 diffuse;",
  9979. "uniform float opacity;",
  9980. "uniform float dashSize;",
  9981. "uniform float totalSize;",
  9982. "varying float vLineDistance;",
  9983. THREE.ShaderChunk[ "color_pars_fragment" ],
  9984. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9985. "void main() {",
  9986. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  9987. "discard;",
  9988. "}",
  9989. "gl_FragColor = vec4( diffuse, opacity );",
  9990. THREE.ShaderChunk[ "color_fragment" ],
  9991. THREE.ShaderChunk[ "fog_fragment" ],
  9992. "}"
  9993. ].join("\n")
  9994. },
  9995. // Depth encoding into RGBA texture
  9996. // based on SpiderGL shadow map example
  9997. // http://spidergl.org/example.php?id=6
  9998. // originally from
  9999. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  10000. // see also here:
  10001. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  10002. 'depthRGBA': {
  10003. uniforms: {},
  10004. vertexShader: [
  10005. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10006. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10007. "void main() {",
  10008. THREE.ShaderChunk[ "skinbase_vertex" ],
  10009. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10010. THREE.ShaderChunk[ "skinning_vertex" ],
  10011. THREE.ShaderChunk[ "default_vertex" ],
  10012. "}"
  10013. ].join("\n"),
  10014. fragmentShader: [
  10015. "vec4 pack_depth( const in float depth ) {",
  10016. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  10017. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  10018. "vec4 res = fract( depth * bit_shift );",
  10019. "res -= res.xxyz * bit_mask;",
  10020. "return res;",
  10021. "}",
  10022. "void main() {",
  10023. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  10024. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  10025. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  10026. //"gl_FragData[ 0 ] = pack_depth( z );",
  10027. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  10028. "}"
  10029. ].join("\n")
  10030. }
  10031. };
  10032. /**
  10033. * @author supereggbert / http://www.paulbrunt.co.uk/
  10034. * @author mrdoob / http://mrdoob.com/
  10035. * @author alteredq / http://alteredqualia.com/
  10036. * @author szimek / https://github.com/szimek/
  10037. */
  10038. THREE.WebGLRenderer = function ( parameters ) {
  10039. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  10040. parameters = parameters || {};
  10041. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  10042. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  10043. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  10044. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  10045. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  10046. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  10047. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  10048. _clearColor = parameters.clearColor !== undefined ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ),
  10049. _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0;
  10050. // public properties
  10051. this.domElement = _canvas;
  10052. this.context = null;
  10053. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  10054. ? parameters.devicePixelRatio
  10055. : window.devicePixelRatio !== undefined
  10056. ? window.devicePixelRatio
  10057. : 1;
  10058. // clearing
  10059. this.autoClear = true;
  10060. this.autoClearColor = true;
  10061. this.autoClearDepth = true;
  10062. this.autoClearStencil = true;
  10063. // scene graph
  10064. this.sortObjects = true;
  10065. this.autoUpdateObjects = true;
  10066. this.autoUpdateScene = true;
  10067. // physically based shading
  10068. this.gammaInput = false;
  10069. this.gammaOutput = false;
  10070. this.physicallyBasedShading = false;
  10071. // shadow map
  10072. this.shadowMapEnabled = false;
  10073. this.shadowMapAutoUpdate = true;
  10074. this.shadowMapType = THREE.PCFShadowMap;
  10075. this.shadowMapCullFace = THREE.CullFaceFront;
  10076. this.shadowMapDebug = false;
  10077. this.shadowMapCascade = false;
  10078. // morphs
  10079. this.maxMorphTargets = 8;
  10080. this.maxMorphNormals = 4;
  10081. // flags
  10082. this.autoScaleCubemaps = true;
  10083. // custom render plugins
  10084. this.renderPluginsPre = [];
  10085. this.renderPluginsPost = [];
  10086. // info
  10087. this.info = {
  10088. memory: {
  10089. programs: 0,
  10090. geometries: 0,
  10091. textures: 0
  10092. },
  10093. render: {
  10094. calls: 0,
  10095. vertices: 0,
  10096. faces: 0,
  10097. points: 0
  10098. }
  10099. };
  10100. // internal properties
  10101. var _this = this,
  10102. _programs = [],
  10103. _programs_counter = 0,
  10104. // internal state cache
  10105. _currentProgram = null,
  10106. _currentFramebuffer = null,
  10107. _currentMaterialId = -1,
  10108. _currentGeometryGroupHash = null,
  10109. _currentCamera = null,
  10110. _geometryGroupCounter = 0,
  10111. _usedTextureUnits = 0,
  10112. // GL state cache
  10113. _oldDoubleSided = -1,
  10114. _oldFlipSided = -1,
  10115. _oldBlending = -1,
  10116. _oldBlendEquation = -1,
  10117. _oldBlendSrc = -1,
  10118. _oldBlendDst = -1,
  10119. _oldDepthTest = -1,
  10120. _oldDepthWrite = -1,
  10121. _oldPolygonOffset = null,
  10122. _oldPolygonOffsetFactor = null,
  10123. _oldPolygonOffsetUnits = null,
  10124. _oldLineWidth = null,
  10125. _viewportX = 0,
  10126. _viewportY = 0,
  10127. _viewportWidth = 0,
  10128. _viewportHeight = 0,
  10129. _currentWidth = 0,
  10130. _currentHeight = 0,
  10131. _enabledAttributes = {},
  10132. // frustum
  10133. _frustum = new THREE.Frustum(),
  10134. // camera matrices cache
  10135. _projScreenMatrix = new THREE.Matrix4(),
  10136. _projScreenMatrixPS = new THREE.Matrix4(),
  10137. _vector3 = new THREE.Vector3(),
  10138. // light arrays cache
  10139. _direction = new THREE.Vector3(),
  10140. _lightsNeedUpdate = true,
  10141. _lights = {
  10142. ambient: [ 0, 0, 0 ],
  10143. directional: { length: 0, colors: new Array(), positions: new Array() },
  10144. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  10145. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  10146. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  10147. };
  10148. // initialize
  10149. var _gl;
  10150. var _glExtensionTextureFloat;
  10151. var _glExtensionStandardDerivatives;
  10152. var _glExtensionTextureFilterAnisotropic;
  10153. var _glExtensionCompressedTextureS3TC;
  10154. initGL();
  10155. setDefaultGLState();
  10156. this.context = _gl;
  10157. // GPU capabilities
  10158. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  10159. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  10160. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  10161. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  10162. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  10163. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  10164. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  10165. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  10166. //
  10167. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  10168. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  10169. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  10170. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  10171. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  10172. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  10173. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  10174. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  10175. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  10176. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  10177. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  10178. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  10179. // clamp precision to maximum available
  10180. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  10181. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  10182. if ( _precision === "highp" && ! highpAvailable ) {
  10183. if ( mediumpAvailable ) {
  10184. _precision = "mediump";
  10185. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  10186. } else {
  10187. _precision = "lowp";
  10188. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  10189. }
  10190. }
  10191. if ( _precision === "mediump" && ! mediumpAvailable ) {
  10192. _precision = "lowp";
  10193. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  10194. }
  10195. // API
  10196. this.getContext = function () {
  10197. return _gl;
  10198. };
  10199. this.supportsVertexTextures = function () {
  10200. return _supportsVertexTextures;
  10201. };
  10202. this.supportsFloatTextures = function () {
  10203. return _glExtensionTextureFloat;
  10204. };
  10205. this.supportsStandardDerivatives = function () {
  10206. return _glExtensionStandardDerivatives;
  10207. };
  10208. this.supportsCompressedTextureS3TC = function () {
  10209. return _glExtensionCompressedTextureS3TC;
  10210. };
  10211. this.getMaxAnisotropy = function () {
  10212. return _maxAnisotropy;
  10213. };
  10214. this.getPrecision = function () {
  10215. return _precision;
  10216. };
  10217. this.setSize = function ( width, height ) {
  10218. _canvas.width = width * this.devicePixelRatio;
  10219. _canvas.height = height * this.devicePixelRatio;
  10220. _canvas.style.width = width + 'px';
  10221. _canvas.style.height = height + 'px';
  10222. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  10223. };
  10224. this.setViewport = function ( x, y, width, height ) {
  10225. _viewportX = x !== undefined ? x : 0;
  10226. _viewportY = y !== undefined ? y : 0;
  10227. _viewportWidth = width !== undefined ? width : _canvas.width;
  10228. _viewportHeight = height !== undefined ? height : _canvas.height;
  10229. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  10230. };
  10231. this.setScissor = function ( x, y, width, height ) {
  10232. _gl.scissor( x, y, width, height );
  10233. };
  10234. this.enableScissorTest = function ( enable ) {
  10235. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  10236. };
  10237. // Clearing
  10238. this.setClearColorHex = function ( hex, alpha ) {
  10239. _clearColor.setHex( hex );
  10240. _clearAlpha = alpha;
  10241. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  10242. };
  10243. this.setClearColor = function ( color, alpha ) {
  10244. _clearColor.copy( color );
  10245. _clearAlpha = alpha;
  10246. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  10247. };
  10248. this.getClearColor = function () {
  10249. return _clearColor;
  10250. };
  10251. this.getClearAlpha = function () {
  10252. return _clearAlpha;
  10253. };
  10254. this.clear = function ( color, depth, stencil ) {
  10255. var bits = 0;
  10256. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  10257. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  10258. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  10259. _gl.clear( bits );
  10260. };
  10261. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  10262. this.setRenderTarget( renderTarget );
  10263. this.clear( color, depth, stencil );
  10264. };
  10265. // Plugins
  10266. this.addPostPlugin = function ( plugin ) {
  10267. plugin.init( this );
  10268. this.renderPluginsPost.push( plugin );
  10269. };
  10270. this.addPrePlugin = function ( plugin ) {
  10271. plugin.init( this );
  10272. this.renderPluginsPre.push( plugin );
  10273. };
  10274. // Rendering
  10275. this.updateShadowMap = function ( scene, camera ) {
  10276. _currentProgram = null;
  10277. _oldBlending = -1;
  10278. _oldDepthTest = -1;
  10279. _oldDepthWrite = -1;
  10280. _currentGeometryGroupHash = -1;
  10281. _currentMaterialId = -1;
  10282. _lightsNeedUpdate = true;
  10283. _oldDoubleSided = -1;
  10284. _oldFlipSided = -1;
  10285. this.shadowMapPlugin.update( scene, camera );
  10286. };
  10287. // Internal functions
  10288. // Buffer allocation
  10289. function createParticleBuffers ( geometry ) {
  10290. geometry.__webglVertexBuffer = _gl.createBuffer();
  10291. geometry.__webglColorBuffer = _gl.createBuffer();
  10292. _this.info.memory.geometries ++;
  10293. };
  10294. function createLineBuffers ( geometry ) {
  10295. geometry.__webglVertexBuffer = _gl.createBuffer();
  10296. geometry.__webglColorBuffer = _gl.createBuffer();
  10297. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  10298. _this.info.memory.geometries ++;
  10299. };
  10300. function createRibbonBuffers ( geometry ) {
  10301. geometry.__webglVertexBuffer = _gl.createBuffer();
  10302. geometry.__webglColorBuffer = _gl.createBuffer();
  10303. geometry.__webglNormalBuffer = _gl.createBuffer();
  10304. _this.info.memory.geometries ++;
  10305. };
  10306. function createMeshBuffers ( geometryGroup ) {
  10307. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  10308. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  10309. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  10310. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  10311. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  10312. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  10313. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  10314. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  10315. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  10316. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  10317. var m, ml;
  10318. if ( geometryGroup.numMorphTargets ) {
  10319. geometryGroup.__webglMorphTargetsBuffers = [];
  10320. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10321. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  10322. }
  10323. }
  10324. if ( geometryGroup.numMorphNormals ) {
  10325. geometryGroup.__webglMorphNormalsBuffers = [];
  10326. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10327. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  10328. }
  10329. }
  10330. _this.info.memory.geometries ++;
  10331. };
  10332. // Events
  10333. var onGeometryDispose = function ( event ) {
  10334. var geometry = event.target;
  10335. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10336. deallocateGeometry( geometry );
  10337. _this.info.memory.geometries --;
  10338. };
  10339. var onTextureDispose = function ( event ) {
  10340. var texture = event.target;
  10341. texture.removeEventListener( 'dispose', onTextureDispose );
  10342. deallocateTexture( texture );
  10343. _this.info.memory.textures --;
  10344. };
  10345. var onRenderTargetDispose = function ( event ) {
  10346. var renderTarget = event.target;
  10347. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  10348. deallocateRenderTarget( renderTarget );
  10349. _this.info.memory.textures --;
  10350. };
  10351. var onMaterialDispose = function ( event ) {
  10352. var material = event.target;
  10353. material.removeEventListener( 'dispose', onMaterialDispose );
  10354. deallocateMaterial( material );
  10355. };
  10356. // Buffer deallocation
  10357. var deallocateGeometry = function ( geometry ) {
  10358. geometry.__webglInit = undefined;
  10359. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10360. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  10361. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  10362. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  10363. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  10364. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  10365. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  10366. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  10367. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  10368. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  10369. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  10370. // geometry groups
  10371. if ( geometry.geometryGroups !== undefined ) {
  10372. for ( var g in geometry.geometryGroups ) {
  10373. var geometryGroup = geometry.geometryGroups[ g ];
  10374. if ( geometryGroup.numMorphTargets !== undefined ) {
  10375. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10376. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  10377. }
  10378. }
  10379. if ( geometryGroup.numMorphNormals !== undefined ) {
  10380. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10381. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  10382. }
  10383. }
  10384. deleteCustomAttributesBuffers( geometryGroup );
  10385. }
  10386. }
  10387. deleteCustomAttributesBuffers( geometry );
  10388. };
  10389. var deallocateTexture = function ( texture ) {
  10390. if ( texture.image && texture.image.__webglTextureCube ) {
  10391. // cube texture
  10392. _gl.deleteTexture( texture.image.__webglTextureCube );
  10393. } else {
  10394. // 2D texture
  10395. if ( ! texture.__webglInit ) return;
  10396. texture.__webglInit = false;
  10397. _gl.deleteTexture( texture.__webglTexture );
  10398. }
  10399. };
  10400. var deallocateRenderTarget = function ( renderTarget ) {
  10401. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  10402. _gl.deleteTexture( renderTarget.__webglTexture );
  10403. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  10404. for ( var i = 0; i < 6; i ++ ) {
  10405. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  10406. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  10407. }
  10408. } else {
  10409. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  10410. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  10411. }
  10412. };
  10413. var deallocateMaterial = function ( material ) {
  10414. var program = material.program;
  10415. if ( program === undefined ) return;
  10416. material.program = undefined;
  10417. // only deallocate GL program if this was the last use of shared program
  10418. // assumed there is only single copy of any program in the _programs list
  10419. // (that's how it's constructed)
  10420. var i, il, programInfo;
  10421. var deleteProgram = false;
  10422. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  10423. programInfo = _programs[ i ];
  10424. if ( programInfo.program === program ) {
  10425. programInfo.usedTimes --;
  10426. if ( programInfo.usedTimes === 0 ) {
  10427. deleteProgram = true;
  10428. }
  10429. break;
  10430. }
  10431. }
  10432. if ( deleteProgram === true ) {
  10433. // avoid using array.splice, this is costlier than creating new array from scratch
  10434. var newPrograms = [];
  10435. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  10436. programInfo = _programs[ i ];
  10437. if ( programInfo.program !== program ) {
  10438. newPrograms.push( programInfo );
  10439. }
  10440. }
  10441. _programs = newPrograms;
  10442. _gl.deleteProgram( program );
  10443. _this.info.memory.programs --;
  10444. }
  10445. };
  10446. //
  10447. /*
  10448. function deleteParticleBuffers ( geometry ) {
  10449. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10450. _gl.deleteBuffer( geometry.__webglColorBuffer );
  10451. deleteCustomAttributesBuffers( geometry );
  10452. _this.info.memory.geometries --;
  10453. };
  10454. function deleteLineBuffers ( geometry ) {
  10455. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10456. _gl.deleteBuffer( geometry.__webglColorBuffer );
  10457. _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  10458. deleteCustomAttributesBuffers( geometry );
  10459. _this.info.memory.geometries --;
  10460. };
  10461. function deleteRibbonBuffers ( geometry ) {
  10462. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10463. _gl.deleteBuffer( geometry.__webglColorBuffer );
  10464. _gl.deleteBuffer( geometry.__webglNormalBuffer );
  10465. deleteCustomAttributesBuffers( geometry );
  10466. _this.info.memory.geometries --;
  10467. };
  10468. function deleteMeshBuffers ( geometryGroup ) {
  10469. _gl.deleteBuffer( geometryGroup.__webglVertexBuffer );
  10470. _gl.deleteBuffer( geometryGroup.__webglNormalBuffer );
  10471. _gl.deleteBuffer( geometryGroup.__webglTangentBuffer );
  10472. _gl.deleteBuffer( geometryGroup.__webglColorBuffer );
  10473. _gl.deleteBuffer( geometryGroup.__webglUVBuffer );
  10474. _gl.deleteBuffer( geometryGroup.__webglUV2Buffer );
  10475. _gl.deleteBuffer( geometryGroup.__webglSkinIndicesBuffer );
  10476. _gl.deleteBuffer( geometryGroup.__webglSkinWeightsBuffer );
  10477. _gl.deleteBuffer( geometryGroup.__webglFaceBuffer );
  10478. _gl.deleteBuffer( geometryGroup.__webglLineBuffer );
  10479. var m, ml;
  10480. if ( geometryGroup.numMorphTargets ) {
  10481. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10482. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  10483. }
  10484. }
  10485. if ( geometryGroup.numMorphNormals ) {
  10486. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10487. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  10488. }
  10489. }
  10490. deleteCustomAttributesBuffers( geometryGroup );
  10491. _this.info.memory.geometries --;
  10492. };
  10493. */
  10494. function deleteCustomAttributesBuffers( geometry ) {
  10495. if ( geometry.__webglCustomAttributesList ) {
  10496. for ( var id in geometry.__webglCustomAttributesList ) {
  10497. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  10498. }
  10499. }
  10500. };
  10501. // Buffer initialization
  10502. function initCustomAttributes ( geometry, object ) {
  10503. var nvertices = geometry.vertices.length;
  10504. var material = object.material;
  10505. if ( material.attributes ) {
  10506. if ( geometry.__webglCustomAttributesList === undefined ) {
  10507. geometry.__webglCustomAttributesList = [];
  10508. }
  10509. for ( var a in material.attributes ) {
  10510. var attribute = material.attributes[ a ];
  10511. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  10512. attribute.__webglInitialized = true;
  10513. var size = 1; // "f" and "i"
  10514. if ( attribute.type === "v2" ) size = 2;
  10515. else if ( attribute.type === "v3" ) size = 3;
  10516. else if ( attribute.type === "v4" ) size = 4;
  10517. else if ( attribute.type === "c" ) size = 3;
  10518. attribute.size = size;
  10519. attribute.array = new Float32Array( nvertices * size );
  10520. attribute.buffer = _gl.createBuffer();
  10521. attribute.buffer.belongsToAttribute = a;
  10522. attribute.needsUpdate = true;
  10523. }
  10524. geometry.__webglCustomAttributesList.push( attribute );
  10525. }
  10526. }
  10527. };
  10528. function initParticleBuffers ( geometry, object ) {
  10529. var nvertices = geometry.vertices.length;
  10530. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  10531. geometry.__colorArray = new Float32Array( nvertices * 3 );
  10532. geometry.__sortArray = [];
  10533. geometry.__webglParticleCount = nvertices;
  10534. initCustomAttributes ( geometry, object );
  10535. };
  10536. function initLineBuffers ( geometry, object ) {
  10537. var nvertices = geometry.vertices.length;
  10538. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  10539. geometry.__colorArray = new Float32Array( nvertices * 3 );
  10540. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  10541. geometry.__webglLineCount = nvertices;
  10542. initCustomAttributes ( geometry, object );
  10543. };
  10544. function initRibbonBuffers ( geometry, object ) {
  10545. var nvertices = geometry.vertices.length;
  10546. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  10547. geometry.__colorArray = new Float32Array( nvertices * 3 );
  10548. geometry.__normalArray = new Float32Array( nvertices * 3 );
  10549. geometry.__webglVertexCount = nvertices;
  10550. initCustomAttributes ( geometry, object );
  10551. };
  10552. function initMeshBuffers ( geometryGroup, object ) {
  10553. var geometry = object.geometry,
  10554. faces3 = geometryGroup.faces3,
  10555. faces4 = geometryGroup.faces4,
  10556. nvertices = faces3.length * 3 + faces4.length * 4,
  10557. ntris = faces3.length * 1 + faces4.length * 2,
  10558. nlines = faces3.length * 3 + faces4.length * 4,
  10559. material = getBufferMaterial( object, geometryGroup ),
  10560. uvType = bufferGuessUVType( material ),
  10561. normalType = bufferGuessNormalType( material ),
  10562. vertexColorType = bufferGuessVertexColorType( material );
  10563. //console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  10564. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  10565. if ( normalType ) {
  10566. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  10567. }
  10568. if ( geometry.hasTangents ) {
  10569. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  10570. }
  10571. if ( vertexColorType ) {
  10572. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  10573. }
  10574. if ( uvType ) {
  10575. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  10576. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  10577. }
  10578. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  10579. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  10580. }
  10581. }
  10582. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  10583. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  10584. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  10585. }
  10586. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  10587. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  10588. var m, ml;
  10589. if ( geometryGroup.numMorphTargets ) {
  10590. geometryGroup.__morphTargetsArrays = [];
  10591. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10592. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  10593. }
  10594. }
  10595. if ( geometryGroup.numMorphNormals ) {
  10596. geometryGroup.__morphNormalsArrays = [];
  10597. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10598. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  10599. }
  10600. }
  10601. geometryGroup.__webglFaceCount = ntris * 3;
  10602. geometryGroup.__webglLineCount = nlines * 2;
  10603. // custom attributes
  10604. if ( material.attributes ) {
  10605. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  10606. geometryGroup.__webglCustomAttributesList = [];
  10607. }
  10608. for ( var a in material.attributes ) {
  10609. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  10610. // attribute buffers which are correctly indexed in the setMeshBuffers function
  10611. var originalAttribute = material.attributes[ a ];
  10612. var attribute = {};
  10613. for ( var property in originalAttribute ) {
  10614. attribute[ property ] = originalAttribute[ property ];
  10615. }
  10616. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  10617. attribute.__webglInitialized = true;
  10618. var size = 1; // "f" and "i"
  10619. if( attribute.type === "v2" ) size = 2;
  10620. else if( attribute.type === "v3" ) size = 3;
  10621. else if( attribute.type === "v4" ) size = 4;
  10622. else if( attribute.type === "c" ) size = 3;
  10623. attribute.size = size;
  10624. attribute.array = new Float32Array( nvertices * size );
  10625. attribute.buffer = _gl.createBuffer();
  10626. attribute.buffer.belongsToAttribute = a;
  10627. originalAttribute.needsUpdate = true;
  10628. attribute.__original = originalAttribute;
  10629. }
  10630. geometryGroup.__webglCustomAttributesList.push( attribute );
  10631. }
  10632. }
  10633. geometryGroup.__inittedArrays = true;
  10634. };
  10635. function getBufferMaterial( object, geometryGroup ) {
  10636. return object.material instanceof THREE.MeshFaceMaterial
  10637. ? object.material.materials[ geometryGroup.materialIndex ]
  10638. : object.material;
  10639. };
  10640. function materialNeedsSmoothNormals ( material ) {
  10641. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  10642. };
  10643. function bufferGuessNormalType ( material ) {
  10644. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  10645. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  10646. return false;
  10647. }
  10648. if ( materialNeedsSmoothNormals( material ) ) {
  10649. return THREE.SmoothShading;
  10650. } else {
  10651. return THREE.FlatShading;
  10652. }
  10653. };
  10654. function bufferGuessVertexColorType ( material ) {
  10655. if ( material.vertexColors ) {
  10656. return material.vertexColors;
  10657. }
  10658. return false;
  10659. };
  10660. function bufferGuessUVType ( material ) {
  10661. // material must use some texture to require uvs
  10662. if ( material.map || material.lightMap || material.bumpMap || material.normalMap || material.specularMap || material instanceof THREE.ShaderMaterial ) {
  10663. return true;
  10664. }
  10665. return false;
  10666. };
  10667. //
  10668. function initDirectBuffers( geometry ) {
  10669. var a, attribute, type;
  10670. for ( a in geometry.attributes ) {
  10671. if ( a === "index" ) {
  10672. type = _gl.ELEMENT_ARRAY_BUFFER;
  10673. } else {
  10674. type = _gl.ARRAY_BUFFER;
  10675. }
  10676. attribute = geometry.attributes[ a ];
  10677. attribute.buffer = _gl.createBuffer();
  10678. _gl.bindBuffer( type, attribute.buffer );
  10679. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  10680. }
  10681. };
  10682. // Buffer setting
  10683. function setParticleBuffers ( geometry, hint, object ) {
  10684. var v, c, vertex, offset, index, color,
  10685. vertices = geometry.vertices,
  10686. vl = vertices.length,
  10687. colors = geometry.colors,
  10688. cl = colors.length,
  10689. vertexArray = geometry.__vertexArray,
  10690. colorArray = geometry.__colorArray,
  10691. sortArray = geometry.__sortArray,
  10692. dirtyVertices = geometry.verticesNeedUpdate,
  10693. dirtyElements = geometry.elementsNeedUpdate,
  10694. dirtyColors = geometry.colorsNeedUpdate,
  10695. customAttributes = geometry.__webglCustomAttributesList,
  10696. i, il,
  10697. a, ca, cal, value,
  10698. customAttribute;
  10699. if ( object.sortParticles ) {
  10700. _projScreenMatrixPS.copy( _projScreenMatrix );
  10701. _projScreenMatrixPS.multiply( object.matrixWorld );
  10702. for ( v = 0; v < vl; v ++ ) {
  10703. vertex = vertices[ v ];
  10704. _vector3.copy( vertex );
  10705. _vector3.applyMatrix4( _projScreenMatrixPS );
  10706. sortArray[ v ] = [ _vector3.z, v ];
  10707. }
  10708. sortArray.sort( numericalSort );
  10709. for ( v = 0; v < vl; v ++ ) {
  10710. vertex = vertices[ sortArray[v][1] ];
  10711. offset = v * 3;
  10712. vertexArray[ offset ] = vertex.x;
  10713. vertexArray[ offset + 1 ] = vertex.y;
  10714. vertexArray[ offset + 2 ] = vertex.z;
  10715. }
  10716. for ( c = 0; c < cl; c ++ ) {
  10717. offset = c * 3;
  10718. color = colors[ sortArray[c][1] ];
  10719. colorArray[ offset ] = color.r;
  10720. colorArray[ offset + 1 ] = color.g;
  10721. colorArray[ offset + 2 ] = color.b;
  10722. }
  10723. if ( customAttributes ) {
  10724. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10725. customAttribute = customAttributes[ i ];
  10726. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  10727. offset = 0;
  10728. cal = customAttribute.value.length;
  10729. if ( customAttribute.size === 1 ) {
  10730. for ( ca = 0; ca < cal; ca ++ ) {
  10731. index = sortArray[ ca ][ 1 ];
  10732. customAttribute.array[ ca ] = customAttribute.value[ index ];
  10733. }
  10734. } else if ( customAttribute.size === 2 ) {
  10735. for ( ca = 0; ca < cal; ca ++ ) {
  10736. index = sortArray[ ca ][ 1 ];
  10737. value = customAttribute.value[ index ];
  10738. customAttribute.array[ offset ] = value.x;
  10739. customAttribute.array[ offset + 1 ] = value.y;
  10740. offset += 2;
  10741. }
  10742. } else if ( customAttribute.size === 3 ) {
  10743. if ( customAttribute.type === "c" ) {
  10744. for ( ca = 0; ca < cal; ca ++ ) {
  10745. index = sortArray[ ca ][ 1 ];
  10746. value = customAttribute.value[ index ];
  10747. customAttribute.array[ offset ] = value.r;
  10748. customAttribute.array[ offset + 1 ] = value.g;
  10749. customAttribute.array[ offset + 2 ] = value.b;
  10750. offset += 3;
  10751. }
  10752. } else {
  10753. for ( ca = 0; ca < cal; ca ++ ) {
  10754. index = sortArray[ ca ][ 1 ];
  10755. value = customAttribute.value[ index ];
  10756. customAttribute.array[ offset ] = value.x;
  10757. customAttribute.array[ offset + 1 ] = value.y;
  10758. customAttribute.array[ offset + 2 ] = value.z;
  10759. offset += 3;
  10760. }
  10761. }
  10762. } else if ( customAttribute.size === 4 ) {
  10763. for ( ca = 0; ca < cal; ca ++ ) {
  10764. index = sortArray[ ca ][ 1 ];
  10765. value = customAttribute.value[ index ];
  10766. customAttribute.array[ offset ] = value.x;
  10767. customAttribute.array[ offset + 1 ] = value.y;
  10768. customAttribute.array[ offset + 2 ] = value.z;
  10769. customAttribute.array[ offset + 3 ] = value.w;
  10770. offset += 4;
  10771. }
  10772. }
  10773. }
  10774. }
  10775. } else {
  10776. if ( dirtyVertices ) {
  10777. for ( v = 0; v < vl; v ++ ) {
  10778. vertex = vertices[ v ];
  10779. offset = v * 3;
  10780. vertexArray[ offset ] = vertex.x;
  10781. vertexArray[ offset + 1 ] = vertex.y;
  10782. vertexArray[ offset + 2 ] = vertex.z;
  10783. }
  10784. }
  10785. if ( dirtyColors ) {
  10786. for ( c = 0; c < cl; c ++ ) {
  10787. color = colors[ c ];
  10788. offset = c * 3;
  10789. colorArray[ offset ] = color.r;
  10790. colorArray[ offset + 1 ] = color.g;
  10791. colorArray[ offset + 2 ] = color.b;
  10792. }
  10793. }
  10794. if ( customAttributes ) {
  10795. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10796. customAttribute = customAttributes[ i ];
  10797. if ( customAttribute.needsUpdate &&
  10798. ( customAttribute.boundTo === undefined ||
  10799. customAttribute.boundTo === "vertices") ) {
  10800. cal = customAttribute.value.length;
  10801. offset = 0;
  10802. if ( customAttribute.size === 1 ) {
  10803. for ( ca = 0; ca < cal; ca ++ ) {
  10804. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10805. }
  10806. } else if ( customAttribute.size === 2 ) {
  10807. for ( ca = 0; ca < cal; ca ++ ) {
  10808. value = customAttribute.value[ ca ];
  10809. customAttribute.array[ offset ] = value.x;
  10810. customAttribute.array[ offset + 1 ] = value.y;
  10811. offset += 2;
  10812. }
  10813. } else if ( customAttribute.size === 3 ) {
  10814. if ( customAttribute.type === "c" ) {
  10815. for ( ca = 0; ca < cal; ca ++ ) {
  10816. value = customAttribute.value[ ca ];
  10817. customAttribute.array[ offset ] = value.r;
  10818. customAttribute.array[ offset + 1 ] = value.g;
  10819. customAttribute.array[ offset + 2 ] = value.b;
  10820. offset += 3;
  10821. }
  10822. } else {
  10823. for ( ca = 0; ca < cal; ca ++ ) {
  10824. value = customAttribute.value[ ca ];
  10825. customAttribute.array[ offset ] = value.x;
  10826. customAttribute.array[ offset + 1 ] = value.y;
  10827. customAttribute.array[ offset + 2 ] = value.z;
  10828. offset += 3;
  10829. }
  10830. }
  10831. } else if ( customAttribute.size === 4 ) {
  10832. for ( ca = 0; ca < cal; ca ++ ) {
  10833. value = customAttribute.value[ ca ];
  10834. customAttribute.array[ offset ] = value.x;
  10835. customAttribute.array[ offset + 1 ] = value.y;
  10836. customAttribute.array[ offset + 2 ] = value.z;
  10837. customAttribute.array[ offset + 3 ] = value.w;
  10838. offset += 4;
  10839. }
  10840. }
  10841. }
  10842. }
  10843. }
  10844. }
  10845. if ( dirtyVertices || object.sortParticles ) {
  10846. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10847. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10848. }
  10849. if ( dirtyColors || object.sortParticles ) {
  10850. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10851. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10852. }
  10853. if ( customAttributes ) {
  10854. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10855. customAttribute = customAttributes[ i ];
  10856. if ( customAttribute.needsUpdate || object.sortParticles ) {
  10857. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10858. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10859. }
  10860. }
  10861. }
  10862. };
  10863. function setLineBuffers ( geometry, hint ) {
  10864. var v, c, d, vertex, offset, color,
  10865. vertices = geometry.vertices,
  10866. colors = geometry.colors,
  10867. lineDistances = geometry.lineDistances,
  10868. vl = vertices.length,
  10869. cl = colors.length,
  10870. dl = lineDistances.length,
  10871. vertexArray = geometry.__vertexArray,
  10872. colorArray = geometry.__colorArray,
  10873. lineDistanceArray = geometry.__lineDistanceArray,
  10874. dirtyVertices = geometry.verticesNeedUpdate,
  10875. dirtyColors = geometry.colorsNeedUpdate,
  10876. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  10877. customAttributes = geometry.__webglCustomAttributesList,
  10878. i, il,
  10879. a, ca, cal, value,
  10880. customAttribute;
  10881. if ( dirtyVertices ) {
  10882. for ( v = 0; v < vl; v ++ ) {
  10883. vertex = vertices[ v ];
  10884. offset = v * 3;
  10885. vertexArray[ offset ] = vertex.x;
  10886. vertexArray[ offset + 1 ] = vertex.y;
  10887. vertexArray[ offset + 2 ] = vertex.z;
  10888. }
  10889. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10890. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10891. }
  10892. if ( dirtyColors ) {
  10893. for ( c = 0; c < cl; c ++ ) {
  10894. color = colors[ c ];
  10895. offset = c * 3;
  10896. colorArray[ offset ] = color.r;
  10897. colorArray[ offset + 1 ] = color.g;
  10898. colorArray[ offset + 2 ] = color.b;
  10899. }
  10900. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10901. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10902. }
  10903. if ( dirtyLineDistances ) {
  10904. for ( d = 0; d < dl; d ++ ) {
  10905. lineDistanceArray[ d ] = lineDistances[ d ];
  10906. }
  10907. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  10908. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  10909. }
  10910. if ( customAttributes ) {
  10911. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10912. customAttribute = customAttributes[ i ];
  10913. if ( customAttribute.needsUpdate &&
  10914. ( customAttribute.boundTo === undefined ||
  10915. customAttribute.boundTo === "vertices" ) ) {
  10916. offset = 0;
  10917. cal = customAttribute.value.length;
  10918. if ( customAttribute.size === 1 ) {
  10919. for ( ca = 0; ca < cal; ca ++ ) {
  10920. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10921. }
  10922. } else if ( customAttribute.size === 2 ) {
  10923. for ( ca = 0; ca < cal; ca ++ ) {
  10924. value = customAttribute.value[ ca ];
  10925. customAttribute.array[ offset ] = value.x;
  10926. customAttribute.array[ offset + 1 ] = value.y;
  10927. offset += 2;
  10928. }
  10929. } else if ( customAttribute.size === 3 ) {
  10930. if ( customAttribute.type === "c" ) {
  10931. for ( ca = 0; ca < cal; ca ++ ) {
  10932. value = customAttribute.value[ ca ];
  10933. customAttribute.array[ offset ] = value.r;
  10934. customAttribute.array[ offset + 1 ] = value.g;
  10935. customAttribute.array[ offset + 2 ] = value.b;
  10936. offset += 3;
  10937. }
  10938. } else {
  10939. for ( ca = 0; ca < cal; ca ++ ) {
  10940. value = customAttribute.value[ ca ];
  10941. customAttribute.array[ offset ] = value.x;
  10942. customAttribute.array[ offset + 1 ] = value.y;
  10943. customAttribute.array[ offset + 2 ] = value.z;
  10944. offset += 3;
  10945. }
  10946. }
  10947. } else if ( customAttribute.size === 4 ) {
  10948. for ( ca = 0; ca < cal; ca ++ ) {
  10949. value = customAttribute.value[ ca ];
  10950. customAttribute.array[ offset ] = value.x;
  10951. customAttribute.array[ offset + 1 ] = value.y;
  10952. customAttribute.array[ offset + 2 ] = value.z;
  10953. customAttribute.array[ offset + 3 ] = value.w;
  10954. offset += 4;
  10955. }
  10956. }
  10957. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10958. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10959. }
  10960. }
  10961. }
  10962. };
  10963. function setRibbonBuffers ( geometry, hint ) {
  10964. var v, c, n, vertex, offset, color, normal,
  10965. i, il, ca, cal, customAttribute, value,
  10966. vertices = geometry.vertices,
  10967. colors = geometry.colors,
  10968. normals = geometry.normals,
  10969. vl = vertices.length,
  10970. cl = colors.length,
  10971. nl = normals.length,
  10972. vertexArray = geometry.__vertexArray,
  10973. colorArray = geometry.__colorArray,
  10974. normalArray = geometry.__normalArray,
  10975. dirtyVertices = geometry.verticesNeedUpdate,
  10976. dirtyColors = geometry.colorsNeedUpdate,
  10977. dirtyNormals = geometry.normalsNeedUpdate,
  10978. customAttributes = geometry.__webglCustomAttributesList;
  10979. if ( dirtyVertices ) {
  10980. for ( v = 0; v < vl; v ++ ) {
  10981. vertex = vertices[ v ];
  10982. offset = v * 3;
  10983. vertexArray[ offset ] = vertex.x;
  10984. vertexArray[ offset + 1 ] = vertex.y;
  10985. vertexArray[ offset + 2 ] = vertex.z;
  10986. }
  10987. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10988. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10989. }
  10990. if ( dirtyColors ) {
  10991. for ( c = 0; c < cl; c ++ ) {
  10992. color = colors[ c ];
  10993. offset = c * 3;
  10994. colorArray[ offset ] = color.r;
  10995. colorArray[ offset + 1 ] = color.g;
  10996. colorArray[ offset + 2 ] = color.b;
  10997. }
  10998. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10999. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11000. }
  11001. if ( dirtyNormals ) {
  11002. for ( n = 0; n < nl; n ++ ) {
  11003. normal = normals[ n ];
  11004. offset = n * 3;
  11005. normalArray[ offset ] = normal.x;
  11006. normalArray[ offset + 1 ] = normal.y;
  11007. normalArray[ offset + 2 ] = normal.z;
  11008. }
  11009. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglNormalBuffer );
  11010. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  11011. }
  11012. if ( customAttributes ) {
  11013. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11014. customAttribute = customAttributes[ i ];
  11015. if ( customAttribute.needsUpdate &&
  11016. ( customAttribute.boundTo === undefined ||
  11017. customAttribute.boundTo === "vertices" ) ) {
  11018. offset = 0;
  11019. cal = customAttribute.value.length;
  11020. if ( customAttribute.size === 1 ) {
  11021. for ( ca = 0; ca < cal; ca ++ ) {
  11022. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11023. }
  11024. } else if ( customAttribute.size === 2 ) {
  11025. for ( ca = 0; ca < cal; ca ++ ) {
  11026. value = customAttribute.value[ ca ];
  11027. customAttribute.array[ offset ] = value.x;
  11028. customAttribute.array[ offset + 1 ] = value.y;
  11029. offset += 2;
  11030. }
  11031. } else if ( customAttribute.size === 3 ) {
  11032. if ( customAttribute.type === "c" ) {
  11033. for ( ca = 0; ca < cal; ca ++ ) {
  11034. value = customAttribute.value[ ca ];
  11035. customAttribute.array[ offset ] = value.r;
  11036. customAttribute.array[ offset + 1 ] = value.g;
  11037. customAttribute.array[ offset + 2 ] = value.b;
  11038. offset += 3;
  11039. }
  11040. } else {
  11041. for ( ca = 0; ca < cal; ca ++ ) {
  11042. value = customAttribute.value[ ca ];
  11043. customAttribute.array[ offset ] = value.x;
  11044. customAttribute.array[ offset + 1 ] = value.y;
  11045. customAttribute.array[ offset + 2 ] = value.z;
  11046. offset += 3;
  11047. }
  11048. }
  11049. } else if ( customAttribute.size === 4 ) {
  11050. for ( ca = 0; ca < cal; ca ++ ) {
  11051. value = customAttribute.value[ ca ];
  11052. customAttribute.array[ offset ] = value.x;
  11053. customAttribute.array[ offset + 1 ] = value.y;
  11054. customAttribute.array[ offset + 2 ] = value.z;
  11055. customAttribute.array[ offset + 3 ] = value.w;
  11056. offset += 4;
  11057. }
  11058. }
  11059. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11060. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11061. }
  11062. }
  11063. }
  11064. };
  11065. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  11066. if ( ! geometryGroup.__inittedArrays ) {
  11067. return;
  11068. }
  11069. var normalType = bufferGuessNormalType( material ),
  11070. vertexColorType = bufferGuessVertexColorType( material ),
  11071. uvType = bufferGuessUVType( material ),
  11072. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  11073. var f, fl, fi, face,
  11074. vertexNormals, faceNormal, normal,
  11075. vertexColors, faceColor,
  11076. vertexTangents,
  11077. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  11078. c1, c2, c3, c4,
  11079. sw1, sw2, sw3, sw4,
  11080. si1, si2, si3, si4,
  11081. sa1, sa2, sa3, sa4,
  11082. sb1, sb2, sb3, sb4,
  11083. m, ml, i, il,
  11084. vn, uvi, uv2i,
  11085. vk, vkl, vka,
  11086. nka, chf, faceVertexNormals,
  11087. a,
  11088. vertexIndex = 0,
  11089. offset = 0,
  11090. offset_uv = 0,
  11091. offset_uv2 = 0,
  11092. offset_face = 0,
  11093. offset_normal = 0,
  11094. offset_tangent = 0,
  11095. offset_line = 0,
  11096. offset_color = 0,
  11097. offset_skin = 0,
  11098. offset_morphTarget = 0,
  11099. offset_custom = 0,
  11100. offset_customSrc = 0,
  11101. value,
  11102. vertexArray = geometryGroup.__vertexArray,
  11103. uvArray = geometryGroup.__uvArray,
  11104. uv2Array = geometryGroup.__uv2Array,
  11105. normalArray = geometryGroup.__normalArray,
  11106. tangentArray = geometryGroup.__tangentArray,
  11107. colorArray = geometryGroup.__colorArray,
  11108. skinIndexArray = geometryGroup.__skinIndexArray,
  11109. skinWeightArray = geometryGroup.__skinWeightArray,
  11110. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  11111. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  11112. customAttributes = geometryGroup.__webglCustomAttributesList,
  11113. customAttribute,
  11114. faceArray = geometryGroup.__faceArray,
  11115. lineArray = geometryGroup.__lineArray,
  11116. geometry = object.geometry, // this is shared for all chunks
  11117. dirtyVertices = geometry.verticesNeedUpdate,
  11118. dirtyElements = geometry.elementsNeedUpdate,
  11119. dirtyUvs = geometry.uvsNeedUpdate,
  11120. dirtyNormals = geometry.normalsNeedUpdate,
  11121. dirtyTangents = geometry.tangentsNeedUpdate,
  11122. dirtyColors = geometry.colorsNeedUpdate,
  11123. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  11124. vertices = geometry.vertices,
  11125. chunk_faces3 = geometryGroup.faces3,
  11126. chunk_faces4 = geometryGroup.faces4,
  11127. obj_faces = geometry.faces,
  11128. obj_uvs = geometry.faceVertexUvs[ 0 ],
  11129. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  11130. obj_colors = geometry.colors,
  11131. obj_skinIndices = geometry.skinIndices,
  11132. obj_skinWeights = geometry.skinWeights,
  11133. morphTargets = geometry.morphTargets,
  11134. morphNormals = geometry.morphNormals;
  11135. if ( dirtyVertices ) {
  11136. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11137. face = obj_faces[ chunk_faces3[ f ] ];
  11138. v1 = vertices[ face.a ];
  11139. v2 = vertices[ face.b ];
  11140. v3 = vertices[ face.c ];
  11141. vertexArray[ offset ] = v1.x;
  11142. vertexArray[ offset + 1 ] = v1.y;
  11143. vertexArray[ offset + 2 ] = v1.z;
  11144. vertexArray[ offset + 3 ] = v2.x;
  11145. vertexArray[ offset + 4 ] = v2.y;
  11146. vertexArray[ offset + 5 ] = v2.z;
  11147. vertexArray[ offset + 6 ] = v3.x;
  11148. vertexArray[ offset + 7 ] = v3.y;
  11149. vertexArray[ offset + 8 ] = v3.z;
  11150. offset += 9;
  11151. }
  11152. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11153. face = obj_faces[ chunk_faces4[ f ] ];
  11154. v1 = vertices[ face.a ];
  11155. v2 = vertices[ face.b ];
  11156. v3 = vertices[ face.c ];
  11157. v4 = vertices[ face.d ];
  11158. vertexArray[ offset ] = v1.x;
  11159. vertexArray[ offset + 1 ] = v1.y;
  11160. vertexArray[ offset + 2 ] = v1.z;
  11161. vertexArray[ offset + 3 ] = v2.x;
  11162. vertexArray[ offset + 4 ] = v2.y;
  11163. vertexArray[ offset + 5 ] = v2.z;
  11164. vertexArray[ offset + 6 ] = v3.x;
  11165. vertexArray[ offset + 7 ] = v3.y;
  11166. vertexArray[ offset + 8 ] = v3.z;
  11167. vertexArray[ offset + 9 ] = v4.x;
  11168. vertexArray[ offset + 10 ] = v4.y;
  11169. vertexArray[ offset + 11 ] = v4.z;
  11170. offset += 12;
  11171. }
  11172. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11173. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11174. }
  11175. if ( dirtyMorphTargets ) {
  11176. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  11177. offset_morphTarget = 0;
  11178. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11179. chf = chunk_faces3[ f ];
  11180. face = obj_faces[ chf ];
  11181. // morph positions
  11182. v1 = morphTargets[ vk ].vertices[ face.a ];
  11183. v2 = morphTargets[ vk ].vertices[ face.b ];
  11184. v3 = morphTargets[ vk ].vertices[ face.c ];
  11185. vka = morphTargetsArrays[ vk ];
  11186. vka[ offset_morphTarget ] = v1.x;
  11187. vka[ offset_morphTarget + 1 ] = v1.y;
  11188. vka[ offset_morphTarget + 2 ] = v1.z;
  11189. vka[ offset_morphTarget + 3 ] = v2.x;
  11190. vka[ offset_morphTarget + 4 ] = v2.y;
  11191. vka[ offset_morphTarget + 5 ] = v2.z;
  11192. vka[ offset_morphTarget + 6 ] = v3.x;
  11193. vka[ offset_morphTarget + 7 ] = v3.y;
  11194. vka[ offset_morphTarget + 8 ] = v3.z;
  11195. // morph normals
  11196. if ( material.morphNormals ) {
  11197. if ( needsSmoothNormals ) {
  11198. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  11199. n1 = faceVertexNormals.a;
  11200. n2 = faceVertexNormals.b;
  11201. n3 = faceVertexNormals.c;
  11202. } else {
  11203. n1 = morphNormals[ vk ].faceNormals[ chf ];
  11204. n2 = n1;
  11205. n3 = n1;
  11206. }
  11207. nka = morphNormalsArrays[ vk ];
  11208. nka[ offset_morphTarget ] = n1.x;
  11209. nka[ offset_morphTarget + 1 ] = n1.y;
  11210. nka[ offset_morphTarget + 2 ] = n1.z;
  11211. nka[ offset_morphTarget + 3 ] = n2.x;
  11212. nka[ offset_morphTarget + 4 ] = n2.y;
  11213. nka[ offset_morphTarget + 5 ] = n2.z;
  11214. nka[ offset_morphTarget + 6 ] = n3.x;
  11215. nka[ offset_morphTarget + 7 ] = n3.y;
  11216. nka[ offset_morphTarget + 8 ] = n3.z;
  11217. }
  11218. //
  11219. offset_morphTarget += 9;
  11220. }
  11221. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11222. chf = chunk_faces4[ f ];
  11223. face = obj_faces[ chf ];
  11224. // morph positions
  11225. v1 = morphTargets[ vk ].vertices[ face.a ];
  11226. v2 = morphTargets[ vk ].vertices[ face.b ];
  11227. v3 = morphTargets[ vk ].vertices[ face.c ];
  11228. v4 = morphTargets[ vk ].vertices[ face.d ];
  11229. vka = morphTargetsArrays[ vk ];
  11230. vka[ offset_morphTarget ] = v1.x;
  11231. vka[ offset_morphTarget + 1 ] = v1.y;
  11232. vka[ offset_morphTarget + 2 ] = v1.z;
  11233. vka[ offset_morphTarget + 3 ] = v2.x;
  11234. vka[ offset_morphTarget + 4 ] = v2.y;
  11235. vka[ offset_morphTarget + 5 ] = v2.z;
  11236. vka[ offset_morphTarget + 6 ] = v3.x;
  11237. vka[ offset_morphTarget + 7 ] = v3.y;
  11238. vka[ offset_morphTarget + 8 ] = v3.z;
  11239. vka[ offset_morphTarget + 9 ] = v4.x;
  11240. vka[ offset_morphTarget + 10 ] = v4.y;
  11241. vka[ offset_morphTarget + 11 ] = v4.z;
  11242. // morph normals
  11243. if ( material.morphNormals ) {
  11244. if ( needsSmoothNormals ) {
  11245. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  11246. n1 = faceVertexNormals.a;
  11247. n2 = faceVertexNormals.b;
  11248. n3 = faceVertexNormals.c;
  11249. n4 = faceVertexNormals.d;
  11250. } else {
  11251. n1 = morphNormals[ vk ].faceNormals[ chf ];
  11252. n2 = n1;
  11253. n3 = n1;
  11254. n4 = n1;
  11255. }
  11256. nka = morphNormalsArrays[ vk ];
  11257. nka[ offset_morphTarget ] = n1.x;
  11258. nka[ offset_morphTarget + 1 ] = n1.y;
  11259. nka[ offset_morphTarget + 2 ] = n1.z;
  11260. nka[ offset_morphTarget + 3 ] = n2.x;
  11261. nka[ offset_morphTarget + 4 ] = n2.y;
  11262. nka[ offset_morphTarget + 5 ] = n2.z;
  11263. nka[ offset_morphTarget + 6 ] = n3.x;
  11264. nka[ offset_morphTarget + 7 ] = n3.y;
  11265. nka[ offset_morphTarget + 8 ] = n3.z;
  11266. nka[ offset_morphTarget + 9 ] = n4.x;
  11267. nka[ offset_morphTarget + 10 ] = n4.y;
  11268. nka[ offset_morphTarget + 11 ] = n4.z;
  11269. }
  11270. //
  11271. offset_morphTarget += 12;
  11272. }
  11273. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  11274. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  11275. if ( material.morphNormals ) {
  11276. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  11277. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  11278. }
  11279. }
  11280. }
  11281. if ( obj_skinWeights.length ) {
  11282. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11283. face = obj_faces[ chunk_faces3[ f ] ];
  11284. // weights
  11285. sw1 = obj_skinWeights[ face.a ];
  11286. sw2 = obj_skinWeights[ face.b ];
  11287. sw3 = obj_skinWeights[ face.c ];
  11288. skinWeightArray[ offset_skin ] = sw1.x;
  11289. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  11290. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  11291. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  11292. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  11293. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  11294. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  11295. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  11296. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  11297. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  11298. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  11299. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  11300. // indices
  11301. si1 = obj_skinIndices[ face.a ];
  11302. si2 = obj_skinIndices[ face.b ];
  11303. si3 = obj_skinIndices[ face.c ];
  11304. skinIndexArray[ offset_skin ] = si1.x;
  11305. skinIndexArray[ offset_skin + 1 ] = si1.y;
  11306. skinIndexArray[ offset_skin + 2 ] = si1.z;
  11307. skinIndexArray[ offset_skin + 3 ] = si1.w;
  11308. skinIndexArray[ offset_skin + 4 ] = si2.x;
  11309. skinIndexArray[ offset_skin + 5 ] = si2.y;
  11310. skinIndexArray[ offset_skin + 6 ] = si2.z;
  11311. skinIndexArray[ offset_skin + 7 ] = si2.w;
  11312. skinIndexArray[ offset_skin + 8 ] = si3.x;
  11313. skinIndexArray[ offset_skin + 9 ] = si3.y;
  11314. skinIndexArray[ offset_skin + 10 ] = si3.z;
  11315. skinIndexArray[ offset_skin + 11 ] = si3.w;
  11316. offset_skin += 12;
  11317. }
  11318. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11319. face = obj_faces[ chunk_faces4[ f ] ];
  11320. // weights
  11321. sw1 = obj_skinWeights[ face.a ];
  11322. sw2 = obj_skinWeights[ face.b ];
  11323. sw3 = obj_skinWeights[ face.c ];
  11324. sw4 = obj_skinWeights[ face.d ];
  11325. skinWeightArray[ offset_skin ] = sw1.x;
  11326. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  11327. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  11328. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  11329. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  11330. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  11331. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  11332. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  11333. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  11334. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  11335. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  11336. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  11337. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  11338. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  11339. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  11340. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  11341. // indices
  11342. si1 = obj_skinIndices[ face.a ];
  11343. si2 = obj_skinIndices[ face.b ];
  11344. si3 = obj_skinIndices[ face.c ];
  11345. si4 = obj_skinIndices[ face.d ];
  11346. skinIndexArray[ offset_skin ] = si1.x;
  11347. skinIndexArray[ offset_skin + 1 ] = si1.y;
  11348. skinIndexArray[ offset_skin + 2 ] = si1.z;
  11349. skinIndexArray[ offset_skin + 3 ] = si1.w;
  11350. skinIndexArray[ offset_skin + 4 ] = si2.x;
  11351. skinIndexArray[ offset_skin + 5 ] = si2.y;
  11352. skinIndexArray[ offset_skin + 6 ] = si2.z;
  11353. skinIndexArray[ offset_skin + 7 ] = si2.w;
  11354. skinIndexArray[ offset_skin + 8 ] = si3.x;
  11355. skinIndexArray[ offset_skin + 9 ] = si3.y;
  11356. skinIndexArray[ offset_skin + 10 ] = si3.z;
  11357. skinIndexArray[ offset_skin + 11 ] = si3.w;
  11358. skinIndexArray[ offset_skin + 12 ] = si4.x;
  11359. skinIndexArray[ offset_skin + 13 ] = si4.y;
  11360. skinIndexArray[ offset_skin + 14 ] = si4.z;
  11361. skinIndexArray[ offset_skin + 15 ] = si4.w;
  11362. offset_skin += 16;
  11363. }
  11364. if ( offset_skin > 0 ) {
  11365. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  11366. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  11367. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  11368. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  11369. }
  11370. }
  11371. if ( dirtyColors && vertexColorType ) {
  11372. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11373. face = obj_faces[ chunk_faces3[ f ] ];
  11374. vertexColors = face.vertexColors;
  11375. faceColor = face.color;
  11376. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  11377. c1 = vertexColors[ 0 ];
  11378. c2 = vertexColors[ 1 ];
  11379. c3 = vertexColors[ 2 ];
  11380. } else {
  11381. c1 = faceColor;
  11382. c2 = faceColor;
  11383. c3 = faceColor;
  11384. }
  11385. colorArray[ offset_color ] = c1.r;
  11386. colorArray[ offset_color + 1 ] = c1.g;
  11387. colorArray[ offset_color + 2 ] = c1.b;
  11388. colorArray[ offset_color + 3 ] = c2.r;
  11389. colorArray[ offset_color + 4 ] = c2.g;
  11390. colorArray[ offset_color + 5 ] = c2.b;
  11391. colorArray[ offset_color + 6 ] = c3.r;
  11392. colorArray[ offset_color + 7 ] = c3.g;
  11393. colorArray[ offset_color + 8 ] = c3.b;
  11394. offset_color += 9;
  11395. }
  11396. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11397. face = obj_faces[ chunk_faces4[ f ] ];
  11398. vertexColors = face.vertexColors;
  11399. faceColor = face.color;
  11400. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  11401. c1 = vertexColors[ 0 ];
  11402. c2 = vertexColors[ 1 ];
  11403. c3 = vertexColors[ 2 ];
  11404. c4 = vertexColors[ 3 ];
  11405. } else {
  11406. c1 = faceColor;
  11407. c2 = faceColor;
  11408. c3 = faceColor;
  11409. c4 = faceColor;
  11410. }
  11411. colorArray[ offset_color ] = c1.r;
  11412. colorArray[ offset_color + 1 ] = c1.g;
  11413. colorArray[ offset_color + 2 ] = c1.b;
  11414. colorArray[ offset_color + 3 ] = c2.r;
  11415. colorArray[ offset_color + 4 ] = c2.g;
  11416. colorArray[ offset_color + 5 ] = c2.b;
  11417. colorArray[ offset_color + 6 ] = c3.r;
  11418. colorArray[ offset_color + 7 ] = c3.g;
  11419. colorArray[ offset_color + 8 ] = c3.b;
  11420. colorArray[ offset_color + 9 ] = c4.r;
  11421. colorArray[ offset_color + 10 ] = c4.g;
  11422. colorArray[ offset_color + 11 ] = c4.b;
  11423. offset_color += 12;
  11424. }
  11425. if ( offset_color > 0 ) {
  11426. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  11427. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11428. }
  11429. }
  11430. if ( dirtyTangents && geometry.hasTangents ) {
  11431. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11432. face = obj_faces[ chunk_faces3[ f ] ];
  11433. vertexTangents = face.vertexTangents;
  11434. t1 = vertexTangents[ 0 ];
  11435. t2 = vertexTangents[ 1 ];
  11436. t3 = vertexTangents[ 2 ];
  11437. tangentArray[ offset_tangent ] = t1.x;
  11438. tangentArray[ offset_tangent + 1 ] = t1.y;
  11439. tangentArray[ offset_tangent + 2 ] = t1.z;
  11440. tangentArray[ offset_tangent + 3 ] = t1.w;
  11441. tangentArray[ offset_tangent + 4 ] = t2.x;
  11442. tangentArray[ offset_tangent + 5 ] = t2.y;
  11443. tangentArray[ offset_tangent + 6 ] = t2.z;
  11444. tangentArray[ offset_tangent + 7 ] = t2.w;
  11445. tangentArray[ offset_tangent + 8 ] = t3.x;
  11446. tangentArray[ offset_tangent + 9 ] = t3.y;
  11447. tangentArray[ offset_tangent + 10 ] = t3.z;
  11448. tangentArray[ offset_tangent + 11 ] = t3.w;
  11449. offset_tangent += 12;
  11450. }
  11451. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11452. face = obj_faces[ chunk_faces4[ f ] ];
  11453. vertexTangents = face.vertexTangents;
  11454. t1 = vertexTangents[ 0 ];
  11455. t2 = vertexTangents[ 1 ];
  11456. t3 = vertexTangents[ 2 ];
  11457. t4 = vertexTangents[ 3 ];
  11458. tangentArray[ offset_tangent ] = t1.x;
  11459. tangentArray[ offset_tangent + 1 ] = t1.y;
  11460. tangentArray[ offset_tangent + 2 ] = t1.z;
  11461. tangentArray[ offset_tangent + 3 ] = t1.w;
  11462. tangentArray[ offset_tangent + 4 ] = t2.x;
  11463. tangentArray[ offset_tangent + 5 ] = t2.y;
  11464. tangentArray[ offset_tangent + 6 ] = t2.z;
  11465. tangentArray[ offset_tangent + 7 ] = t2.w;
  11466. tangentArray[ offset_tangent + 8 ] = t3.x;
  11467. tangentArray[ offset_tangent + 9 ] = t3.y;
  11468. tangentArray[ offset_tangent + 10 ] = t3.z;
  11469. tangentArray[ offset_tangent + 11 ] = t3.w;
  11470. tangentArray[ offset_tangent + 12 ] = t4.x;
  11471. tangentArray[ offset_tangent + 13 ] = t4.y;
  11472. tangentArray[ offset_tangent + 14 ] = t4.z;
  11473. tangentArray[ offset_tangent + 15 ] = t4.w;
  11474. offset_tangent += 16;
  11475. }
  11476. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  11477. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  11478. }
  11479. if ( dirtyNormals && normalType ) {
  11480. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11481. face = obj_faces[ chunk_faces3[ f ] ];
  11482. vertexNormals = face.vertexNormals;
  11483. faceNormal = face.normal;
  11484. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  11485. for ( i = 0; i < 3; i ++ ) {
  11486. vn = vertexNormals[ i ];
  11487. normalArray[ offset_normal ] = vn.x;
  11488. normalArray[ offset_normal + 1 ] = vn.y;
  11489. normalArray[ offset_normal + 2 ] = vn.z;
  11490. offset_normal += 3;
  11491. }
  11492. } else {
  11493. for ( i = 0; i < 3; i ++ ) {
  11494. normalArray[ offset_normal ] = faceNormal.x;
  11495. normalArray[ offset_normal + 1 ] = faceNormal.y;
  11496. normalArray[ offset_normal + 2 ] = faceNormal.z;
  11497. offset_normal += 3;
  11498. }
  11499. }
  11500. }
  11501. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11502. face = obj_faces[ chunk_faces4[ f ] ];
  11503. vertexNormals = face.vertexNormals;
  11504. faceNormal = face.normal;
  11505. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  11506. for ( i = 0; i < 4; i ++ ) {
  11507. vn = vertexNormals[ i ];
  11508. normalArray[ offset_normal ] = vn.x;
  11509. normalArray[ offset_normal + 1 ] = vn.y;
  11510. normalArray[ offset_normal + 2 ] = vn.z;
  11511. offset_normal += 3;
  11512. }
  11513. } else {
  11514. for ( i = 0; i < 4; i ++ ) {
  11515. normalArray[ offset_normal ] = faceNormal.x;
  11516. normalArray[ offset_normal + 1 ] = faceNormal.y;
  11517. normalArray[ offset_normal + 2 ] = faceNormal.z;
  11518. offset_normal += 3;
  11519. }
  11520. }
  11521. }
  11522. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  11523. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  11524. }
  11525. if ( dirtyUvs && obj_uvs && uvType ) {
  11526. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11527. fi = chunk_faces3[ f ];
  11528. uv = obj_uvs[ fi ];
  11529. if ( uv === undefined ) continue;
  11530. for ( i = 0; i < 3; i ++ ) {
  11531. uvi = uv[ i ];
  11532. uvArray[ offset_uv ] = uvi.x;
  11533. uvArray[ offset_uv + 1 ] = uvi.y;
  11534. offset_uv += 2;
  11535. }
  11536. }
  11537. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11538. fi = chunk_faces4[ f ];
  11539. uv = obj_uvs[ fi ];
  11540. if ( uv === undefined ) continue;
  11541. for ( i = 0; i < 4; i ++ ) {
  11542. uvi = uv[ i ];
  11543. uvArray[ offset_uv ] = uvi.x;
  11544. uvArray[ offset_uv + 1 ] = uvi.y;
  11545. offset_uv += 2;
  11546. }
  11547. }
  11548. if ( offset_uv > 0 ) {
  11549. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  11550. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  11551. }
  11552. }
  11553. if ( dirtyUvs && obj_uvs2 && uvType ) {
  11554. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11555. fi = chunk_faces3[ f ];
  11556. uv2 = obj_uvs2[ fi ];
  11557. if ( uv2 === undefined ) continue;
  11558. for ( i = 0; i < 3; i ++ ) {
  11559. uv2i = uv2[ i ];
  11560. uv2Array[ offset_uv2 ] = uv2i.x;
  11561. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  11562. offset_uv2 += 2;
  11563. }
  11564. }
  11565. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11566. fi = chunk_faces4[ f ];
  11567. uv2 = obj_uvs2[ fi ];
  11568. if ( uv2 === undefined ) continue;
  11569. for ( i = 0; i < 4; i ++ ) {
  11570. uv2i = uv2[ i ];
  11571. uv2Array[ offset_uv2 ] = uv2i.x;
  11572. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  11573. offset_uv2 += 2;
  11574. }
  11575. }
  11576. if ( offset_uv2 > 0 ) {
  11577. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  11578. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  11579. }
  11580. }
  11581. if ( dirtyElements ) {
  11582. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11583. faceArray[ offset_face ] = vertexIndex;
  11584. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  11585. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  11586. offset_face += 3;
  11587. lineArray[ offset_line ] = vertexIndex;
  11588. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  11589. lineArray[ offset_line + 2 ] = vertexIndex;
  11590. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  11591. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  11592. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  11593. offset_line += 6;
  11594. vertexIndex += 3;
  11595. }
  11596. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11597. faceArray[ offset_face ] = vertexIndex;
  11598. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  11599. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  11600. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  11601. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  11602. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  11603. offset_face += 6;
  11604. lineArray[ offset_line ] = vertexIndex;
  11605. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  11606. lineArray[ offset_line + 2 ] = vertexIndex;
  11607. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  11608. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  11609. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  11610. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  11611. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  11612. offset_line += 8;
  11613. vertexIndex += 4;
  11614. }
  11615. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  11616. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  11617. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  11618. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  11619. }
  11620. if ( customAttributes ) {
  11621. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11622. customAttribute = customAttributes[ i ];
  11623. if ( ! customAttribute.__original.needsUpdate ) continue;
  11624. offset_custom = 0;
  11625. offset_customSrc = 0;
  11626. if ( customAttribute.size === 1 ) {
  11627. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11628. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11629. face = obj_faces[ chunk_faces3[ f ] ];
  11630. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  11631. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  11632. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  11633. offset_custom += 3;
  11634. }
  11635. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11636. face = obj_faces[ chunk_faces4[ f ] ];
  11637. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  11638. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  11639. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  11640. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  11641. offset_custom += 4;
  11642. }
  11643. } else if ( customAttribute.boundTo === "faces" ) {
  11644. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11645. value = customAttribute.value[ chunk_faces3[ f ] ];
  11646. customAttribute.array[ offset_custom ] = value;
  11647. customAttribute.array[ offset_custom + 1 ] = value;
  11648. customAttribute.array[ offset_custom + 2 ] = value;
  11649. offset_custom += 3;
  11650. }
  11651. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11652. value = customAttribute.value[ chunk_faces4[ f ] ];
  11653. customAttribute.array[ offset_custom ] = value;
  11654. customAttribute.array[ offset_custom + 1 ] = value;
  11655. customAttribute.array[ offset_custom + 2 ] = value;
  11656. customAttribute.array[ offset_custom + 3 ] = value;
  11657. offset_custom += 4;
  11658. }
  11659. }
  11660. } else if ( customAttribute.size === 2 ) {
  11661. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11662. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11663. face = obj_faces[ chunk_faces3[ f ] ];
  11664. v1 = customAttribute.value[ face.a ];
  11665. v2 = customAttribute.value[ face.b ];
  11666. v3 = customAttribute.value[ face.c ];
  11667. customAttribute.array[ offset_custom ] = v1.x;
  11668. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11669. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11670. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11671. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11672. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11673. offset_custom += 6;
  11674. }
  11675. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11676. face = obj_faces[ chunk_faces4[ f ] ];
  11677. v1 = customAttribute.value[ face.a ];
  11678. v2 = customAttribute.value[ face.b ];
  11679. v3 = customAttribute.value[ face.c ];
  11680. v4 = customAttribute.value[ face.d ];
  11681. customAttribute.array[ offset_custom ] = v1.x;
  11682. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11683. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11684. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11685. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11686. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11687. customAttribute.array[ offset_custom + 6 ] = v4.x;
  11688. customAttribute.array[ offset_custom + 7 ] = v4.y;
  11689. offset_custom += 8;
  11690. }
  11691. } else if ( customAttribute.boundTo === "faces" ) {
  11692. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11693. value = customAttribute.value[ chunk_faces3[ f ] ];
  11694. v1 = value;
  11695. v2 = value;
  11696. v3 = value;
  11697. customAttribute.array[ offset_custom ] = v1.x;
  11698. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11699. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11700. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11701. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11702. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11703. offset_custom += 6;
  11704. }
  11705. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11706. value = customAttribute.value[ chunk_faces4[ f ] ];
  11707. v1 = value;
  11708. v2 = value;
  11709. v3 = value;
  11710. v4 = value;
  11711. customAttribute.array[ offset_custom ] = v1.x;
  11712. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11713. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11714. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11715. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11716. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11717. customAttribute.array[ offset_custom + 6 ] = v4.x;
  11718. customAttribute.array[ offset_custom + 7 ] = v4.y;
  11719. offset_custom += 8;
  11720. }
  11721. }
  11722. } else if ( customAttribute.size === 3 ) {
  11723. var pp;
  11724. if ( customAttribute.type === "c" ) {
  11725. pp = [ "r", "g", "b" ];
  11726. } else {
  11727. pp = [ "x", "y", "z" ];
  11728. }
  11729. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11730. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11731. face = obj_faces[ chunk_faces3[ f ] ];
  11732. v1 = customAttribute.value[ face.a ];
  11733. v2 = customAttribute.value[ face.b ];
  11734. v3 = customAttribute.value[ face.c ];
  11735. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11736. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11737. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11738. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11739. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11740. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11741. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11742. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11743. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11744. offset_custom += 9;
  11745. }
  11746. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11747. face = obj_faces[ chunk_faces4[ f ] ];
  11748. v1 = customAttribute.value[ face.a ];
  11749. v2 = customAttribute.value[ face.b ];
  11750. v3 = customAttribute.value[ face.c ];
  11751. v4 = customAttribute.value[ face.d ];
  11752. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11753. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11754. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11755. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11756. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11757. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11758. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11759. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11760. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11761. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11762. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11763. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11764. offset_custom += 12;
  11765. }
  11766. } else if ( customAttribute.boundTo === "faces" ) {
  11767. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11768. value = customAttribute.value[ chunk_faces3[ f ] ];
  11769. v1 = value;
  11770. v2 = value;
  11771. v3 = value;
  11772. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11773. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11774. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11775. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11776. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11777. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11778. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11779. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11780. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11781. offset_custom += 9;
  11782. }
  11783. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11784. value = customAttribute.value[ chunk_faces4[ f ] ];
  11785. v1 = value;
  11786. v2 = value;
  11787. v3 = value;
  11788. v4 = value;
  11789. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11790. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11791. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11792. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11793. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11794. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11795. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11796. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11797. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11798. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11799. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11800. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11801. offset_custom += 12;
  11802. }
  11803. } else if ( customAttribute.boundTo === "faceVertices" ) {
  11804. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11805. value = customAttribute.value[ chunk_faces3[ f ] ];
  11806. v1 = value[ 0 ];
  11807. v2 = value[ 1 ];
  11808. v3 = value[ 2 ];
  11809. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11810. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11811. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11812. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11813. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11814. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11815. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11816. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11817. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11818. offset_custom += 9;
  11819. }
  11820. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11821. value = customAttribute.value[ chunk_faces4[ f ] ];
  11822. v1 = value[ 0 ];
  11823. v2 = value[ 1 ];
  11824. v3 = value[ 2 ];
  11825. v4 = value[ 3 ];
  11826. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11827. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11828. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11829. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11830. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11831. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11832. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11833. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11834. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11835. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11836. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11837. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11838. offset_custom += 12;
  11839. }
  11840. }
  11841. } else if ( customAttribute.size === 4 ) {
  11842. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11843. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11844. face = obj_faces[ chunk_faces3[ f ] ];
  11845. v1 = customAttribute.value[ face.a ];
  11846. v2 = customAttribute.value[ face.b ];
  11847. v3 = customAttribute.value[ face.c ];
  11848. customAttribute.array[ offset_custom ] = v1.x;
  11849. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11850. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11851. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11852. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11853. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11854. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11855. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11856. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11857. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11858. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11859. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11860. offset_custom += 12;
  11861. }
  11862. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11863. face = obj_faces[ chunk_faces4[ f ] ];
  11864. v1 = customAttribute.value[ face.a ];
  11865. v2 = customAttribute.value[ face.b ];
  11866. v3 = customAttribute.value[ face.c ];
  11867. v4 = customAttribute.value[ face.d ];
  11868. customAttribute.array[ offset_custom ] = v1.x;
  11869. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11870. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11871. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11872. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11873. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11874. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11875. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11876. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11877. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11878. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11879. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11880. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11881. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11882. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11883. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11884. offset_custom += 16;
  11885. }
  11886. } else if ( customAttribute.boundTo === "faces" ) {
  11887. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11888. value = customAttribute.value[ chunk_faces3[ f ] ];
  11889. v1 = value;
  11890. v2 = value;
  11891. v3 = value;
  11892. customAttribute.array[ offset_custom ] = v1.x;
  11893. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11894. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11895. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11896. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11897. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11898. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11899. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11900. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11901. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11902. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11903. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11904. offset_custom += 12;
  11905. }
  11906. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11907. value = customAttribute.value[ chunk_faces4[ f ] ];
  11908. v1 = value;
  11909. v2 = value;
  11910. v3 = value;
  11911. v4 = value;
  11912. customAttribute.array[ offset_custom ] = v1.x;
  11913. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11914. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11915. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11916. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11917. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11918. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11919. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11920. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11921. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11922. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11923. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11924. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11925. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11926. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11927. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11928. offset_custom += 16;
  11929. }
  11930. } else if ( customAttribute.boundTo === "faceVertices" ) {
  11931. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11932. value = customAttribute.value[ chunk_faces3[ f ] ];
  11933. v1 = value[ 0 ];
  11934. v2 = value[ 1 ];
  11935. v3 = value[ 2 ];
  11936. customAttribute.array[ offset_custom ] = v1.x;
  11937. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11938. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11939. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11940. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11941. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11942. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11943. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11944. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11945. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11946. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11947. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11948. offset_custom += 12;
  11949. }
  11950. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11951. value = customAttribute.value[ chunk_faces4[ f ] ];
  11952. v1 = value[ 0 ];
  11953. v2 = value[ 1 ];
  11954. v3 = value[ 2 ];
  11955. v4 = value[ 3 ];
  11956. customAttribute.array[ offset_custom ] = v1.x;
  11957. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11958. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11959. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11960. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11961. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11962. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11963. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11964. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11965. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11966. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11967. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11968. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11969. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11970. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11971. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11972. offset_custom += 16;
  11973. }
  11974. }
  11975. }
  11976. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11977. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11978. }
  11979. }
  11980. if ( dispose ) {
  11981. delete geometryGroup.__inittedArrays;
  11982. delete geometryGroup.__colorArray;
  11983. delete geometryGroup.__normalArray;
  11984. delete geometryGroup.__tangentArray;
  11985. delete geometryGroup.__uvArray;
  11986. delete geometryGroup.__uv2Array;
  11987. delete geometryGroup.__faceArray;
  11988. delete geometryGroup.__vertexArray;
  11989. delete geometryGroup.__lineArray;
  11990. delete geometryGroup.__skinIndexArray;
  11991. delete geometryGroup.__skinWeightArray;
  11992. }
  11993. };
  11994. function setDirectBuffers ( geometry, hint, dispose ) {
  11995. var attributes = geometry.attributes;
  11996. var index = attributes[ "index" ];
  11997. var position = attributes[ "position" ];
  11998. var normal = attributes[ "normal" ];
  11999. var uv = attributes[ "uv" ];
  12000. var color = attributes[ "color" ];
  12001. var tangent = attributes[ "tangent" ];
  12002. if ( geometry.elementsNeedUpdate && index !== undefined ) {
  12003. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12004. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, index.array, hint );
  12005. }
  12006. if ( geometry.verticesNeedUpdate && position !== undefined ) {
  12007. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12008. _gl.bufferData( _gl.ARRAY_BUFFER, position.array, hint );
  12009. }
  12010. if ( geometry.normalsNeedUpdate && normal !== undefined ) {
  12011. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  12012. _gl.bufferData( _gl.ARRAY_BUFFER, normal.array, hint );
  12013. }
  12014. if ( geometry.uvsNeedUpdate && uv !== undefined ) {
  12015. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  12016. _gl.bufferData( _gl.ARRAY_BUFFER, uv.array, hint );
  12017. }
  12018. if ( geometry.colorsNeedUpdate && color !== undefined ) {
  12019. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12020. _gl.bufferData( _gl.ARRAY_BUFFER, color.array, hint );
  12021. }
  12022. if ( geometry.tangentsNeedUpdate && tangent !== undefined ) {
  12023. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  12024. _gl.bufferData( _gl.ARRAY_BUFFER, tangent.array, hint );
  12025. }
  12026. if ( dispose ) {
  12027. for ( var i in geometry.attributes ) {
  12028. delete geometry.attributes[ i ].array;
  12029. }
  12030. }
  12031. };
  12032. // Buffer rendering
  12033. this.renderBufferImmediate = function ( object, program, material ) {
  12034. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  12035. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  12036. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  12037. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  12038. if ( object.hasPositions ) {
  12039. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  12040. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  12041. _gl.enableVertexAttribArray( program.attributes.position );
  12042. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12043. }
  12044. if ( object.hasNormals ) {
  12045. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  12046. if ( material.shading === THREE.FlatShading ) {
  12047. var nx, ny, nz,
  12048. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  12049. normalArray,
  12050. i, il = object.count * 3;
  12051. for( i = 0; i < il; i += 9 ) {
  12052. normalArray = object.normalArray;
  12053. nax = normalArray[ i ];
  12054. nay = normalArray[ i + 1 ];
  12055. naz = normalArray[ i + 2 ];
  12056. nbx = normalArray[ i + 3 ];
  12057. nby = normalArray[ i + 4 ];
  12058. nbz = normalArray[ i + 5 ];
  12059. ncx = normalArray[ i + 6 ];
  12060. ncy = normalArray[ i + 7 ];
  12061. ncz = normalArray[ i + 8 ];
  12062. nx = ( nax + nbx + ncx ) / 3;
  12063. ny = ( nay + nby + ncy ) / 3;
  12064. nz = ( naz + nbz + ncz ) / 3;
  12065. normalArray[ i ] = nx;
  12066. normalArray[ i + 1 ] = ny;
  12067. normalArray[ i + 2 ] = nz;
  12068. normalArray[ i + 3 ] = nx;
  12069. normalArray[ i + 4 ] = ny;
  12070. normalArray[ i + 5 ] = nz;
  12071. normalArray[ i + 6 ] = nx;
  12072. normalArray[ i + 7 ] = ny;
  12073. normalArray[ i + 8 ] = nz;
  12074. }
  12075. }
  12076. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  12077. _gl.enableVertexAttribArray( program.attributes.normal );
  12078. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12079. }
  12080. if ( object.hasUvs && material.map ) {
  12081. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  12082. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  12083. _gl.enableVertexAttribArray( program.attributes.uv );
  12084. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12085. }
  12086. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  12087. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  12088. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  12089. _gl.enableVertexAttribArray( program.attributes.color );
  12090. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12091. }
  12092. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  12093. object.count = 0;
  12094. };
  12095. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  12096. if ( material.visible === false ) return;
  12097. var program, attributes, linewidth, primitives, a, attribute;
  12098. program = setProgram( camera, lights, fog, material, object );
  12099. attributes = program.attributes;
  12100. var updateBuffers = false,
  12101. wireframeBit = material.wireframe ? 1 : 0,
  12102. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  12103. if ( geometryHash !== _currentGeometryGroupHash ) {
  12104. _currentGeometryGroupHash = geometryHash;
  12105. updateBuffers = true;
  12106. }
  12107. if ( updateBuffers ) {
  12108. disableAttributes();
  12109. }
  12110. // render mesh
  12111. if ( object instanceof THREE.Mesh ) {
  12112. var index = geometry.attributes[ "index" ];
  12113. // indexed triangles
  12114. if ( index ) {
  12115. var offsets = geometry.offsets;
  12116. // if there is more than 1 chunk
  12117. // must set attribute pointers to use new offsets for each chunk
  12118. // even if geometry and materials didn't change
  12119. if ( offsets.length > 1 ) updateBuffers = true;
  12120. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  12121. var startIndex = offsets[ i ].index;
  12122. if ( updateBuffers ) {
  12123. // vertices
  12124. var position = geometry.attributes[ "position" ];
  12125. var positionSize = position.itemSize;
  12126. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12127. enableAttribute( attributes.position );
  12128. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, startIndex * positionSize * 4 ); // 4 bytes per Float32
  12129. // normals
  12130. var normal = geometry.attributes[ "normal" ];
  12131. if ( attributes.normal >= 0 && normal ) {
  12132. var normalSize = normal.itemSize;
  12133. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  12134. enableAttribute( attributes.normal );
  12135. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, startIndex * normalSize * 4 );
  12136. }
  12137. // uvs
  12138. var uv = geometry.attributes[ "uv" ];
  12139. if ( attributes.uv >= 0 && uv ) {
  12140. var uvSize = uv.itemSize;
  12141. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  12142. enableAttribute( attributes.uv );
  12143. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, startIndex * uvSize * 4 );
  12144. }
  12145. // colors
  12146. var color = geometry.attributes[ "color" ];
  12147. if ( attributes.color >= 0 && color ) {
  12148. var colorSize = color.itemSize;
  12149. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12150. enableAttribute( attributes.color );
  12151. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, startIndex * colorSize * 4 );
  12152. }
  12153. // tangents
  12154. var tangent = geometry.attributes[ "tangent" ];
  12155. if ( attributes.tangent >= 0 && tangent ) {
  12156. var tangentSize = tangent.itemSize;
  12157. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  12158. enableAttribute( attributes.tangent );
  12159. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, startIndex * tangentSize * 4 );
  12160. }
  12161. // indices
  12162. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12163. }
  12164. // render indexed triangles
  12165. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  12166. _this.info.render.calls ++;
  12167. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  12168. _this.info.render.faces += offsets[ i ].count / 3;
  12169. }
  12170. // non-indexed triangles
  12171. } else {
  12172. if ( updateBuffers ) {
  12173. // vertices
  12174. var position = geometry.attributes[ "position" ];
  12175. var positionSize = position.itemSize;
  12176. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12177. enableAttribute( attributes.position );
  12178. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  12179. // normals
  12180. var normal = geometry.attributes[ "normal" ];
  12181. if ( attributes.normal >= 0 && normal ) {
  12182. var normalSize = normal.itemSize;
  12183. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  12184. enableAttribute( attributes.normal );
  12185. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, 0 );
  12186. }
  12187. // uvs
  12188. var uv = geometry.attributes[ "uv" ];
  12189. if ( attributes.uv >= 0 && uv ) {
  12190. var uvSize = uv.itemSize;
  12191. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  12192. enableAttribute( attributes.uv );
  12193. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, 0 );
  12194. }
  12195. // colors
  12196. var color = geometry.attributes[ "color" ];
  12197. if ( attributes.color >= 0 && color ) {
  12198. var colorSize = color.itemSize;
  12199. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12200. enableAttribute( attributes.color );
  12201. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  12202. }
  12203. // tangents
  12204. var tangent = geometry.attributes[ "tangent" ];
  12205. if ( attributes.tangent >= 0 && tangent ) {
  12206. var tangentSize = tangent.itemSize;
  12207. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  12208. enableAttribute( attributes.tangent );
  12209. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, 0 );
  12210. }
  12211. }
  12212. // render non-indexed triangles
  12213. _gl.drawArrays( _gl.TRIANGLES, 0, position.numItems / 3 );
  12214. _this.info.render.calls ++;
  12215. _this.info.render.vertices += position.numItems / 3;
  12216. _this.info.render.faces += position.numItems / 3 / 3;
  12217. }
  12218. // render particles
  12219. } else if ( object instanceof THREE.ParticleSystem ) {
  12220. if ( updateBuffers ) {
  12221. // vertices
  12222. var position = geometry.attributes[ "position" ];
  12223. var positionSize = position.itemSize;
  12224. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12225. enableAttribute( attributes.position );
  12226. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  12227. // colors
  12228. var color = geometry.attributes[ "color" ];
  12229. if ( attributes.color >= 0 && color ) {
  12230. var colorSize = color.itemSize;
  12231. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12232. enableAttribute( attributes.color );
  12233. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  12234. }
  12235. // render particles
  12236. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  12237. _this.info.render.calls ++;
  12238. _this.info.render.points += position.numItems / 3;
  12239. }
  12240. } else if ( object instanceof THREE.Line ) {
  12241. if ( updateBuffers ) {
  12242. // vertices
  12243. var position = geometry.attributes[ "position" ];
  12244. var positionSize = position.itemSize;
  12245. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12246. enableAttribute( attributes.position );
  12247. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  12248. // colors
  12249. var color = geometry.attributes[ "color" ];
  12250. if ( attributes.color >= 0 && color ) {
  12251. var colorSize = color.itemSize;
  12252. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12253. enableAttribute( attributes.color );
  12254. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  12255. }
  12256. // render lines
  12257. _gl.drawArrays( _gl.LINE_STRIP, 0, position.numItems / 3 );
  12258. _this.info.render.calls ++;
  12259. _this.info.render.points += position.numItems;
  12260. }
  12261. }
  12262. };
  12263. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  12264. if ( material.visible === false ) return;
  12265. var program, attributes, linewidth, primitives, a, attribute, i, il;
  12266. program = setProgram( camera, lights, fog, material, object );
  12267. attributes = program.attributes;
  12268. var updateBuffers = false,
  12269. wireframeBit = material.wireframe ? 1 : 0,
  12270. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  12271. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  12272. _currentGeometryGroupHash = geometryGroupHash;
  12273. updateBuffers = true;
  12274. }
  12275. if ( updateBuffers ) {
  12276. disableAttributes();
  12277. }
  12278. // vertices
  12279. if ( !material.morphTargets && attributes.position >= 0 ) {
  12280. if ( updateBuffers ) {
  12281. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12282. enableAttribute( attributes.position );
  12283. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12284. }
  12285. } else {
  12286. if ( object.morphTargetBase ) {
  12287. setupMorphTargets( material, geometryGroup, object );
  12288. }
  12289. }
  12290. if ( updateBuffers ) {
  12291. // custom attributes
  12292. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  12293. if ( geometryGroup.__webglCustomAttributesList ) {
  12294. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  12295. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  12296. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  12297. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  12298. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  12299. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  12300. }
  12301. }
  12302. }
  12303. // colors
  12304. if ( attributes.color >= 0 ) {
  12305. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12306. enableAttribute( attributes.color );
  12307. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12308. }
  12309. // normals
  12310. if ( attributes.normal >= 0 ) {
  12311. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12312. enableAttribute( attributes.normal );
  12313. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12314. }
  12315. // tangents
  12316. if ( attributes.tangent >= 0 ) {
  12317. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12318. enableAttribute( attributes.tangent );
  12319. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  12320. }
  12321. // uvs
  12322. if ( attributes.uv >= 0 ) {
  12323. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12324. enableAttribute( attributes.uv );
  12325. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12326. }
  12327. if ( attributes.uv2 >= 0 ) {
  12328. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12329. enableAttribute( attributes.uv2 );
  12330. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  12331. }
  12332. if ( material.skinning &&
  12333. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  12334. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  12335. enableAttribute( attributes.skinIndex );
  12336. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  12337. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  12338. enableAttribute( attributes.skinWeight );
  12339. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  12340. }
  12341. // line distances
  12342. if ( attributes.lineDistance >= 0 ) {
  12343. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  12344. enableAttribute( attributes.lineDistance );
  12345. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  12346. }
  12347. }
  12348. // render mesh
  12349. if ( object instanceof THREE.Mesh ) {
  12350. // wireframe
  12351. if ( material.wireframe ) {
  12352. setLineWidth( material.wireframeLinewidth );
  12353. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  12354. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  12355. // triangles
  12356. } else {
  12357. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12358. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  12359. }
  12360. _this.info.render.calls ++;
  12361. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  12362. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  12363. // render lines
  12364. } else if ( object instanceof THREE.Line ) {
  12365. primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  12366. setLineWidth( material.linewidth );
  12367. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  12368. _this.info.render.calls ++;
  12369. // render particles
  12370. } else if ( object instanceof THREE.ParticleSystem ) {
  12371. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  12372. _this.info.render.calls ++;
  12373. _this.info.render.points += geometryGroup.__webglParticleCount;
  12374. // render ribbon
  12375. } else if ( object instanceof THREE.Ribbon ) {
  12376. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  12377. _this.info.render.calls ++;
  12378. }
  12379. };
  12380. function enableAttribute( attribute ) {
  12381. if ( ! _enabledAttributes[ attribute ] ) {
  12382. _gl.enableVertexAttribArray( attribute );
  12383. _enabledAttributes[ attribute ] = true;
  12384. }
  12385. };
  12386. function disableAttributes() {
  12387. for ( var attribute in _enabledAttributes ) {
  12388. if ( _enabledAttributes[ attribute ] ) {
  12389. _gl.disableVertexAttribArray( attribute );
  12390. _enabledAttributes[ attribute ] = false;
  12391. }
  12392. }
  12393. };
  12394. function setupMorphTargets ( material, geometryGroup, object ) {
  12395. // set base
  12396. var attributes = material.program.attributes;
  12397. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  12398. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  12399. enableAttribute( attributes.position );
  12400. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12401. } else if ( attributes.position >= 0 ) {
  12402. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12403. enableAttribute( attributes.position );
  12404. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12405. }
  12406. if ( object.morphTargetForcedOrder.length ) {
  12407. // set forced order
  12408. var m = 0;
  12409. var order = object.morphTargetForcedOrder;
  12410. var influences = object.morphTargetInfluences;
  12411. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  12412. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  12413. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  12414. enableAttribute( attributes[ "morphTarget" + m ] );
  12415. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12416. }
  12417. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  12418. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  12419. enableAttribute( attributes[ "morphNormal" + m ] );
  12420. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12421. }
  12422. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  12423. m ++;
  12424. }
  12425. } else {
  12426. // find the most influencing
  12427. var influence, activeInfluenceIndices = [];
  12428. var influences = object.morphTargetInfluences;
  12429. var i, il = influences.length;
  12430. for ( i = 0; i < il; i ++ ) {
  12431. influence = influences[ i ];
  12432. if ( influence > 0 ) {
  12433. activeInfluenceIndices.push( [ influence, i ] );
  12434. }
  12435. }
  12436. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  12437. activeInfluenceIndices.sort( numericalSort );
  12438. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  12439. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  12440. activeInfluenceIndices.sort( numericalSort );
  12441. } else if ( activeInfluenceIndices.length === 0 ) {
  12442. activeInfluenceIndices.push( [ 0, 0 ] );
  12443. };
  12444. var influenceIndex, m = 0;
  12445. while ( m < material.numSupportedMorphTargets ) {
  12446. if ( activeInfluenceIndices[ m ] ) {
  12447. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  12448. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  12449. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  12450. enableAttribute( attributes[ "morphTarget" + m ] );
  12451. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12452. }
  12453. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  12454. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  12455. enableAttribute( attributes[ "morphNormal" + m ] );
  12456. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12457. }
  12458. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  12459. } else {
  12460. /*
  12461. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12462. if ( material.morphNormals ) {
  12463. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12464. }
  12465. */
  12466. object.__webglMorphTargetInfluences[ m ] = 0;
  12467. }
  12468. m ++;
  12469. }
  12470. }
  12471. // load updated influences uniform
  12472. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  12473. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  12474. }
  12475. };
  12476. // Sorting
  12477. function painterSortStable ( a, b ) {
  12478. if ( a.z !== b.z ) {
  12479. return b.z - a.z;
  12480. } else {
  12481. return b.id - a.id;
  12482. }
  12483. };
  12484. function numericalSort ( a, b ) {
  12485. return b[ 0 ] - a[ 0 ];
  12486. };
  12487. // Rendering
  12488. this.render = function ( scene, camera, renderTarget, forceClear ) {
  12489. if ( camera instanceof THREE.Camera === false ) {
  12490. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  12491. return;
  12492. }
  12493. var i, il,
  12494. webglObject, object,
  12495. renderList,
  12496. lights = scene.__lights,
  12497. fog = scene.fog;
  12498. // reset caching for this frame
  12499. _currentMaterialId = -1;
  12500. _lightsNeedUpdate = true;
  12501. // update scene graph
  12502. if ( this.autoUpdateScene ) scene.updateMatrixWorld();
  12503. // update camera matrices and frustum
  12504. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  12505. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  12506. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  12507. _frustum.setFromMatrix( _projScreenMatrix );
  12508. // update WebGL objects
  12509. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  12510. // custom render plugins (pre pass)
  12511. renderPlugins( this.renderPluginsPre, scene, camera );
  12512. //
  12513. _this.info.render.calls = 0;
  12514. _this.info.render.vertices = 0;
  12515. _this.info.render.faces = 0;
  12516. _this.info.render.points = 0;
  12517. this.setRenderTarget( renderTarget );
  12518. if ( this.autoClear || forceClear ) {
  12519. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  12520. }
  12521. // set matrices for regular objects (frustum culled)
  12522. renderList = scene.__webglObjects;
  12523. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  12524. webglObject = renderList[ i ];
  12525. object = webglObject.object;
  12526. webglObject.render = false;
  12527. if ( object.visible ) {
  12528. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  12529. setupMatrices( object, camera );
  12530. unrollBufferMaterial( webglObject );
  12531. webglObject.render = true;
  12532. if ( this.sortObjects === true ) {
  12533. if ( object.renderDepth !== null ) {
  12534. webglObject.z = object.renderDepth;
  12535. } else {
  12536. _vector3.copy( object.matrixWorld.getPosition() );
  12537. _vector3.applyMatrix4( _projScreenMatrix );
  12538. webglObject.z = _vector3.z;
  12539. }
  12540. webglObject.id = object.id;
  12541. }
  12542. }
  12543. }
  12544. }
  12545. if ( this.sortObjects ) {
  12546. renderList.sort( painterSortStable );
  12547. }
  12548. // set matrices for immediate objects
  12549. renderList = scene.__webglObjectsImmediate;
  12550. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  12551. webglObject = renderList[ i ];
  12552. object = webglObject.object;
  12553. if ( object.visible ) {
  12554. setupMatrices( object, camera );
  12555. unrollImmediateBufferMaterial( webglObject );
  12556. }
  12557. }
  12558. if ( scene.overrideMaterial ) {
  12559. var material = scene.overrideMaterial;
  12560. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  12561. this.setDepthTest( material.depthTest );
  12562. this.setDepthWrite( material.depthWrite );
  12563. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12564. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  12565. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  12566. } else {
  12567. var material = null;
  12568. // opaque pass (front-to-back order)
  12569. this.setBlending( THREE.NoBlending );
  12570. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  12571. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  12572. // transparent pass (back-to-front order)
  12573. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  12574. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  12575. }
  12576. // custom render plugins (post pass)
  12577. renderPlugins( this.renderPluginsPost, scene, camera );
  12578. // Generate mipmap if we're using any kind of mipmap filtering
  12579. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  12580. updateRenderTargetMipmap( renderTarget );
  12581. }
  12582. // Ensure depth buffer writing is enabled so it can be cleared on next render
  12583. this.setDepthTest( true );
  12584. this.setDepthWrite( true );
  12585. // _gl.finish();
  12586. };
  12587. function renderPlugins( plugins, scene, camera ) {
  12588. if ( ! plugins.length ) return;
  12589. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  12590. // reset state for plugin (to start from clean slate)
  12591. _currentProgram = null;
  12592. _currentCamera = null;
  12593. _oldBlending = -1;
  12594. _oldDepthTest = -1;
  12595. _oldDepthWrite = -1;
  12596. _oldDoubleSided = -1;
  12597. _oldFlipSided = -1;
  12598. _currentGeometryGroupHash = -1;
  12599. _currentMaterialId = -1;
  12600. _lightsNeedUpdate = true;
  12601. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  12602. // reset state after plugin (anything could have changed)
  12603. _currentProgram = null;
  12604. _currentCamera = null;
  12605. _oldBlending = -1;
  12606. _oldDepthTest = -1;
  12607. _oldDepthWrite = -1;
  12608. _oldDoubleSided = -1;
  12609. _oldFlipSided = -1;
  12610. _currentGeometryGroupHash = -1;
  12611. _currentMaterialId = -1;
  12612. _lightsNeedUpdate = true;
  12613. }
  12614. };
  12615. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  12616. var webglObject, object, buffer, material, start, end, delta;
  12617. if ( reverse ) {
  12618. start = renderList.length - 1;
  12619. end = -1;
  12620. delta = -1;
  12621. } else {
  12622. start = 0;
  12623. end = renderList.length;
  12624. delta = 1;
  12625. }
  12626. for ( var i = start; i !== end; i += delta ) {
  12627. webglObject = renderList[ i ];
  12628. if ( webglObject.render ) {
  12629. object = webglObject.object;
  12630. buffer = webglObject.buffer;
  12631. if ( overrideMaterial ) {
  12632. material = overrideMaterial;
  12633. } else {
  12634. material = webglObject[ materialType ];
  12635. if ( ! material ) continue;
  12636. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  12637. _this.setDepthTest( material.depthTest );
  12638. _this.setDepthWrite( material.depthWrite );
  12639. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12640. }
  12641. _this.setMaterialFaces( material );
  12642. if ( buffer instanceof THREE.BufferGeometry ) {
  12643. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  12644. } else {
  12645. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  12646. }
  12647. }
  12648. }
  12649. };
  12650. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  12651. var webglObject, object, material, program;
  12652. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  12653. webglObject = renderList[ i ];
  12654. object = webglObject.object;
  12655. if ( object.visible ) {
  12656. if ( overrideMaterial ) {
  12657. material = overrideMaterial;
  12658. } else {
  12659. material = webglObject[ materialType ];
  12660. if ( ! material ) continue;
  12661. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  12662. _this.setDepthTest( material.depthTest );
  12663. _this.setDepthWrite( material.depthWrite );
  12664. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12665. }
  12666. _this.renderImmediateObject( camera, lights, fog, material, object );
  12667. }
  12668. }
  12669. };
  12670. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  12671. var program = setProgram( camera, lights, fog, material, object );
  12672. _currentGeometryGroupHash = -1;
  12673. _this.setMaterialFaces( material );
  12674. if ( object.immediateRenderCallback ) {
  12675. object.immediateRenderCallback( program, _gl, _frustum );
  12676. } else {
  12677. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  12678. }
  12679. };
  12680. function unrollImmediateBufferMaterial ( globject ) {
  12681. var object = globject.object,
  12682. material = object.material;
  12683. if ( material.transparent ) {
  12684. globject.transparent = material;
  12685. globject.opaque = null;
  12686. } else {
  12687. globject.opaque = material;
  12688. globject.transparent = null;
  12689. }
  12690. };
  12691. function unrollBufferMaterial ( globject ) {
  12692. var object = globject.object,
  12693. buffer = globject.buffer,
  12694. material, materialIndex, meshMaterial;
  12695. meshMaterial = object.material;
  12696. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  12697. materialIndex = buffer.materialIndex;
  12698. material = meshMaterial.materials[ materialIndex ];
  12699. if ( material.transparent ) {
  12700. globject.transparent = material;
  12701. globject.opaque = null;
  12702. } else {
  12703. globject.opaque = material;
  12704. globject.transparent = null;
  12705. }
  12706. } else {
  12707. material = meshMaterial;
  12708. if ( material ) {
  12709. if ( material.transparent ) {
  12710. globject.transparent = material;
  12711. globject.opaque = null;
  12712. } else {
  12713. globject.opaque = material;
  12714. globject.transparent = null;
  12715. }
  12716. }
  12717. }
  12718. };
  12719. // Geometry splitting
  12720. function sortFacesByMaterial ( geometry, material ) {
  12721. var f, fl, face, materialIndex, vertices,
  12722. groupHash, hash_map = {};
  12723. var numMorphTargets = geometry.morphTargets.length;
  12724. var numMorphNormals = geometry.morphNormals.length;
  12725. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  12726. geometry.geometryGroups = {};
  12727. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  12728. face = geometry.faces[ f ];
  12729. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  12730. if ( hash_map[ materialIndex ] === undefined ) {
  12731. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  12732. }
  12733. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  12734. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  12735. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  12736. }
  12737. vertices = face instanceof THREE.Face3 ? 3 : 4;
  12738. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  12739. hash_map[ materialIndex ].counter += 1;
  12740. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  12741. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  12742. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  12743. }
  12744. }
  12745. if ( face instanceof THREE.Face3 ) {
  12746. geometry.geometryGroups[ groupHash ].faces3.push( f );
  12747. } else {
  12748. geometry.geometryGroups[ groupHash ].faces4.push( f );
  12749. }
  12750. geometry.geometryGroups[ groupHash ].vertices += vertices;
  12751. }
  12752. geometry.geometryGroupsList = [];
  12753. for ( var g in geometry.geometryGroups ) {
  12754. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  12755. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  12756. }
  12757. };
  12758. // Objects refresh
  12759. this.initWebGLObjects = function ( scene ) {
  12760. if ( !scene.__webglObjects ) {
  12761. scene.__webglObjects = [];
  12762. scene.__webglObjectsImmediate = [];
  12763. scene.__webglSprites = [];
  12764. scene.__webglFlares = [];
  12765. }
  12766. while ( scene.__objectsAdded.length ) {
  12767. addObject( scene.__objectsAdded[ 0 ], scene );
  12768. scene.__objectsAdded.splice( 0, 1 );
  12769. }
  12770. while ( scene.__objectsRemoved.length ) {
  12771. removeObject( scene.__objectsRemoved[ 0 ], scene );
  12772. scene.__objectsRemoved.splice( 0, 1 );
  12773. }
  12774. // update must be called after objects adding / removal
  12775. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  12776. updateObject( scene.__webglObjects[ o ].object );
  12777. }
  12778. };
  12779. // Objects adding
  12780. function addObject ( object, scene ) {
  12781. var g, geometry, material, geometryGroup;
  12782. if ( ! object.__webglInit ) {
  12783. object.__webglInit = true;
  12784. object._modelViewMatrix = new THREE.Matrix4();
  12785. object._normalMatrix = new THREE.Matrix3();
  12786. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  12787. object.geometry.__webglInit = true;
  12788. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  12789. }
  12790. if ( object instanceof THREE.Mesh ) {
  12791. geometry = object.geometry;
  12792. material = object.material;
  12793. if ( geometry instanceof THREE.Geometry ) {
  12794. if ( geometry.geometryGroups === undefined ) {
  12795. sortFacesByMaterial( geometry, material );
  12796. }
  12797. // create separate VBOs per geometry chunk
  12798. for ( g in geometry.geometryGroups ) {
  12799. geometryGroup = geometry.geometryGroups[ g ];
  12800. // initialise VBO on the first access
  12801. if ( ! geometryGroup.__webglVertexBuffer ) {
  12802. createMeshBuffers( geometryGroup );
  12803. initMeshBuffers( geometryGroup, object );
  12804. geometry.verticesNeedUpdate = true;
  12805. geometry.morphTargetsNeedUpdate = true;
  12806. geometry.elementsNeedUpdate = true;
  12807. geometry.uvsNeedUpdate = true;
  12808. geometry.normalsNeedUpdate = true;
  12809. geometry.tangentsNeedUpdate = true;
  12810. geometry.colorsNeedUpdate = true;
  12811. }
  12812. }
  12813. } else if ( geometry instanceof THREE.BufferGeometry ) {
  12814. initDirectBuffers( geometry );
  12815. }
  12816. } else if ( object instanceof THREE.Ribbon ) {
  12817. geometry = object.geometry;
  12818. if ( ! geometry.__webglVertexBuffer ) {
  12819. createRibbonBuffers( geometry );
  12820. initRibbonBuffers( geometry, object );
  12821. geometry.verticesNeedUpdate = true;
  12822. geometry.colorsNeedUpdate = true;
  12823. geometry.normalsNeedUpdate = true;
  12824. }
  12825. } else if ( object instanceof THREE.Line ) {
  12826. geometry = object.geometry;
  12827. if ( ! geometry.__webglVertexBuffer ) {
  12828. if ( geometry instanceof THREE.Geometry ) {
  12829. createLineBuffers( geometry );
  12830. initLineBuffers( geometry, object );
  12831. geometry.verticesNeedUpdate = true;
  12832. geometry.colorsNeedUpdate = true;
  12833. geometry.lineDistancesNeedUpdate = true;
  12834. } else if ( geometry instanceof THREE.BufferGeometry ) {
  12835. initDirectBuffers( geometry );
  12836. }
  12837. }
  12838. } else if ( object instanceof THREE.ParticleSystem ) {
  12839. geometry = object.geometry;
  12840. if ( ! geometry.__webglVertexBuffer ) {
  12841. if ( geometry instanceof THREE.Geometry ) {
  12842. createParticleBuffers( geometry );
  12843. initParticleBuffers( geometry, object );
  12844. geometry.verticesNeedUpdate = true;
  12845. geometry.colorsNeedUpdate = true;
  12846. } else if ( geometry instanceof THREE.BufferGeometry ) {
  12847. initDirectBuffers( geometry );
  12848. }
  12849. }
  12850. }
  12851. }
  12852. if ( ! object.__webglActive ) {
  12853. if ( object instanceof THREE.Mesh ) {
  12854. geometry = object.geometry;
  12855. if ( geometry instanceof THREE.BufferGeometry ) {
  12856. addBuffer( scene.__webglObjects, geometry, object );
  12857. } else if ( geometry instanceof THREE.Geometry ) {
  12858. for ( g in geometry.geometryGroups ) {
  12859. geometryGroup = geometry.geometryGroups[ g ];
  12860. addBuffer( scene.__webglObjects, geometryGroup, object );
  12861. }
  12862. }
  12863. } else if ( object instanceof THREE.Ribbon ||
  12864. object instanceof THREE.Line ||
  12865. object instanceof THREE.ParticleSystem ) {
  12866. geometry = object.geometry;
  12867. addBuffer( scene.__webglObjects, geometry, object );
  12868. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  12869. addBufferImmediate( scene.__webglObjectsImmediate, object );
  12870. } else if ( object instanceof THREE.Sprite ) {
  12871. scene.__webglSprites.push( object );
  12872. } else if ( object instanceof THREE.LensFlare ) {
  12873. scene.__webglFlares.push( object );
  12874. }
  12875. object.__webglActive = true;
  12876. }
  12877. };
  12878. function addBuffer ( objlist, buffer, object ) {
  12879. objlist.push(
  12880. {
  12881. buffer: buffer,
  12882. object: object,
  12883. opaque: null,
  12884. transparent: null
  12885. }
  12886. );
  12887. };
  12888. function addBufferImmediate ( objlist, object ) {
  12889. objlist.push(
  12890. {
  12891. object: object,
  12892. opaque: null,
  12893. transparent: null
  12894. }
  12895. );
  12896. };
  12897. // Objects updates
  12898. function updateObject ( object ) {
  12899. var geometry = object.geometry,
  12900. geometryGroup, customAttributesDirty, material;
  12901. if ( object instanceof THREE.Mesh ) {
  12902. if ( geometry instanceof THREE.BufferGeometry ) {
  12903. if ( geometry.verticesNeedUpdate || geometry.elementsNeedUpdate ||
  12904. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  12905. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate ) {
  12906. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  12907. }
  12908. geometry.verticesNeedUpdate = false;
  12909. geometry.elementsNeedUpdate = false;
  12910. geometry.uvsNeedUpdate = false;
  12911. geometry.normalsNeedUpdate = false;
  12912. geometry.colorsNeedUpdate = false;
  12913. geometry.tangentsNeedUpdate = false;
  12914. } else {
  12915. // check all geometry groups
  12916. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  12917. geometryGroup = geometry.geometryGroupsList[ i ];
  12918. material = getBufferMaterial( object, geometryGroup );
  12919. if ( geometry.buffersNeedUpdate ) {
  12920. initMeshBuffers( geometryGroup, object );
  12921. }
  12922. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12923. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  12924. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  12925. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  12926. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  12927. }
  12928. }
  12929. geometry.verticesNeedUpdate = false;
  12930. geometry.morphTargetsNeedUpdate = false;
  12931. geometry.elementsNeedUpdate = false;
  12932. geometry.uvsNeedUpdate = false;
  12933. geometry.normalsNeedUpdate = false;
  12934. geometry.colorsNeedUpdate = false;
  12935. geometry.tangentsNeedUpdate = false;
  12936. geometry.buffersNeedUpdate = false;
  12937. material.attributes && clearCustomAttributes( material );
  12938. }
  12939. } else if ( object instanceof THREE.Ribbon ) {
  12940. material = getBufferMaterial( object, geometry );
  12941. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12942. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.normalsNeedUpdate || customAttributesDirty ) {
  12943. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  12944. }
  12945. geometry.verticesNeedUpdate = false;
  12946. geometry.colorsNeedUpdate = false;
  12947. geometry.normalsNeedUpdate = false;
  12948. material.attributes && clearCustomAttributes( material );
  12949. } else if ( object instanceof THREE.Line ) {
  12950. if ( geometry instanceof THREE.BufferGeometry ) {
  12951. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  12952. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  12953. }
  12954. geometry.verticesNeedUpdate = false;
  12955. geometry.colorsNeedUpdate = false;
  12956. } else {
  12957. material = getBufferMaterial( object, geometry );
  12958. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12959. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  12960. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  12961. }
  12962. geometry.verticesNeedUpdate = false;
  12963. geometry.colorsNeedUpdate = false;
  12964. geometry.lineDistancesNeedUpdate = false;
  12965. material.attributes && clearCustomAttributes( material );
  12966. }
  12967. } else if ( object instanceof THREE.ParticleSystem ) {
  12968. if ( geometry instanceof THREE.BufferGeometry ) {
  12969. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  12970. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  12971. }
  12972. geometry.verticesNeedUpdate = false;
  12973. geometry.colorsNeedUpdate = false;
  12974. } else {
  12975. material = getBufferMaterial( object, geometry );
  12976. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12977. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  12978. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  12979. }
  12980. geometry.verticesNeedUpdate = false;
  12981. geometry.colorsNeedUpdate = false;
  12982. material.attributes && clearCustomAttributes( material );
  12983. }
  12984. }
  12985. };
  12986. // Objects updates - custom attributes check
  12987. function areCustomAttributesDirty ( material ) {
  12988. for ( var a in material.attributes ) {
  12989. if ( material.attributes[ a ].needsUpdate ) return true;
  12990. }
  12991. return false;
  12992. };
  12993. function clearCustomAttributes ( material ) {
  12994. for ( var a in material.attributes ) {
  12995. material.attributes[ a ].needsUpdate = false;
  12996. }
  12997. };
  12998. // Objects removal
  12999. function removeObject ( object, scene ) {
  13000. if ( object instanceof THREE.Mesh ||
  13001. object instanceof THREE.ParticleSystem ||
  13002. object instanceof THREE.Ribbon ||
  13003. object instanceof THREE.Line ) {
  13004. removeInstances( scene.__webglObjects, object );
  13005. } else if ( object instanceof THREE.Sprite ) {
  13006. removeInstancesDirect( scene.__webglSprites, object );
  13007. } else if ( object instanceof THREE.LensFlare ) {
  13008. removeInstancesDirect( scene.__webglFlares, object );
  13009. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13010. removeInstances( scene.__webglObjectsImmediate, object );
  13011. }
  13012. object.__webglActive = false;
  13013. };
  13014. function removeInstances ( objlist, object ) {
  13015. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13016. if ( objlist[ o ].object === object ) {
  13017. objlist.splice( o, 1 );
  13018. }
  13019. }
  13020. };
  13021. function removeInstancesDirect ( objlist, object ) {
  13022. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13023. if ( objlist[ o ] === object ) {
  13024. objlist.splice( o, 1 );
  13025. }
  13026. }
  13027. };
  13028. // Materials
  13029. this.initMaterial = function ( material, lights, fog, object ) {
  13030. material.addEventListener( 'dispose', onMaterialDispose );
  13031. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  13032. if ( material instanceof THREE.MeshDepthMaterial ) {
  13033. shaderID = 'depth';
  13034. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13035. shaderID = 'normal';
  13036. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  13037. shaderID = 'basic';
  13038. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13039. shaderID = 'lambert';
  13040. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13041. shaderID = 'phong';
  13042. } else if ( material instanceof THREE.LineBasicMaterial ) {
  13043. shaderID = 'basic';
  13044. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13045. shaderID = 'dashed';
  13046. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  13047. shaderID = 'particle_basic';
  13048. }
  13049. if ( shaderID ) {
  13050. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  13051. }
  13052. // heuristics to create shader parameters according to lights in the scene
  13053. // (not to blow over maxLights budget)
  13054. maxLightCount = allocateLights( lights );
  13055. maxShadows = allocateShadows( lights );
  13056. maxBones = allocateBones( object );
  13057. parameters = {
  13058. map: !!material.map,
  13059. envMap: !!material.envMap,
  13060. lightMap: !!material.lightMap,
  13061. bumpMap: !!material.bumpMap,
  13062. normalMap: !!material.normalMap,
  13063. specularMap: !!material.specularMap,
  13064. vertexColors: material.vertexColors,
  13065. fog: fog,
  13066. useFog: material.fog,
  13067. fogExp: fog instanceof THREE.FogExp2,
  13068. sizeAttenuation: material.sizeAttenuation,
  13069. skinning: material.skinning,
  13070. maxBones: maxBones,
  13071. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  13072. boneTextureWidth: object && object.boneTextureWidth,
  13073. boneTextureHeight: object && object.boneTextureHeight,
  13074. morphTargets: material.morphTargets,
  13075. morphNormals: material.morphNormals,
  13076. maxMorphTargets: this.maxMorphTargets,
  13077. maxMorphNormals: this.maxMorphNormals,
  13078. maxDirLights: maxLightCount.directional,
  13079. maxPointLights: maxLightCount.point,
  13080. maxSpotLights: maxLightCount.spot,
  13081. maxHemiLights: maxLightCount.hemi,
  13082. maxShadows: maxShadows,
  13083. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  13084. shadowMapType: this.shadowMapType,
  13085. shadowMapDebug: this.shadowMapDebug,
  13086. shadowMapCascade: this.shadowMapCascade,
  13087. alphaTest: material.alphaTest,
  13088. metal: material.metal,
  13089. perPixel: material.perPixel,
  13090. wrapAround: material.wrapAround,
  13091. doubleSided: material.side === THREE.DoubleSide,
  13092. flipSided: material.side === THREE.BackSide
  13093. };
  13094. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters );
  13095. var attributes = material.program.attributes;
  13096. if ( material.morphTargets ) {
  13097. material.numSupportedMorphTargets = 0;
  13098. var id, base = "morphTarget";
  13099. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  13100. id = base + i;
  13101. if ( attributes[ id ] >= 0 ) {
  13102. material.numSupportedMorphTargets ++;
  13103. }
  13104. }
  13105. }
  13106. if ( material.morphNormals ) {
  13107. material.numSupportedMorphNormals = 0;
  13108. var id, base = "morphNormal";
  13109. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  13110. id = base + i;
  13111. if ( attributes[ id ] >= 0 ) {
  13112. material.numSupportedMorphNormals ++;
  13113. }
  13114. }
  13115. }
  13116. material.uniformsList = [];
  13117. for ( u in material.uniforms ) {
  13118. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  13119. }
  13120. };
  13121. function setMaterialShaders( material, shaders ) {
  13122. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  13123. material.vertexShader = shaders.vertexShader;
  13124. material.fragmentShader = shaders.fragmentShader;
  13125. };
  13126. function setProgram( camera, lights, fog, material, object ) {
  13127. _usedTextureUnits = 0;
  13128. if ( material.needsUpdate ) {
  13129. if ( material.program ) deallocateMaterial( material );
  13130. _this.initMaterial( material, lights, fog, object );
  13131. material.needsUpdate = false;
  13132. }
  13133. if ( material.morphTargets ) {
  13134. if ( ! object.__webglMorphTargetInfluences ) {
  13135. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  13136. }
  13137. }
  13138. var refreshMaterial = false;
  13139. var program = material.program,
  13140. p_uniforms = program.uniforms,
  13141. m_uniforms = material.uniforms;
  13142. if ( program !== _currentProgram ) {
  13143. _gl.useProgram( program );
  13144. _currentProgram = program;
  13145. refreshMaterial = true;
  13146. }
  13147. if ( material.id !== _currentMaterialId ) {
  13148. _currentMaterialId = material.id;
  13149. refreshMaterial = true;
  13150. }
  13151. if ( refreshMaterial || camera !== _currentCamera ) {
  13152. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  13153. if ( camera !== _currentCamera ) _currentCamera = camera;
  13154. }
  13155. // skinning uniforms must be set even if material didn't change
  13156. // auto-setting of texture unit for bone texture must go before other textures
  13157. // not sure why, but otherwise weird things happen
  13158. if ( material.skinning ) {
  13159. if ( _supportsBoneTextures && object.useVertexTexture ) {
  13160. if ( p_uniforms.boneTexture !== null ) {
  13161. var textureUnit = getTextureUnit();
  13162. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  13163. _this.setTexture( object.boneTexture, textureUnit );
  13164. }
  13165. } else {
  13166. if ( p_uniforms.boneGlobalMatrices !== null ) {
  13167. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  13168. }
  13169. }
  13170. }
  13171. if ( refreshMaterial ) {
  13172. // refresh uniforms common to several materials
  13173. if ( fog && material.fog ) {
  13174. refreshUniformsFog( m_uniforms, fog );
  13175. }
  13176. if ( material instanceof THREE.MeshPhongMaterial ||
  13177. material instanceof THREE.MeshLambertMaterial ||
  13178. material.lights ) {
  13179. if ( _lightsNeedUpdate ) {
  13180. setupLights( program, lights );
  13181. _lightsNeedUpdate = false;
  13182. }
  13183. refreshUniformsLights( m_uniforms, _lights );
  13184. }
  13185. if ( material instanceof THREE.MeshBasicMaterial ||
  13186. material instanceof THREE.MeshLambertMaterial ||
  13187. material instanceof THREE.MeshPhongMaterial ) {
  13188. refreshUniformsCommon( m_uniforms, material );
  13189. }
  13190. // refresh single material specific uniforms
  13191. if ( material instanceof THREE.LineBasicMaterial ) {
  13192. refreshUniformsLine( m_uniforms, material );
  13193. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13194. refreshUniformsLine( m_uniforms, material );
  13195. refreshUniformsDash( m_uniforms, material );
  13196. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  13197. refreshUniformsParticle( m_uniforms, material );
  13198. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13199. refreshUniformsPhong( m_uniforms, material );
  13200. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13201. refreshUniformsLambert( m_uniforms, material );
  13202. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  13203. m_uniforms.mNear.value = camera.near;
  13204. m_uniforms.mFar.value = camera.far;
  13205. m_uniforms.opacity.value = material.opacity;
  13206. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13207. m_uniforms.opacity.value = material.opacity;
  13208. }
  13209. if ( object.receiveShadow && ! material._shadowPass ) {
  13210. refreshUniformsShadow( m_uniforms, lights );
  13211. }
  13212. // load common uniforms
  13213. loadUniformsGeneric( program, material.uniformsList );
  13214. // load material specific uniforms
  13215. // (shader material also gets them for the sake of genericity)
  13216. if ( material instanceof THREE.ShaderMaterial ||
  13217. material instanceof THREE.MeshPhongMaterial ||
  13218. material.envMap ) {
  13219. if ( p_uniforms.cameraPosition !== null ) {
  13220. var position = camera.matrixWorld.getPosition();
  13221. _gl.uniform3f( p_uniforms.cameraPosition, position.x, position.y, position.z );
  13222. }
  13223. }
  13224. if ( material instanceof THREE.MeshPhongMaterial ||
  13225. material instanceof THREE.MeshLambertMaterial ||
  13226. material instanceof THREE.ShaderMaterial ||
  13227. material.skinning ) {
  13228. if ( p_uniforms.viewMatrix !== null ) {
  13229. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  13230. }
  13231. }
  13232. }
  13233. loadUniformsMatrices( p_uniforms, object );
  13234. if ( p_uniforms.modelMatrix !== null ) {
  13235. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  13236. }
  13237. return program;
  13238. };
  13239. // Uniforms (refresh uniforms objects)
  13240. function refreshUniformsCommon ( uniforms, material ) {
  13241. uniforms.opacity.value = material.opacity;
  13242. if ( _this.gammaInput ) {
  13243. uniforms.diffuse.value.copyGammaToLinear( material.color );
  13244. } else {
  13245. uniforms.diffuse.value = material.color;
  13246. }
  13247. uniforms.map.value = material.map;
  13248. uniforms.lightMap.value = material.lightMap;
  13249. uniforms.specularMap.value = material.specularMap;
  13250. if ( material.bumpMap ) {
  13251. uniforms.bumpMap.value = material.bumpMap;
  13252. uniforms.bumpScale.value = material.bumpScale;
  13253. }
  13254. if ( material.normalMap ) {
  13255. uniforms.normalMap.value = material.normalMap;
  13256. uniforms.normalScale.value.copy( material.normalScale );
  13257. }
  13258. // uv repeat and offset setting priorities
  13259. // 1. color map
  13260. // 2. specular map
  13261. // 3. normal map
  13262. // 4. bump map
  13263. var uvScaleMap;
  13264. if ( material.map ) {
  13265. uvScaleMap = material.map;
  13266. } else if ( material.specularMap ) {
  13267. uvScaleMap = material.specularMap;
  13268. } else if ( material.normalMap ) {
  13269. uvScaleMap = material.normalMap;
  13270. } else if ( material.bumpMap ) {
  13271. uvScaleMap = material.bumpMap;
  13272. }
  13273. if ( uvScaleMap !== undefined ) {
  13274. var offset = uvScaleMap.offset;
  13275. var repeat = uvScaleMap.repeat;
  13276. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  13277. }
  13278. uniforms.envMap.value = material.envMap;
  13279. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  13280. if ( _this.gammaInput ) {
  13281. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  13282. uniforms.reflectivity.value = material.reflectivity;
  13283. } else {
  13284. uniforms.reflectivity.value = material.reflectivity;
  13285. }
  13286. uniforms.refractionRatio.value = material.refractionRatio;
  13287. uniforms.combine.value = material.combine;
  13288. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  13289. };
  13290. function refreshUniformsLine ( uniforms, material ) {
  13291. uniforms.diffuse.value = material.color;
  13292. uniforms.opacity.value = material.opacity;
  13293. };
  13294. function refreshUniformsDash ( uniforms, material ) {
  13295. uniforms.dashSize.value = material.dashSize;
  13296. uniforms.totalSize.value = material.dashSize + material.gapSize;
  13297. uniforms.scale.value = material.scale;
  13298. };
  13299. function refreshUniformsParticle ( uniforms, material ) {
  13300. uniforms.psColor.value = material.color;
  13301. uniforms.opacity.value = material.opacity;
  13302. uniforms.size.value = material.size;
  13303. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  13304. uniforms.map.value = material.map;
  13305. };
  13306. function refreshUniformsFog ( uniforms, fog ) {
  13307. uniforms.fogColor.value = fog.color;
  13308. if ( fog instanceof THREE.Fog ) {
  13309. uniforms.fogNear.value = fog.near;
  13310. uniforms.fogFar.value = fog.far;
  13311. } else if ( fog instanceof THREE.FogExp2 ) {
  13312. uniforms.fogDensity.value = fog.density;
  13313. }
  13314. };
  13315. function refreshUniformsPhong ( uniforms, material ) {
  13316. uniforms.shininess.value = material.shininess;
  13317. if ( _this.gammaInput ) {
  13318. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  13319. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  13320. uniforms.specular.value.copyGammaToLinear( material.specular );
  13321. } else {
  13322. uniforms.ambient.value = material.ambient;
  13323. uniforms.emissive.value = material.emissive;
  13324. uniforms.specular.value = material.specular;
  13325. }
  13326. if ( material.wrapAround ) {
  13327. uniforms.wrapRGB.value.copy( material.wrapRGB );
  13328. }
  13329. };
  13330. function refreshUniformsLambert ( uniforms, material ) {
  13331. if ( _this.gammaInput ) {
  13332. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  13333. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  13334. } else {
  13335. uniforms.ambient.value = material.ambient;
  13336. uniforms.emissive.value = material.emissive;
  13337. }
  13338. if ( material.wrapAround ) {
  13339. uniforms.wrapRGB.value.copy( material.wrapRGB );
  13340. }
  13341. };
  13342. function refreshUniformsLights ( uniforms, lights ) {
  13343. uniforms.ambientLightColor.value = lights.ambient;
  13344. uniforms.directionalLightColor.value = lights.directional.colors;
  13345. uniforms.directionalLightDirection.value = lights.directional.positions;
  13346. uniforms.pointLightColor.value = lights.point.colors;
  13347. uniforms.pointLightPosition.value = lights.point.positions;
  13348. uniforms.pointLightDistance.value = lights.point.distances;
  13349. uniforms.spotLightColor.value = lights.spot.colors;
  13350. uniforms.spotLightPosition.value = lights.spot.positions;
  13351. uniforms.spotLightDistance.value = lights.spot.distances;
  13352. uniforms.spotLightDirection.value = lights.spot.directions;
  13353. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  13354. uniforms.spotLightExponent.value = lights.spot.exponents;
  13355. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  13356. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  13357. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  13358. };
  13359. function refreshUniformsShadow ( uniforms, lights ) {
  13360. if ( uniforms.shadowMatrix ) {
  13361. var j = 0;
  13362. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  13363. var light = lights[ i ];
  13364. if ( ! light.castShadow ) continue;
  13365. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  13366. uniforms.shadowMap.value[ j ] = light.shadowMap;
  13367. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  13368. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  13369. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  13370. uniforms.shadowBias.value[ j ] = light.shadowBias;
  13371. j ++;
  13372. }
  13373. }
  13374. }
  13375. };
  13376. // Uniforms (load to GPU)
  13377. function loadUniformsMatrices ( uniforms, object ) {
  13378. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  13379. if ( uniforms.normalMatrix ) {
  13380. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  13381. }
  13382. };
  13383. function getTextureUnit() {
  13384. var textureUnit = _usedTextureUnits;
  13385. if ( textureUnit >= _maxTextures ) {
  13386. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  13387. }
  13388. _usedTextureUnits += 1;
  13389. return textureUnit;
  13390. };
  13391. function loadUniformsGeneric ( program, uniforms ) {
  13392. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  13393. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  13394. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  13395. if ( !location ) continue;
  13396. uniform = uniforms[ j ][ 0 ];
  13397. type = uniform.type;
  13398. value = uniform.value;
  13399. if ( type === "i" ) { // single integer
  13400. _gl.uniform1i( location, value );
  13401. } else if ( type === "f" ) { // single float
  13402. _gl.uniform1f( location, value );
  13403. } else if ( type === "v2" ) { // single THREE.Vector2
  13404. _gl.uniform2f( location, value.x, value.y );
  13405. } else if ( type === "v3" ) { // single THREE.Vector3
  13406. _gl.uniform3f( location, value.x, value.y, value.z );
  13407. } else if ( type === "v4" ) { // single THREE.Vector4
  13408. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  13409. } else if ( type === "c" ) { // single THREE.Color
  13410. _gl.uniform3f( location, value.r, value.g, value.b );
  13411. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  13412. _gl.uniform1iv( location, value );
  13413. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  13414. _gl.uniform3iv( location, value );
  13415. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  13416. _gl.uniform1fv( location, value );
  13417. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  13418. _gl.uniform3fv( location, value );
  13419. } else if ( type === "v2v" ) { // array of THREE.Vector2
  13420. if ( uniform._array === undefined ) {
  13421. uniform._array = new Float32Array( 2 * value.length );
  13422. }
  13423. for ( i = 0, il = value.length; i < il; i ++ ) {
  13424. offset = i * 2;
  13425. uniform._array[ offset ] = value[ i ].x;
  13426. uniform._array[ offset + 1 ] = value[ i ].y;
  13427. }
  13428. _gl.uniform2fv( location, uniform._array );
  13429. } else if ( type === "v3v" ) { // array of THREE.Vector3
  13430. if ( uniform._array === undefined ) {
  13431. uniform._array = new Float32Array( 3 * value.length );
  13432. }
  13433. for ( i = 0, il = value.length; i < il; i ++ ) {
  13434. offset = i * 3;
  13435. uniform._array[ offset ] = value[ i ].x;
  13436. uniform._array[ offset + 1 ] = value[ i ].y;
  13437. uniform._array[ offset + 2 ] = value[ i ].z;
  13438. }
  13439. _gl.uniform3fv( location, uniform._array );
  13440. } else if ( type === "v4v" ) { // array of THREE.Vector4
  13441. if ( uniform._array === undefined ) {
  13442. uniform._array = new Float32Array( 4 * value.length );
  13443. }
  13444. for ( i = 0, il = value.length; i < il; i ++ ) {
  13445. offset = i * 4;
  13446. uniform._array[ offset ] = value[ i ].x;
  13447. uniform._array[ offset + 1 ] = value[ i ].y;
  13448. uniform._array[ offset + 2 ] = value[ i ].z;
  13449. uniform._array[ offset + 3 ] = value[ i ].w;
  13450. }
  13451. _gl.uniform4fv( location, uniform._array );
  13452. } else if ( type === "m4") { // single THREE.Matrix4
  13453. if ( uniform._array === undefined ) {
  13454. uniform._array = new Float32Array( 16 );
  13455. }
  13456. value.flattenToArray( uniform._array );
  13457. _gl.uniformMatrix4fv( location, false, uniform._array );
  13458. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  13459. if ( uniform._array === undefined ) {
  13460. uniform._array = new Float32Array( 16 * value.length );
  13461. }
  13462. for ( i = 0, il = value.length; i < il; i ++ ) {
  13463. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  13464. }
  13465. _gl.uniformMatrix4fv( location, false, uniform._array );
  13466. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  13467. texture = value;
  13468. textureUnit = getTextureUnit();
  13469. _gl.uniform1i( location, textureUnit );
  13470. if ( !texture ) continue;
  13471. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  13472. setCubeTexture( texture, textureUnit );
  13473. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  13474. setCubeTextureDynamic( texture, textureUnit );
  13475. } else {
  13476. _this.setTexture( texture, textureUnit );
  13477. }
  13478. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  13479. if ( uniform._array === undefined ) {
  13480. uniform._array = [];
  13481. }
  13482. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  13483. uniform._array[ i ] = getTextureUnit();
  13484. }
  13485. _gl.uniform1iv( location, uniform._array );
  13486. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  13487. texture = uniform.value[ i ];
  13488. textureUnit = uniform._array[ i ];
  13489. if ( !texture ) continue;
  13490. _this.setTexture( texture, textureUnit );
  13491. }
  13492. }
  13493. }
  13494. };
  13495. function setupMatrices ( object, camera ) {
  13496. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  13497. object._normalMatrix.getInverse( object._modelViewMatrix );
  13498. object._normalMatrix.transpose();
  13499. };
  13500. //
  13501. function setColorGamma( array, offset, color, intensitySq ) {
  13502. array[ offset ] = color.r * color.r * intensitySq;
  13503. array[ offset + 1 ] = color.g * color.g * intensitySq;
  13504. array[ offset + 2 ] = color.b * color.b * intensitySq;
  13505. };
  13506. function setColorLinear( array, offset, color, intensity ) {
  13507. array[ offset ] = color.r * intensity;
  13508. array[ offset + 1 ] = color.g * intensity;
  13509. array[ offset + 2 ] = color.b * intensity;
  13510. };
  13511. function setupLights ( program, lights ) {
  13512. var l, ll, light, n,
  13513. r = 0, g = 0, b = 0,
  13514. color, skyColor, groundColor,
  13515. intensity, intensitySq,
  13516. position,
  13517. distance,
  13518. zlights = _lights,
  13519. dirColors = zlights.directional.colors,
  13520. dirPositions = zlights.directional.positions,
  13521. pointColors = zlights.point.colors,
  13522. pointPositions = zlights.point.positions,
  13523. pointDistances = zlights.point.distances,
  13524. spotColors = zlights.spot.colors,
  13525. spotPositions = zlights.spot.positions,
  13526. spotDistances = zlights.spot.distances,
  13527. spotDirections = zlights.spot.directions,
  13528. spotAnglesCos = zlights.spot.anglesCos,
  13529. spotExponents = zlights.spot.exponents,
  13530. hemiSkyColors = zlights.hemi.skyColors,
  13531. hemiGroundColors = zlights.hemi.groundColors,
  13532. hemiPositions = zlights.hemi.positions,
  13533. dirLength = 0,
  13534. pointLength = 0,
  13535. spotLength = 0,
  13536. hemiLength = 0,
  13537. dirCount = 0,
  13538. pointCount = 0,
  13539. spotCount = 0,
  13540. hemiCount = 0,
  13541. dirOffset = 0,
  13542. pointOffset = 0,
  13543. spotOffset = 0,
  13544. hemiOffset = 0;
  13545. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  13546. light = lights[ l ];
  13547. if ( light.onlyShadow ) continue;
  13548. color = light.color;
  13549. intensity = light.intensity;
  13550. distance = light.distance;
  13551. if ( light instanceof THREE.AmbientLight ) {
  13552. if ( ! light.visible ) continue;
  13553. if ( _this.gammaInput ) {
  13554. r += color.r * color.r;
  13555. g += color.g * color.g;
  13556. b += color.b * color.b;
  13557. } else {
  13558. r += color.r;
  13559. g += color.g;
  13560. b += color.b;
  13561. }
  13562. } else if ( light instanceof THREE.DirectionalLight ) {
  13563. dirCount += 1;
  13564. if ( ! light.visible ) continue;
  13565. _direction.copy( light.matrixWorld.getPosition() );
  13566. _direction.sub( light.target.matrixWorld.getPosition() );
  13567. _direction.normalize();
  13568. // skip lights with undefined direction
  13569. // these create troubles in OpenGL (making pixel black)
  13570. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  13571. dirOffset = dirLength * 3;
  13572. dirPositions[ dirOffset ] = _direction.x;
  13573. dirPositions[ dirOffset + 1 ] = _direction.y;
  13574. dirPositions[ dirOffset + 2 ] = _direction.z;
  13575. if ( _this.gammaInput ) {
  13576. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  13577. } else {
  13578. setColorLinear( dirColors, dirOffset, color, intensity );
  13579. }
  13580. dirLength += 1;
  13581. } else if ( light instanceof THREE.PointLight ) {
  13582. pointCount += 1;
  13583. if ( ! light.visible ) continue;
  13584. pointOffset = pointLength * 3;
  13585. if ( _this.gammaInput ) {
  13586. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  13587. } else {
  13588. setColorLinear( pointColors, pointOffset, color, intensity );
  13589. }
  13590. position = light.matrixWorld.getPosition();
  13591. pointPositions[ pointOffset ] = position.x;
  13592. pointPositions[ pointOffset + 1 ] = position.y;
  13593. pointPositions[ pointOffset + 2 ] = position.z;
  13594. pointDistances[ pointLength ] = distance;
  13595. pointLength += 1;
  13596. } else if ( light instanceof THREE.SpotLight ) {
  13597. spotCount += 1;
  13598. if ( ! light.visible ) continue;
  13599. spotOffset = spotLength * 3;
  13600. if ( _this.gammaInput ) {
  13601. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  13602. } else {
  13603. setColorLinear( spotColors, spotOffset, color, intensity );
  13604. }
  13605. position = light.matrixWorld.getPosition();
  13606. spotPositions[ spotOffset ] = position.x;
  13607. spotPositions[ spotOffset + 1 ] = position.y;
  13608. spotPositions[ spotOffset + 2 ] = position.z;
  13609. spotDistances[ spotLength ] = distance;
  13610. _direction.copy( position );
  13611. _direction.sub( light.target.matrixWorld.getPosition() );
  13612. _direction.normalize();
  13613. spotDirections[ spotOffset ] = _direction.x;
  13614. spotDirections[ spotOffset + 1 ] = _direction.y;
  13615. spotDirections[ spotOffset + 2 ] = _direction.z;
  13616. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  13617. spotExponents[ spotLength ] = light.exponent;
  13618. spotLength += 1;
  13619. } else if ( light instanceof THREE.HemisphereLight ) {
  13620. hemiCount += 1;
  13621. if ( ! light.visible ) continue;
  13622. _direction.copy( light.matrixWorld.getPosition() );
  13623. _direction.normalize();
  13624. // skip lights with undefined direction
  13625. // these create troubles in OpenGL (making pixel black)
  13626. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  13627. hemiOffset = hemiLength * 3;
  13628. hemiPositions[ hemiOffset ] = _direction.x;
  13629. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  13630. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  13631. skyColor = light.color;
  13632. groundColor = light.groundColor;
  13633. if ( _this.gammaInput ) {
  13634. intensitySq = intensity * intensity;
  13635. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  13636. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  13637. } else {
  13638. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  13639. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  13640. }
  13641. hemiLength += 1;
  13642. }
  13643. }
  13644. // null eventual remains from removed lights
  13645. // (this is to avoid if in shader)
  13646. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  13647. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  13648. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  13649. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  13650. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  13651. zlights.directional.length = dirLength;
  13652. zlights.point.length = pointLength;
  13653. zlights.spot.length = spotLength;
  13654. zlights.hemi.length = hemiLength;
  13655. zlights.ambient[ 0 ] = r;
  13656. zlights.ambient[ 1 ] = g;
  13657. zlights.ambient[ 2 ] = b;
  13658. };
  13659. // GL state setting
  13660. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  13661. if ( cullFace === THREE.CullFaceNone ) {
  13662. _gl.disable( _gl.CULL_FACE );
  13663. } else {
  13664. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  13665. _gl.frontFace( _gl.CW );
  13666. } else {
  13667. _gl.frontFace( _gl.CCW );
  13668. }
  13669. if ( cullFace === THREE.CullFaceBack ) {
  13670. _gl.cullFace( _gl.BACK );
  13671. } else if ( cullFace === THREE.CullFaceFront ) {
  13672. _gl.cullFace( _gl.FRONT );
  13673. } else {
  13674. _gl.cullFace( _gl.FRONT_AND_BACK );
  13675. }
  13676. _gl.enable( _gl.CULL_FACE );
  13677. }
  13678. };
  13679. this.setMaterialFaces = function ( material ) {
  13680. var doubleSided = material.side === THREE.DoubleSide;
  13681. var flipSided = material.side === THREE.BackSide;
  13682. if ( _oldDoubleSided !== doubleSided ) {
  13683. if ( doubleSided ) {
  13684. _gl.disable( _gl.CULL_FACE );
  13685. } else {
  13686. _gl.enable( _gl.CULL_FACE );
  13687. }
  13688. _oldDoubleSided = doubleSided;
  13689. }
  13690. if ( _oldFlipSided !== flipSided ) {
  13691. if ( flipSided ) {
  13692. _gl.frontFace( _gl.CW );
  13693. } else {
  13694. _gl.frontFace( _gl.CCW );
  13695. }
  13696. _oldFlipSided = flipSided;
  13697. }
  13698. };
  13699. this.setDepthTest = function ( depthTest ) {
  13700. if ( _oldDepthTest !== depthTest ) {
  13701. if ( depthTest ) {
  13702. _gl.enable( _gl.DEPTH_TEST );
  13703. } else {
  13704. _gl.disable( _gl.DEPTH_TEST );
  13705. }
  13706. _oldDepthTest = depthTest;
  13707. }
  13708. };
  13709. this.setDepthWrite = function ( depthWrite ) {
  13710. if ( _oldDepthWrite !== depthWrite ) {
  13711. _gl.depthMask( depthWrite );
  13712. _oldDepthWrite = depthWrite;
  13713. }
  13714. };
  13715. function setLineWidth ( width ) {
  13716. if ( width !== _oldLineWidth ) {
  13717. _gl.lineWidth( width );
  13718. _oldLineWidth = width;
  13719. }
  13720. };
  13721. function setPolygonOffset ( polygonoffset, factor, units ) {
  13722. if ( _oldPolygonOffset !== polygonoffset ) {
  13723. if ( polygonoffset ) {
  13724. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  13725. } else {
  13726. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  13727. }
  13728. _oldPolygonOffset = polygonoffset;
  13729. }
  13730. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  13731. _gl.polygonOffset( factor, units );
  13732. _oldPolygonOffsetFactor = factor;
  13733. _oldPolygonOffsetUnits = units;
  13734. }
  13735. };
  13736. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  13737. if ( blending !== _oldBlending ) {
  13738. if ( blending === THREE.NoBlending ) {
  13739. _gl.disable( _gl.BLEND );
  13740. } else if ( blending === THREE.AdditiveBlending ) {
  13741. _gl.enable( _gl.BLEND );
  13742. _gl.blendEquation( _gl.FUNC_ADD );
  13743. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  13744. } else if ( blending === THREE.SubtractiveBlending ) {
  13745. // TODO: Find blendFuncSeparate() combination
  13746. _gl.enable( _gl.BLEND );
  13747. _gl.blendEquation( _gl.FUNC_ADD );
  13748. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  13749. } else if ( blending === THREE.MultiplyBlending ) {
  13750. // TODO: Find blendFuncSeparate() combination
  13751. _gl.enable( _gl.BLEND );
  13752. _gl.blendEquation( _gl.FUNC_ADD );
  13753. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  13754. } else if ( blending === THREE.CustomBlending ) {
  13755. _gl.enable( _gl.BLEND );
  13756. } else {
  13757. _gl.enable( _gl.BLEND );
  13758. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  13759. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  13760. }
  13761. _oldBlending = blending;
  13762. }
  13763. if ( blending === THREE.CustomBlending ) {
  13764. if ( blendEquation !== _oldBlendEquation ) {
  13765. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  13766. _oldBlendEquation = blendEquation;
  13767. }
  13768. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  13769. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  13770. _oldBlendSrc = blendSrc;
  13771. _oldBlendDst = blendDst;
  13772. }
  13773. } else {
  13774. _oldBlendEquation = null;
  13775. _oldBlendSrc = null;
  13776. _oldBlendDst = null;
  13777. }
  13778. };
  13779. // Defines
  13780. function generateDefines ( defines ) {
  13781. var value, chunk, chunks = [];
  13782. for ( var d in defines ) {
  13783. value = defines[ d ];
  13784. if ( value === false ) continue;
  13785. chunk = "#define " + d + " " + value;
  13786. chunks.push( chunk );
  13787. }
  13788. return chunks.join( "\n" );
  13789. };
  13790. // Shaders
  13791. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters ) {
  13792. var p, pl, d, program, code;
  13793. var chunks = [];
  13794. // Generate code
  13795. if ( shaderID ) {
  13796. chunks.push( shaderID );
  13797. } else {
  13798. chunks.push( fragmentShader );
  13799. chunks.push( vertexShader );
  13800. }
  13801. for ( d in defines ) {
  13802. chunks.push( d );
  13803. chunks.push( defines[ d ] );
  13804. }
  13805. for ( p in parameters ) {
  13806. chunks.push( p );
  13807. chunks.push( parameters[ p ] );
  13808. }
  13809. code = chunks.join();
  13810. // Check if code has been already compiled
  13811. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  13812. var programInfo = _programs[ p ];
  13813. if ( programInfo.code === code ) {
  13814. //console.log( "Code already compiled." /*: \n\n" + code*/ );
  13815. programInfo.usedTimes ++;
  13816. return programInfo.program;
  13817. }
  13818. }
  13819. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  13820. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  13821. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  13822. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  13823. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  13824. }
  13825. //console.log( "building new program " );
  13826. //
  13827. var customDefines = generateDefines( defines );
  13828. //
  13829. program = _gl.createProgram();
  13830. var prefix_vertex = [
  13831. "precision " + _precision + " float;",
  13832. customDefines,
  13833. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  13834. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  13835. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  13836. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  13837. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  13838. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  13839. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  13840. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  13841. "#define MAX_SHADOWS " + parameters.maxShadows,
  13842. "#define MAX_BONES " + parameters.maxBones,
  13843. parameters.map ? "#define USE_MAP" : "",
  13844. parameters.envMap ? "#define USE_ENVMAP" : "",
  13845. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  13846. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  13847. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  13848. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  13849. parameters.vertexColors ? "#define USE_COLOR" : "",
  13850. parameters.skinning ? "#define USE_SKINNING" : "",
  13851. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  13852. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  13853. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  13854. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  13855. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  13856. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  13857. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  13858. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  13859. parameters.flipSided ? "#define FLIP_SIDED" : "",
  13860. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  13861. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  13862. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  13863. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  13864. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  13865. "uniform mat4 modelMatrix;",
  13866. "uniform mat4 modelViewMatrix;",
  13867. "uniform mat4 projectionMatrix;",
  13868. "uniform mat4 viewMatrix;",
  13869. "uniform mat3 normalMatrix;",
  13870. "uniform vec3 cameraPosition;",
  13871. "attribute vec3 position;",
  13872. "attribute vec3 normal;",
  13873. "attribute vec2 uv;",
  13874. "attribute vec2 uv2;",
  13875. "#ifdef USE_COLOR",
  13876. "attribute vec3 color;",
  13877. "#endif",
  13878. "#ifdef USE_MORPHTARGETS",
  13879. "attribute vec3 morphTarget0;",
  13880. "attribute vec3 morphTarget1;",
  13881. "attribute vec3 morphTarget2;",
  13882. "attribute vec3 morphTarget3;",
  13883. "#ifdef USE_MORPHNORMALS",
  13884. "attribute vec3 morphNormal0;",
  13885. "attribute vec3 morphNormal1;",
  13886. "attribute vec3 morphNormal2;",
  13887. "attribute vec3 morphNormal3;",
  13888. "#else",
  13889. "attribute vec3 morphTarget4;",
  13890. "attribute vec3 morphTarget5;",
  13891. "attribute vec3 morphTarget6;",
  13892. "attribute vec3 morphTarget7;",
  13893. "#endif",
  13894. "#endif",
  13895. "#ifdef USE_SKINNING",
  13896. "attribute vec4 skinIndex;",
  13897. "attribute vec4 skinWeight;",
  13898. "#endif",
  13899. ""
  13900. ].join("\n");
  13901. var prefix_fragment = [
  13902. "precision " + _precision + " float;",
  13903. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  13904. customDefines,
  13905. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  13906. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  13907. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  13908. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  13909. "#define MAX_SHADOWS " + parameters.maxShadows,
  13910. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  13911. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  13912. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  13913. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  13914. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  13915. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  13916. parameters.map ? "#define USE_MAP" : "",
  13917. parameters.envMap ? "#define USE_ENVMAP" : "",
  13918. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  13919. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  13920. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  13921. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  13922. parameters.vertexColors ? "#define USE_COLOR" : "",
  13923. parameters.metal ? "#define METAL" : "",
  13924. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  13925. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  13926. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  13927. parameters.flipSided ? "#define FLIP_SIDED" : "",
  13928. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  13929. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  13930. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  13931. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  13932. "uniform mat4 viewMatrix;",
  13933. "uniform vec3 cameraPosition;",
  13934. ""
  13935. ].join("\n");
  13936. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  13937. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  13938. _gl.attachShader( program, glVertexShader );
  13939. _gl.attachShader( program, glFragmentShader );
  13940. _gl.linkProgram( program );
  13941. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  13942. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  13943. }
  13944. // clean up
  13945. _gl.deleteShader( glFragmentShader );
  13946. _gl.deleteShader( glVertexShader );
  13947. //console.log( prefix_fragment + fragmentShader );
  13948. //console.log( prefix_vertex + vertexShader );
  13949. program.uniforms = {};
  13950. program.attributes = {};
  13951. var identifiers, u, a, i;
  13952. // cache uniform locations
  13953. identifiers = [
  13954. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  13955. 'morphTargetInfluences'
  13956. ];
  13957. if ( parameters.useVertexTexture ) {
  13958. identifiers.push( 'boneTexture' );
  13959. } else {
  13960. identifiers.push( 'boneGlobalMatrices' );
  13961. }
  13962. for ( u in uniforms ) {
  13963. identifiers.push( u );
  13964. }
  13965. cacheUniformLocations( program, identifiers );
  13966. // cache attributes locations
  13967. identifiers = [
  13968. "position", "normal", "uv", "uv2", "tangent", "color",
  13969. "skinIndex", "skinWeight", "lineDistance"
  13970. ];
  13971. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  13972. identifiers.push( "morphTarget" + i );
  13973. }
  13974. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  13975. identifiers.push( "morphNormal" + i );
  13976. }
  13977. for ( a in attributes ) {
  13978. identifiers.push( a );
  13979. }
  13980. cacheAttributeLocations( program, identifiers );
  13981. program.id = _programs_counter ++;
  13982. _programs.push( { program: program, code: code, usedTimes: 1 } );
  13983. _this.info.memory.programs = _programs.length;
  13984. return program;
  13985. };
  13986. // Shader parameters cache
  13987. function cacheUniformLocations ( program, identifiers ) {
  13988. var i, l, id;
  13989. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  13990. id = identifiers[ i ];
  13991. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  13992. }
  13993. };
  13994. function cacheAttributeLocations ( program, identifiers ) {
  13995. var i, l, id;
  13996. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  13997. id = identifiers[ i ];
  13998. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  13999. }
  14000. };
  14001. function addLineNumbers ( string ) {
  14002. var chunks = string.split( "\n" );
  14003. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  14004. // Chrome reports shader errors on lines
  14005. // starting counting from 1
  14006. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  14007. }
  14008. return chunks.join( "\n" );
  14009. };
  14010. function getShader ( type, string ) {
  14011. var shader;
  14012. if ( type === "fragment" ) {
  14013. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  14014. } else if ( type === "vertex" ) {
  14015. shader = _gl.createShader( _gl.VERTEX_SHADER );
  14016. }
  14017. _gl.shaderSource( shader, string );
  14018. _gl.compileShader( shader );
  14019. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  14020. console.error( _gl.getShaderInfoLog( shader ) );
  14021. console.error( addLineNumbers( string ) );
  14022. return null;
  14023. }
  14024. return shader;
  14025. };
  14026. // Textures
  14027. function isPowerOfTwo ( value ) {
  14028. return ( value & ( value - 1 ) ) === 0;
  14029. };
  14030. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  14031. if ( isImagePowerOfTwo ) {
  14032. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  14033. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  14034. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  14035. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  14036. } else {
  14037. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  14038. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  14039. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  14040. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  14041. }
  14042. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  14043. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  14044. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  14045. texture.__oldAnisotropy = texture.anisotropy;
  14046. }
  14047. }
  14048. };
  14049. this.setTexture = function ( texture, slot ) {
  14050. if ( texture.needsUpdate ) {
  14051. if ( ! texture.__webglInit ) {
  14052. texture.__webglInit = true;
  14053. texture.addEventListener( 'dispose', onTextureDispose );
  14054. texture.__webglTexture = _gl.createTexture();
  14055. _this.info.memory.textures ++;
  14056. }
  14057. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14058. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14059. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14060. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14061. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14062. var image = texture.image,
  14063. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  14064. glFormat = paramThreeToGL( texture.format ),
  14065. glType = paramThreeToGL( texture.type );
  14066. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  14067. var mipmap, mipmaps = texture.mipmaps;
  14068. if ( texture instanceof THREE.DataTexture ) {
  14069. // use manually created mipmaps if available
  14070. // if there are no manual mipmaps
  14071. // set 0 level mipmap and then use GL to generate other mipmap levels
  14072. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14073. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14074. mipmap = mipmaps[ i ];
  14075. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14076. }
  14077. texture.generateMipmaps = false;
  14078. } else {
  14079. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14080. }
  14081. } else if ( texture instanceof THREE.CompressedTexture ) {
  14082. // compressed textures can only use manually created mipmaps
  14083. // WebGL can't generate mipmaps for DDS textures
  14084. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14085. mipmap = mipmaps[ i ];
  14086. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14087. }
  14088. } else { // regular Texture (image, video, canvas)
  14089. // use manually created mipmaps if available
  14090. // if there are no manual mipmaps
  14091. // set 0 level mipmap and then use GL to generate other mipmap levels
  14092. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14093. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14094. mipmap = mipmaps[ i ];
  14095. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  14096. }
  14097. texture.generateMipmaps = false;
  14098. } else {
  14099. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  14100. }
  14101. }
  14102. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14103. texture.needsUpdate = false;
  14104. if ( texture.onUpdate ) texture.onUpdate();
  14105. } else {
  14106. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14107. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14108. }
  14109. };
  14110. function clampToMaxSize ( image, maxSize ) {
  14111. if ( image.width <= maxSize && image.height <= maxSize ) {
  14112. return image;
  14113. }
  14114. // Warning: Scaling through the canvas will only work with images that use
  14115. // premultiplied alpha.
  14116. var maxDimension = Math.max( image.width, image.height );
  14117. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  14118. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  14119. var canvas = document.createElement( 'canvas' );
  14120. canvas.width = newWidth;
  14121. canvas.height = newHeight;
  14122. var ctx = canvas.getContext( "2d" );
  14123. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  14124. return canvas;
  14125. }
  14126. function setCubeTexture ( texture, slot ) {
  14127. if ( texture.image.length === 6 ) {
  14128. if ( texture.needsUpdate ) {
  14129. if ( ! texture.image.__webglTextureCube ) {
  14130. texture.image.__webglTextureCube = _gl.createTexture();
  14131. _this.info.memory.textures ++;
  14132. }
  14133. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14134. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  14135. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14136. var isCompressed = texture instanceof THREE.CompressedTexture;
  14137. var cubeImage = [];
  14138. for ( var i = 0; i < 6; i ++ ) {
  14139. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  14140. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  14141. } else {
  14142. cubeImage[ i ] = texture.image[ i ];
  14143. }
  14144. }
  14145. var image = cubeImage[ 0 ],
  14146. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  14147. glFormat = paramThreeToGL( texture.format ),
  14148. glType = paramThreeToGL( texture.type );
  14149. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  14150. for ( var i = 0; i < 6; i ++ ) {
  14151. if ( isCompressed ) {
  14152. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  14153. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  14154. mipmap = mipmaps[ j ];
  14155. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14156. }
  14157. } else {
  14158. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  14159. }
  14160. }
  14161. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  14162. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14163. }
  14164. texture.needsUpdate = false;
  14165. if ( texture.onUpdate ) texture.onUpdate();
  14166. } else {
  14167. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14168. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  14169. }
  14170. }
  14171. };
  14172. function setCubeTextureDynamic ( texture, slot ) {
  14173. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14174. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  14175. };
  14176. // Render targets
  14177. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  14178. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14179. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  14180. };
  14181. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  14182. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  14183. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14184. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  14185. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14186. /* For some reason this is not working. Defaulting to RGBA4.
  14187. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14188. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  14189. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14190. */
  14191. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14192. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  14193. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14194. } else {
  14195. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  14196. }
  14197. };
  14198. this.setRenderTarget = function ( renderTarget ) {
  14199. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  14200. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  14201. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  14202. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  14203. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  14204. renderTarget.__webglTexture = _gl.createTexture();
  14205. _this.info.memory.textures ++;
  14206. // Setup texture, create render and frame buffers
  14207. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  14208. glFormat = paramThreeToGL( renderTarget.format ),
  14209. glType = paramThreeToGL( renderTarget.type );
  14210. if ( isCube ) {
  14211. renderTarget.__webglFramebuffer = [];
  14212. renderTarget.__webglRenderbuffer = [];
  14213. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  14214. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  14215. for ( var i = 0; i < 6; i ++ ) {
  14216. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  14217. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  14218. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14219. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  14220. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  14221. }
  14222. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14223. } else {
  14224. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  14225. if ( renderTarget.shareDepthFrom ) {
  14226. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  14227. } else {
  14228. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  14229. }
  14230. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  14231. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  14232. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14233. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  14234. if ( renderTarget.shareDepthFrom ) {
  14235. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14236. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  14237. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14238. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  14239. }
  14240. } else {
  14241. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  14242. }
  14243. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14244. }
  14245. // Release everything
  14246. if ( isCube ) {
  14247. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  14248. } else {
  14249. _gl.bindTexture( _gl.TEXTURE_2D, null );
  14250. }
  14251. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  14252. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14253. }
  14254. var framebuffer, width, height, vx, vy;
  14255. if ( renderTarget ) {
  14256. if ( isCube ) {
  14257. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  14258. } else {
  14259. framebuffer = renderTarget.__webglFramebuffer;
  14260. }
  14261. width = renderTarget.width;
  14262. height = renderTarget.height;
  14263. vx = 0;
  14264. vy = 0;
  14265. } else {
  14266. framebuffer = null;
  14267. width = _viewportWidth;
  14268. height = _viewportHeight;
  14269. vx = _viewportX;
  14270. vy = _viewportY;
  14271. }
  14272. if ( framebuffer !== _currentFramebuffer ) {
  14273. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14274. _gl.viewport( vx, vy, width, height );
  14275. _currentFramebuffer = framebuffer;
  14276. }
  14277. _currentWidth = width;
  14278. _currentHeight = height;
  14279. };
  14280. function updateRenderTargetMipmap ( renderTarget ) {
  14281. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  14282. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  14283. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14284. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  14285. } else {
  14286. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  14287. _gl.generateMipmap( _gl.TEXTURE_2D );
  14288. _gl.bindTexture( _gl.TEXTURE_2D, null );
  14289. }
  14290. };
  14291. // Fallback filters for non-power-of-2 textures
  14292. function filterFallback ( f ) {
  14293. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  14294. return _gl.NEAREST;
  14295. }
  14296. return _gl.LINEAR;
  14297. };
  14298. // Map three.js constants to WebGL constants
  14299. function paramThreeToGL ( p ) {
  14300. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  14301. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  14302. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  14303. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  14304. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  14305. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  14306. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  14307. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  14308. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  14309. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  14310. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  14311. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  14312. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  14313. if ( p === THREE.ByteType ) return _gl.BYTE;
  14314. if ( p === THREE.ShortType ) return _gl.SHORT;
  14315. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  14316. if ( p === THREE.IntType ) return _gl.INT;
  14317. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  14318. if ( p === THREE.FloatType ) return _gl.FLOAT;
  14319. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  14320. if ( p === THREE.RGBFormat ) return _gl.RGB;
  14321. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  14322. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  14323. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  14324. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  14325. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  14326. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  14327. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  14328. if ( p === THREE.OneFactor ) return _gl.ONE;
  14329. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  14330. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  14331. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  14332. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  14333. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  14334. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  14335. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  14336. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  14337. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  14338. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  14339. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14340. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14341. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14342. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14343. }
  14344. return 0;
  14345. };
  14346. // Allocations
  14347. function allocateBones ( object ) {
  14348. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  14349. return 1024;
  14350. } else {
  14351. // default for when object is not specified
  14352. // ( for example when prebuilding shader
  14353. // to be used with multiple objects )
  14354. //
  14355. // - leave some extra space for other uniforms
  14356. // - limit here is ANGLE's 254 max uniform vectors
  14357. // (up to 54 should be safe)
  14358. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  14359. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  14360. var maxBones = nVertexMatrices;
  14361. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  14362. maxBones = Math.min( object.bones.length, maxBones );
  14363. if ( maxBones < object.bones.length ) {
  14364. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  14365. }
  14366. }
  14367. return maxBones;
  14368. }
  14369. };
  14370. function allocateLights ( lights ) {
  14371. var l, ll, light, dirLights, pointLights, spotLights, hemiLights;
  14372. dirLights = pointLights = spotLights = hemiLights = 0;
  14373. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14374. light = lights[ l ];
  14375. if ( light.onlyShadow ) continue;
  14376. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  14377. if ( light instanceof THREE.PointLight ) pointLights ++;
  14378. if ( light instanceof THREE.SpotLight ) spotLights ++;
  14379. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  14380. }
  14381. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  14382. };
  14383. function allocateShadows ( lights ) {
  14384. var l, ll, light, maxShadows = 0;
  14385. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  14386. light = lights[ l ];
  14387. if ( ! light.castShadow ) continue;
  14388. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  14389. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  14390. }
  14391. return maxShadows;
  14392. };
  14393. // Initialization
  14394. function initGL () {
  14395. try {
  14396. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  14397. throw 'Error creating WebGL context.';
  14398. }
  14399. } catch ( error ) {
  14400. console.error( error );
  14401. }
  14402. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  14403. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  14404. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) ||
  14405. _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) ||
  14406. _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  14407. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) ||
  14408. _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) ||
  14409. _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  14410. if ( ! _glExtensionTextureFloat ) {
  14411. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  14412. }
  14413. if ( ! _glExtensionStandardDerivatives ) {
  14414. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  14415. }
  14416. if ( ! _glExtensionTextureFilterAnisotropic ) {
  14417. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  14418. }
  14419. if ( ! _glExtensionCompressedTextureS3TC ) {
  14420. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  14421. }
  14422. };
  14423. function setDefaultGLState () {
  14424. _gl.clearColor( 0, 0, 0, 1 );
  14425. _gl.clearDepth( 1 );
  14426. _gl.clearStencil( 0 );
  14427. _gl.enable( _gl.DEPTH_TEST );
  14428. _gl.depthFunc( _gl.LEQUAL );
  14429. _gl.frontFace( _gl.CCW );
  14430. _gl.cullFace( _gl.BACK );
  14431. _gl.enable( _gl.CULL_FACE );
  14432. _gl.enable( _gl.BLEND );
  14433. _gl.blendEquation( _gl.FUNC_ADD );
  14434. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  14435. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  14436. };
  14437. // default plugins (order is important)
  14438. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  14439. this.addPrePlugin( this.shadowMapPlugin );
  14440. this.addPostPlugin( new THREE.SpritePlugin() );
  14441. this.addPostPlugin( new THREE.LensFlarePlugin() );
  14442. };
  14443. /**
  14444. * @author szimek / https://github.com/szimek/
  14445. * @author alteredq / http://alteredqualia.com/
  14446. */
  14447. THREE.WebGLRenderTarget = function ( width, height, options ) {
  14448. THREE.EventDispatcher.call( this );
  14449. this.width = width;
  14450. this.height = height;
  14451. options = options || {};
  14452. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  14453. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  14454. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  14455. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  14456. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  14457. this.offset = new THREE.Vector2( 0, 0 );
  14458. this.repeat = new THREE.Vector2( 1, 1 );
  14459. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  14460. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  14461. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  14462. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  14463. this.generateMipmaps = true;
  14464. this.shareDepthFrom = null;
  14465. };
  14466. THREE.WebGLRenderTarget.prototype.clone = function() {
  14467. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  14468. tmp.wrapS = this.wrapS;
  14469. tmp.wrapT = this.wrapT;
  14470. tmp.magFilter = this.magFilter;
  14471. tmp.minFilter = this.minFilter;
  14472. tmp.anisotropy = this.anisotropy;
  14473. tmp.offset.copy( this.offset );
  14474. tmp.repeat.copy( this.repeat );
  14475. tmp.format = this.format;
  14476. tmp.type = this.type;
  14477. tmp.depthBuffer = this.depthBuffer;
  14478. tmp.stencilBuffer = this.stencilBuffer;
  14479. tmp.generateMipmaps = this.generateMipmaps;
  14480. tmp.shareDepthFrom = this.shareDepthFrom;
  14481. return tmp;
  14482. };
  14483. THREE.WebGLRenderTarget.prototype.dispose = function () {
  14484. this.dispatchEvent( { type: 'dispose' } );
  14485. };
  14486. /**
  14487. * @author alteredq / http://alteredqualia.com
  14488. */
  14489. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  14490. THREE.WebGLRenderTarget.call( this, width, height, options );
  14491. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  14492. };
  14493. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  14494. /**
  14495. * @author mrdoob / http://mrdoob.com/
  14496. */
  14497. THREE.RenderableVertex = function () {
  14498. this.positionWorld = new THREE.Vector3();
  14499. this.positionScreen = new THREE.Vector4();
  14500. this.visible = true;
  14501. };
  14502. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  14503. this.positionWorld.copy( vertex.positionWorld );
  14504. this.positionScreen.copy( vertex.positionScreen );
  14505. };
  14506. /**
  14507. * @author mrdoob / http://mrdoob.com/
  14508. */
  14509. THREE.RenderableFace3 = function () {
  14510. this.v1 = new THREE.RenderableVertex();
  14511. this.v2 = new THREE.RenderableVertex();
  14512. this.v3 = new THREE.RenderableVertex();
  14513. this.centroidModel = new THREE.Vector3();
  14514. this.normalModel = new THREE.Vector3();
  14515. this.normalModelView = new THREE.Vector3();
  14516. this.vertexNormalsLength = 0;
  14517. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  14518. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  14519. this.color = null;
  14520. this.material = null;
  14521. this.uvs = [[]];
  14522. this.z = null;
  14523. };
  14524. /**
  14525. * @author mrdoob / http://mrdoob.com/
  14526. */
  14527. THREE.RenderableFace4 = function () {
  14528. this.v1 = new THREE.RenderableVertex();
  14529. this.v2 = new THREE.RenderableVertex();
  14530. this.v3 = new THREE.RenderableVertex();
  14531. this.v4 = new THREE.RenderableVertex();
  14532. this.centroidModel = new THREE.Vector3();
  14533. this.normalModel = new THREE.Vector3();
  14534. this.normalModelView = new THREE.Vector3();
  14535. this.vertexNormalsLength = 0;
  14536. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  14537. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  14538. this.color = null;
  14539. this.material = null;
  14540. this.uvs = [[]];
  14541. this.z = null;
  14542. };
  14543. /**
  14544. * @author mrdoob / http://mrdoob.com/
  14545. */
  14546. THREE.RenderableObject = function () {
  14547. this.object = null;
  14548. this.z = null;
  14549. };
  14550. /**
  14551. * @author mrdoob / http://mrdoob.com/
  14552. */
  14553. THREE.RenderableParticle = function () {
  14554. this.object = null;
  14555. this.x = null;
  14556. this.y = null;
  14557. this.z = null;
  14558. this.rotation = null;
  14559. this.scale = new THREE.Vector2();
  14560. this.material = null;
  14561. };
  14562. /**
  14563. * @author mrdoob / http://mrdoob.com/
  14564. */
  14565. THREE.RenderableLine = function () {
  14566. this.z = null;
  14567. this.v1 = new THREE.RenderableVertex();
  14568. this.v2 = new THREE.RenderableVertex();
  14569. this.material = null;
  14570. };
  14571. /**
  14572. * @author alteredq / http://alteredqualia.com/
  14573. */
  14574. THREE.ColorUtils = {
  14575. adjustHSV : function ( color, h, s, v ) {
  14576. var hsv = THREE.ColorUtils.__hsv;
  14577. color.getHSV( hsv );
  14578. hsv.h = THREE.Math.clamp( hsv.h + h, 0, 1 );
  14579. hsv.s = THREE.Math.clamp( hsv.s + s, 0, 1 );
  14580. hsv.v = THREE.Math.clamp( hsv.v + v, 0, 1 );
  14581. color.setHSV( hsv.h, hsv.s, hsv.v );
  14582. }
  14583. };
  14584. THREE.ColorUtils.__hsv = { h: 0, s: 0, v: 0 };/**
  14585. * @author mrdoob / http://mrdoob.com/
  14586. * @author alteredq / http://alteredqualia.com/
  14587. */
  14588. THREE.GeometryUtils = {
  14589. // Merge two geometries or geometry and geometry from object (using object's transform)
  14590. merge: function ( geometry1, object2 /* mesh | geometry */ ) {
  14591. var matrix, normalMatrix,
  14592. vertexOffset = geometry1.vertices.length,
  14593. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  14594. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  14595. vertices1 = geometry1.vertices,
  14596. vertices2 = geometry2.vertices,
  14597. faces1 = geometry1.faces,
  14598. faces2 = geometry2.faces,
  14599. uvs1 = geometry1.faceVertexUvs[ 0 ],
  14600. uvs2 = geometry2.faceVertexUvs[ 0 ];
  14601. if ( object2 instanceof THREE.Mesh ) {
  14602. object2.matrixAutoUpdate && object2.updateMatrix();
  14603. matrix = object2.matrix;
  14604. normalMatrix = new THREE.Matrix3();
  14605. normalMatrix.getInverse( matrix );
  14606. normalMatrix.transpose();
  14607. }
  14608. // vertices
  14609. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  14610. var vertex = vertices2[ i ];
  14611. var vertexCopy = vertex.clone();
  14612. if ( matrix ) vertexCopy.applyMatrix4( matrix );
  14613. vertices1.push( vertexCopy );
  14614. }
  14615. // faces
  14616. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  14617. var face = faces2[ i ], faceCopy, normal, color,
  14618. faceVertexNormals = face.vertexNormals,
  14619. faceVertexColors = face.vertexColors;
  14620. if ( face instanceof THREE.Face3 ) {
  14621. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  14622. } else if ( face instanceof THREE.Face4 ) {
  14623. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  14624. }
  14625. faceCopy.normal.copy( face.normal );
  14626. if ( normalMatrix ) {
  14627. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  14628. }
  14629. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  14630. normal = faceVertexNormals[ j ].clone();
  14631. if ( normalMatrix ) {
  14632. normal.applyMatrix3( normalMatrix ).normalize();
  14633. }
  14634. faceCopy.vertexNormals.push( normal );
  14635. }
  14636. faceCopy.color.copy( face.color );
  14637. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  14638. color = faceVertexColors[ j ];
  14639. faceCopy.vertexColors.push( color.clone() );
  14640. }
  14641. faceCopy.materialIndex = face.materialIndex;
  14642. faceCopy.centroid.copy( face.centroid );
  14643. if ( matrix ) {
  14644. faceCopy.centroid.applyMatrix4( matrix );
  14645. }
  14646. faces1.push( faceCopy );
  14647. }
  14648. // uvs
  14649. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  14650. var uv = uvs2[ i ], uvCopy = [];
  14651. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  14652. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  14653. }
  14654. uvs1.push( uvCopy );
  14655. }
  14656. },
  14657. removeMaterials: function ( geometry, materialIndexArray ) {
  14658. var materialIndexMap = {};
  14659. for ( var i = 0, il = materialIndexArray.length; i < il; i ++ ) {
  14660. materialIndexMap[ materialIndexArray[i] ] = true;
  14661. }
  14662. var face, newFaces = [];
  14663. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14664. face = geometry.faces[ i ];
  14665. if ( ! ( face.materialIndex in materialIndexMap ) ) newFaces.push( face );
  14666. }
  14667. geometry.faces = newFaces;
  14668. },
  14669. // Get random point in triangle (via barycentric coordinates)
  14670. // (uniform distribution)
  14671. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  14672. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  14673. var a, b, c,
  14674. point = new THREE.Vector3(),
  14675. tmp = THREE.GeometryUtils.__v1;
  14676. a = THREE.GeometryUtils.random();
  14677. b = THREE.GeometryUtils.random();
  14678. if ( ( a + b ) > 1 ) {
  14679. a = 1 - a;
  14680. b = 1 - b;
  14681. }
  14682. c = 1 - a - b;
  14683. point.copy( vectorA );
  14684. point.multiplyScalar( a );
  14685. tmp.copy( vectorB );
  14686. tmp.multiplyScalar( b );
  14687. point.add( tmp );
  14688. tmp.copy( vectorC );
  14689. tmp.multiplyScalar( c );
  14690. point.add( tmp );
  14691. return point;
  14692. },
  14693. // Get random point in face (triangle / quad)
  14694. // (uniform distribution)
  14695. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  14696. var vA, vB, vC, vD;
  14697. if ( face instanceof THREE.Face3 ) {
  14698. vA = geometry.vertices[ face.a ];
  14699. vB = geometry.vertices[ face.b ];
  14700. vC = geometry.vertices[ face.c ];
  14701. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  14702. } else if ( face instanceof THREE.Face4 ) {
  14703. vA = geometry.vertices[ face.a ];
  14704. vB = geometry.vertices[ face.b ];
  14705. vC = geometry.vertices[ face.c ];
  14706. vD = geometry.vertices[ face.d ];
  14707. var area1, area2;
  14708. if ( useCachedAreas ) {
  14709. if ( face._area1 && face._area2 ) {
  14710. area1 = face._area1;
  14711. area2 = face._area2;
  14712. } else {
  14713. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  14714. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  14715. face._area1 = area1;
  14716. face._area2 = area2;
  14717. }
  14718. } else {
  14719. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  14720. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  14721. }
  14722. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  14723. if ( r < area1 ) {
  14724. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  14725. } else {
  14726. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  14727. }
  14728. }
  14729. },
  14730. // Get uniformly distributed random points in mesh
  14731. // - create array with cumulative sums of face areas
  14732. // - pick random number from 0 to total area
  14733. // - find corresponding place in area array by binary search
  14734. // - get random point in face
  14735. randomPointsInGeometry: function ( geometry, n ) {
  14736. var face, i,
  14737. faces = geometry.faces,
  14738. vertices = geometry.vertices,
  14739. il = faces.length,
  14740. totalArea = 0,
  14741. cumulativeAreas = [],
  14742. vA, vB, vC, vD;
  14743. // precompute face areas
  14744. for ( i = 0; i < il; i ++ ) {
  14745. face = faces[ i ];
  14746. if ( face instanceof THREE.Face3 ) {
  14747. vA = vertices[ face.a ];
  14748. vB = vertices[ face.b ];
  14749. vC = vertices[ face.c ];
  14750. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  14751. } else if ( face instanceof THREE.Face4 ) {
  14752. vA = vertices[ face.a ];
  14753. vB = vertices[ face.b ];
  14754. vC = vertices[ face.c ];
  14755. vD = vertices[ face.d ];
  14756. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  14757. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  14758. face._area = face._area1 + face._area2;
  14759. }
  14760. totalArea += face._area;
  14761. cumulativeAreas[ i ] = totalArea;
  14762. }
  14763. // binary search cumulative areas array
  14764. function binarySearchIndices( value ) {
  14765. function binarySearch( start, end ) {
  14766. // return closest larger index
  14767. // if exact number is not found
  14768. if ( end < start )
  14769. return start;
  14770. var mid = start + Math.floor( ( end - start ) / 2 );
  14771. if ( cumulativeAreas[ mid ] > value ) {
  14772. return binarySearch( start, mid - 1 );
  14773. } else if ( cumulativeAreas[ mid ] < value ) {
  14774. return binarySearch( mid + 1, end );
  14775. } else {
  14776. return mid;
  14777. }
  14778. }
  14779. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  14780. return result;
  14781. }
  14782. // pick random face weighted by face area
  14783. var r, index,
  14784. result = [];
  14785. var stats = {};
  14786. for ( i = 0; i < n; i ++ ) {
  14787. r = THREE.GeometryUtils.random() * totalArea;
  14788. index = binarySearchIndices( r );
  14789. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  14790. if ( ! stats[ index ] ) {
  14791. stats[ index ] = 1;
  14792. } else {
  14793. stats[ index ] += 1;
  14794. }
  14795. }
  14796. return result;
  14797. },
  14798. // Get triangle area (half of parallelogram)
  14799. // http://mathworld.wolfram.com/TriangleArea.html
  14800. triangleArea: function ( vectorA, vectorB, vectorC ) {
  14801. var tmp1 = THREE.GeometryUtils.__v1,
  14802. tmp2 = THREE.GeometryUtils.__v2;
  14803. tmp1.subVectors( vectorB, vectorA );
  14804. tmp2.subVectors( vectorC, vectorA );
  14805. tmp1.cross( tmp2 );
  14806. return 0.5 * tmp1.length();
  14807. },
  14808. // Center geometry so that 0,0,0 is in center of bounding box
  14809. center: function ( geometry ) {
  14810. geometry.computeBoundingBox();
  14811. var bb = geometry.boundingBox;
  14812. var offset = new THREE.Vector3();
  14813. offset.addVectors( bb.min, bb.max );
  14814. offset.multiplyScalar( -0.5 );
  14815. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset ) );
  14816. geometry.computeBoundingBox();
  14817. return offset;
  14818. },
  14819. // Normalize UVs to be from <0,1>
  14820. // (for now just the first set of UVs)
  14821. normalizeUVs: function ( geometry ) {
  14822. var uvSet = geometry.faceVertexUvs[ 0 ];
  14823. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  14824. var uvs = uvSet[ i ];
  14825. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  14826. // texture repeat
  14827. if( uvs[ j ].x !== 1.0 ) uvs[ j ].x = uvs[ j ].x - Math.floor( uvs[ j ].x );
  14828. if( uvs[ j ].y !== 1.0 ) uvs[ j ].y = uvs[ j ].y - Math.floor( uvs[ j ].y );
  14829. }
  14830. }
  14831. },
  14832. triangulateQuads: function ( geometry ) {
  14833. var i, il, j, jl;
  14834. var faces = [];
  14835. var faceUvs = [];
  14836. var faceVertexUvs = [];
  14837. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  14838. faceUvs[ i ] = [];
  14839. }
  14840. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  14841. faceVertexUvs[ i ] = [];
  14842. }
  14843. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14844. var face = geometry.faces[ i ];
  14845. if ( face instanceof THREE.Face4 ) {
  14846. var a = face.a;
  14847. var b = face.b;
  14848. var c = face.c;
  14849. var d = face.d;
  14850. var triA = new THREE.Face3();
  14851. var triB = new THREE.Face3();
  14852. triA.color.copy( face.color );
  14853. triB.color.copy( face.color );
  14854. triA.materialIndex = face.materialIndex;
  14855. triB.materialIndex = face.materialIndex;
  14856. triA.a = a;
  14857. triA.b = b;
  14858. triA.c = d;
  14859. triB.a = b;
  14860. triB.b = c;
  14861. triB.c = d;
  14862. if ( face.vertexColors.length === 4 ) {
  14863. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  14864. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  14865. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  14866. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  14867. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  14868. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  14869. }
  14870. faces.push( triA, triB );
  14871. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14872. if ( geometry.faceVertexUvs[ j ].length ) {
  14873. var uvs = geometry.faceVertexUvs[ j ][ i ];
  14874. var uvA = uvs[ 0 ];
  14875. var uvB = uvs[ 1 ];
  14876. var uvC = uvs[ 2 ];
  14877. var uvD = uvs[ 3 ];
  14878. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  14879. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  14880. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  14881. }
  14882. }
  14883. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  14884. if ( geometry.faceUvs[ j ].length ) {
  14885. var faceUv = geometry.faceUvs[ j ][ i ];
  14886. faceUvs[ j ].push( faceUv, faceUv );
  14887. }
  14888. }
  14889. } else {
  14890. faces.push( face );
  14891. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  14892. faceUvs[ j ].push( geometry.faceUvs[ j ][ i ] );
  14893. }
  14894. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14895. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  14896. }
  14897. }
  14898. }
  14899. geometry.faces = faces;
  14900. geometry.faceUvs = faceUvs;
  14901. geometry.faceVertexUvs = faceVertexUvs;
  14902. geometry.computeCentroids();
  14903. geometry.computeFaceNormals();
  14904. geometry.computeVertexNormals();
  14905. if ( geometry.hasTangents ) geometry.computeTangents();
  14906. },
  14907. setMaterialIndex: function ( geometry, index, startFace, endFace ){
  14908. var faces = geometry.faces;
  14909. var start = startFace || 0;
  14910. var end = endFace || faces.length - 1;
  14911. for ( var i = start; i <= end; i ++ ) {
  14912. faces[i].materialIndex = index;
  14913. }
  14914. }
  14915. };
  14916. THREE.GeometryUtils.random = THREE.Math.random16;
  14917. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  14918. THREE.GeometryUtils.__v2 = new THREE.Vector3();
  14919. /**
  14920. * @author alteredq / http://alteredqualia.com/
  14921. * @author mrdoob / http://mrdoob.com/
  14922. */
  14923. THREE.ImageUtils = {
  14924. crossOrigin: 'anonymous',
  14925. loadTexture: function ( url, mapping, onLoad, onError ) {
  14926. var image = new Image();
  14927. var texture = new THREE.Texture( image, mapping );
  14928. var loader = new THREE.ImageLoader();
  14929. loader.addEventListener( 'load', function ( event ) {
  14930. texture.image = event.content;
  14931. texture.needsUpdate = true;
  14932. if ( onLoad ) onLoad( texture );
  14933. } );
  14934. loader.addEventListener( 'error', function ( event ) {
  14935. if ( onError ) onError( event.message );
  14936. } );
  14937. loader.crossOrigin = this.crossOrigin;
  14938. loader.load( url, image );
  14939. texture.sourceFile = url;
  14940. return texture;
  14941. },
  14942. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  14943. var texture = new THREE.CompressedTexture();
  14944. texture.mapping = mapping;
  14945. var request = new XMLHttpRequest();
  14946. request.onload = function () {
  14947. var buffer = request.response;
  14948. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  14949. texture.format = dds.format;
  14950. texture.mipmaps = dds.mipmaps;
  14951. texture.image.width = dds.width;
  14952. texture.image.height = dds.height;
  14953. // gl.generateMipmap fails for compressed textures
  14954. // mipmaps must be embedded in the DDS file
  14955. // or texture filters must not use mipmapping
  14956. texture.generateMipmaps = false;
  14957. texture.needsUpdate = true;
  14958. if ( onLoad ) onLoad( texture );
  14959. }
  14960. request.onerror = onError;
  14961. request.open( 'GET', url, true );
  14962. request.responseType = "arraybuffer";
  14963. request.send( null );
  14964. return texture;
  14965. },
  14966. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  14967. var images = [];
  14968. images.loadCount = 0;
  14969. var texture = new THREE.Texture();
  14970. texture.image = images;
  14971. if ( mapping !== undefined ) texture.mapping = mapping;
  14972. // no flipping needed for cube textures
  14973. texture.flipY = false;
  14974. for ( var i = 0, il = array.length; i < il; ++ i ) {
  14975. var cubeImage = new Image();
  14976. images[ i ] = cubeImage;
  14977. cubeImage.onload = function () {
  14978. images.loadCount += 1;
  14979. if ( images.loadCount === 6 ) {
  14980. texture.needsUpdate = true;
  14981. if ( onLoad ) onLoad( texture );
  14982. }
  14983. };
  14984. cubeImage.onerror = onError;
  14985. cubeImage.crossOrigin = this.crossOrigin;
  14986. cubeImage.src = array[ i ];
  14987. }
  14988. return texture;
  14989. },
  14990. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  14991. var images = [];
  14992. images.loadCount = 0;
  14993. var texture = new THREE.CompressedTexture();
  14994. texture.image = images;
  14995. if ( mapping !== undefined ) texture.mapping = mapping;
  14996. // no flipping for cube textures
  14997. // (also flipping doesn't work for compressed textures )
  14998. texture.flipY = false;
  14999. // can't generate mipmaps for compressed textures
  15000. // mips must be embedded in DDS files
  15001. texture.generateMipmaps = false;
  15002. var generateCubeFaceCallback = function ( rq, img ) {
  15003. return function () {
  15004. var buffer = rq.response;
  15005. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15006. img.format = dds.format;
  15007. img.mipmaps = dds.mipmaps;
  15008. img.width = dds.width;
  15009. img.height = dds.height;
  15010. images.loadCount += 1;
  15011. if ( images.loadCount === 6 ) {
  15012. texture.format = dds.format;
  15013. texture.needsUpdate = true;
  15014. if ( onLoad ) onLoad( texture );
  15015. }
  15016. }
  15017. }
  15018. // compressed cubemap textures as 6 separate DDS files
  15019. if ( array instanceof Array ) {
  15020. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15021. var cubeImage = {};
  15022. images[ i ] = cubeImage;
  15023. var request = new XMLHttpRequest();
  15024. request.onload = generateCubeFaceCallback( request, cubeImage );
  15025. request.onerror = onError;
  15026. var url = array[ i ];
  15027. request.open( 'GET', url, true );
  15028. request.responseType = "arraybuffer";
  15029. request.send( null );
  15030. }
  15031. // compressed cubemap texture stored in a single DDS file
  15032. } else {
  15033. var url = array;
  15034. var request = new XMLHttpRequest();
  15035. request.onload = function( ) {
  15036. var buffer = request.response;
  15037. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15038. if ( dds.isCubemap ) {
  15039. var faces = dds.mipmaps.length / dds.mipmapCount;
  15040. for ( var f = 0; f < faces; f ++ ) {
  15041. images[ f ] = { mipmaps : [] };
  15042. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15043. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  15044. images[ f ].format = dds.format;
  15045. images[ f ].width = dds.width;
  15046. images[ f ].height = dds.height;
  15047. }
  15048. }
  15049. texture.format = dds.format;
  15050. texture.needsUpdate = true;
  15051. if ( onLoad ) onLoad( texture );
  15052. }
  15053. }
  15054. request.onerror = onError;
  15055. request.open( 'GET', url, true );
  15056. request.responseType = "arraybuffer";
  15057. request.send( null );
  15058. }
  15059. return texture;
  15060. },
  15061. parseDDS: function ( buffer, loadMipmaps ) {
  15062. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  15063. // Adapted from @toji's DDS utils
  15064. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  15065. // All values and structures referenced from:
  15066. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  15067. var DDS_MAGIC = 0x20534444;
  15068. var DDSD_CAPS = 0x1,
  15069. DDSD_HEIGHT = 0x2,
  15070. DDSD_WIDTH = 0x4,
  15071. DDSD_PITCH = 0x8,
  15072. DDSD_PIXELFORMAT = 0x1000,
  15073. DDSD_MIPMAPCOUNT = 0x20000,
  15074. DDSD_LINEARSIZE = 0x80000,
  15075. DDSD_DEPTH = 0x800000;
  15076. var DDSCAPS_COMPLEX = 0x8,
  15077. DDSCAPS_MIPMAP = 0x400000,
  15078. DDSCAPS_TEXTURE = 0x1000;
  15079. var DDSCAPS2_CUBEMAP = 0x200,
  15080. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  15081. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  15082. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  15083. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  15084. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  15085. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  15086. DDSCAPS2_VOLUME = 0x200000;
  15087. var DDPF_ALPHAPIXELS = 0x1,
  15088. DDPF_ALPHA = 0x2,
  15089. DDPF_FOURCC = 0x4,
  15090. DDPF_RGB = 0x40,
  15091. DDPF_YUV = 0x200,
  15092. DDPF_LUMINANCE = 0x20000;
  15093. function fourCCToInt32( value ) {
  15094. return value.charCodeAt(0) +
  15095. (value.charCodeAt(1) << 8) +
  15096. (value.charCodeAt(2) << 16) +
  15097. (value.charCodeAt(3) << 24);
  15098. }
  15099. function int32ToFourCC( value ) {
  15100. return String.fromCharCode(
  15101. value & 0xff,
  15102. (value >> 8) & 0xff,
  15103. (value >> 16) & 0xff,
  15104. (value >> 24) & 0xff
  15105. );
  15106. }
  15107. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  15108. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  15109. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  15110. var headerLengthInt = 31; // The header length in 32 bit ints
  15111. // Offsets into the header array
  15112. var off_magic = 0;
  15113. var off_size = 1;
  15114. var off_flags = 2;
  15115. var off_height = 3;
  15116. var off_width = 4;
  15117. var off_mipmapCount = 7;
  15118. var off_pfFlags = 20;
  15119. var off_pfFourCC = 21;
  15120. var off_caps = 27;
  15121. var off_caps2 = 28;
  15122. var off_caps3 = 29;
  15123. var off_caps4 = 30;
  15124. // Parse header
  15125. var header = new Int32Array( buffer, 0, headerLengthInt );
  15126. if ( header[ off_magic ] !== DDS_MAGIC ) {
  15127. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  15128. return dds;
  15129. }
  15130. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  15131. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  15132. return dds;
  15133. }
  15134. var blockBytes;
  15135. var fourCC = header[ off_pfFourCC ];
  15136. switch ( fourCC ) {
  15137. case FOURCC_DXT1:
  15138. blockBytes = 8;
  15139. dds.format = THREE.RGB_S3TC_DXT1_Format;
  15140. break;
  15141. case FOURCC_DXT3:
  15142. blockBytes = 16;
  15143. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  15144. break;
  15145. case FOURCC_DXT5:
  15146. blockBytes = 16;
  15147. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  15148. break;
  15149. default:
  15150. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  15151. return dds;
  15152. }
  15153. dds.mipmapCount = 1;
  15154. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  15155. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  15156. }
  15157. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  15158. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  15159. dds.width = header[ off_width ];
  15160. dds.height = header[ off_height ];
  15161. var dataOffset = header[ off_size ] + 4;
  15162. // Extract mipmaps buffers
  15163. var width = dds.width;
  15164. var height = dds.height;
  15165. var faces = dds.isCubemap ? 6 : 1;
  15166. for ( var face = 0; face < faces; face ++ ) {
  15167. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15168. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  15169. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  15170. var mipmap = { "data": byteArray, "width": width, "height": height };
  15171. dds.mipmaps.push( mipmap );
  15172. dataOffset += dataLength;
  15173. width = Math.max( width * 0.5, 1 );
  15174. height = Math.max( height * 0.5, 1 );
  15175. }
  15176. width = dds.width;
  15177. height = dds.height;
  15178. }
  15179. return dds;
  15180. },
  15181. getNormalMap: function ( image, depth ) {
  15182. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  15183. var cross = function ( a, b ) {
  15184. 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 ] ];
  15185. }
  15186. var subtract = function ( a, b ) {
  15187. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  15188. }
  15189. var normalize = function ( a ) {
  15190. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  15191. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  15192. }
  15193. depth = depth | 1;
  15194. var width = image.width;
  15195. var height = image.height;
  15196. var canvas = document.createElement( 'canvas' );
  15197. canvas.width = width;
  15198. canvas.height = height;
  15199. var context = canvas.getContext( '2d' );
  15200. context.drawImage( image, 0, 0 );
  15201. var data = context.getImageData( 0, 0, width, height ).data;
  15202. var imageData = context.createImageData( width, height );
  15203. var output = imageData.data;
  15204. for ( var x = 0; x < width; x ++ ) {
  15205. for ( var y = 0; y < height; y ++ ) {
  15206. var ly = y - 1 < 0 ? 0 : y - 1;
  15207. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  15208. var lx = x - 1 < 0 ? 0 : x - 1;
  15209. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  15210. var points = [];
  15211. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  15212. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  15213. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  15214. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  15215. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  15216. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  15217. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  15218. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  15219. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  15220. var normals = [];
  15221. var num_points = points.length;
  15222. for ( var i = 0; i < num_points; i ++ ) {
  15223. var v1 = points[ i ];
  15224. var v2 = points[ ( i + 1 ) % num_points ];
  15225. v1 = subtract( v1, origin );
  15226. v2 = subtract( v2, origin );
  15227. normals.push( normalize( cross( v1, v2 ) ) );
  15228. }
  15229. var normal = [ 0, 0, 0 ];
  15230. for ( var i = 0; i < normals.length; i ++ ) {
  15231. normal[ 0 ] += normals[ i ][ 0 ];
  15232. normal[ 1 ] += normals[ i ][ 1 ];
  15233. normal[ 2 ] += normals[ i ][ 2 ];
  15234. }
  15235. normal[ 0 ] /= normals.length;
  15236. normal[ 1 ] /= normals.length;
  15237. normal[ 2 ] /= normals.length;
  15238. var idx = ( y * width + x ) * 4;
  15239. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15240. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15241. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  15242. output[ idx + 3 ] = 255;
  15243. }
  15244. }
  15245. context.putImageData( imageData, 0, 0 );
  15246. return canvas;
  15247. },
  15248. generateDataTexture: function ( width, height, color ) {
  15249. var size = width * height;
  15250. var data = new Uint8Array( 3 * size );
  15251. var r = Math.floor( color.r * 255 );
  15252. var g = Math.floor( color.g * 255 );
  15253. var b = Math.floor( color.b * 255 );
  15254. for ( var i = 0; i < size; i ++ ) {
  15255. data[ i * 3 ] = r;
  15256. data[ i * 3 + 1 ] = g;
  15257. data[ i * 3 + 2 ] = b;
  15258. }
  15259. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  15260. texture.needsUpdate = true;
  15261. return texture;
  15262. }
  15263. };
  15264. /**
  15265. * @author alteredq / http://alteredqualia.com/
  15266. */
  15267. THREE.SceneUtils = {
  15268. createMultiMaterialObject: function ( geometry, materials ) {
  15269. var group = new THREE.Object3D();
  15270. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  15271. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  15272. }
  15273. return group;
  15274. },
  15275. detach : function ( child, parent, scene ) {
  15276. child.applyMatrix( parent.matrixWorld );
  15277. parent.remove( child );
  15278. scene.add( child );
  15279. },
  15280. attach: function ( child, scene, parent ) {
  15281. var matrixWorldInverse = new THREE.Matrix4();
  15282. matrixWorldInverse.getInverse( parent.matrixWorld );
  15283. child.applyMatrix( matrixWorldInverse );
  15284. scene.remove( child );
  15285. parent.add( child );
  15286. }
  15287. };
  15288. /**
  15289. * @author alteredq / http://alteredqualia.com/
  15290. * @author mrdoob / http://mrdoob.com/
  15291. *
  15292. * ShaderUtils currently contains:
  15293. *
  15294. * fresnel
  15295. * normal
  15296. * cube
  15297. *
  15298. */
  15299. THREE.ShaderUtils = {
  15300. lib: {
  15301. /* -------------------------------------------------------------------------
  15302. // Fresnel shader
  15303. // - based on Nvidia Cg tutorial
  15304. ------------------------------------------------------------------------- */
  15305. 'fresnel': {
  15306. uniforms: {
  15307. "mRefractionRatio": { type: "f", value: 1.02 },
  15308. "mFresnelBias": { type: "f", value: 0.1 },
  15309. "mFresnelPower": { type: "f", value: 2.0 },
  15310. "mFresnelScale": { type: "f", value: 1.0 },
  15311. "tCube": { type: "t", value: null }
  15312. },
  15313. fragmentShader: [
  15314. "uniform samplerCube tCube;",
  15315. "varying vec3 vReflect;",
  15316. "varying vec3 vRefract[3];",
  15317. "varying float vReflectionFactor;",
  15318. "void main() {",
  15319. "vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  15320. "vec4 refractedColor = vec4( 1.0 );",
  15321. "refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;",
  15322. "refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;",
  15323. "refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;",
  15324. "gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );",
  15325. "}"
  15326. ].join("\n"),
  15327. vertexShader: [
  15328. "uniform float mRefractionRatio;",
  15329. "uniform float mFresnelBias;",
  15330. "uniform float mFresnelScale;",
  15331. "uniform float mFresnelPower;",
  15332. "varying vec3 vReflect;",
  15333. "varying vec3 vRefract[3];",
  15334. "varying float vReflectionFactor;",
  15335. "void main() {",
  15336. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  15337. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  15338. "vec3 worldNormal = normalize( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );",
  15339. "vec3 I = worldPosition.xyz - cameraPosition;",
  15340. "vReflect = reflect( I, worldNormal );",
  15341. "vRefract[0] = refract( normalize( I ), worldNormal, mRefractionRatio );",
  15342. "vRefract[1] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.99 );",
  15343. "vRefract[2] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.98 );",
  15344. "vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), worldNormal ), mFresnelPower );",
  15345. "gl_Position = projectionMatrix * mvPosition;",
  15346. "}"
  15347. ].join("\n")
  15348. },
  15349. /* -------------------------------------------------------------------------
  15350. // Normal map shader
  15351. // - Blinn-Phong
  15352. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  15353. // - point and directional lights (use with "lights: true" material option)
  15354. ------------------------------------------------------------------------- */
  15355. 'normal' : {
  15356. uniforms: THREE.UniformsUtils.merge( [
  15357. THREE.UniformsLib[ "fog" ],
  15358. THREE.UniformsLib[ "lights" ],
  15359. THREE.UniformsLib[ "shadowmap" ],
  15360. {
  15361. "enableAO" : { type: "i", value: 0 },
  15362. "enableDiffuse" : { type: "i", value: 0 },
  15363. "enableSpecular" : { type: "i", value: 0 },
  15364. "enableReflection": { type: "i", value: 0 },
  15365. "enableDisplacement": { type: "i", value: 0 },
  15366. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  15367. "tDiffuse" : { type: "t", value: null },
  15368. "tCube" : { type: "t", value: null },
  15369. "tNormal" : { type: "t", value: null },
  15370. "tSpecular" : { type: "t", value: null },
  15371. "tAO" : { type: "t", value: null },
  15372. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  15373. "uDisplacementBias": { type: "f", value: 0.0 },
  15374. "uDisplacementScale": { type: "f", value: 1.0 },
  15375. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  15376. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  15377. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  15378. "uShininess": { type: "f", value: 30 },
  15379. "uOpacity": { type: "f", value: 1 },
  15380. "useRefract": { type: "i", value: 0 },
  15381. "uRefractionRatio": { type: "f", value: 0.98 },
  15382. "uReflectivity": { type: "f", value: 0.5 },
  15383. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  15384. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  15385. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  15386. }
  15387. ] ),
  15388. fragmentShader: [
  15389. "uniform vec3 uAmbientColor;",
  15390. "uniform vec3 uDiffuseColor;",
  15391. "uniform vec3 uSpecularColor;",
  15392. "uniform float uShininess;",
  15393. "uniform float uOpacity;",
  15394. "uniform bool enableDiffuse;",
  15395. "uniform bool enableSpecular;",
  15396. "uniform bool enableAO;",
  15397. "uniform bool enableReflection;",
  15398. "uniform sampler2D tDiffuse;",
  15399. "uniform sampler2D tNormal;",
  15400. "uniform sampler2D tSpecular;",
  15401. "uniform sampler2D tAO;",
  15402. "uniform samplerCube tCube;",
  15403. "uniform vec2 uNormalScale;",
  15404. "uniform bool useRefract;",
  15405. "uniform float uRefractionRatio;",
  15406. "uniform float uReflectivity;",
  15407. "varying vec3 vTangent;",
  15408. "varying vec3 vBinormal;",
  15409. "varying vec3 vNormal;",
  15410. "varying vec2 vUv;",
  15411. "uniform vec3 ambientLightColor;",
  15412. "#if MAX_DIR_LIGHTS > 0",
  15413. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  15414. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  15415. "#endif",
  15416. "#if MAX_HEMI_LIGHTS > 0",
  15417. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  15418. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  15419. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  15420. "#endif",
  15421. "#if MAX_POINT_LIGHTS > 0",
  15422. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  15423. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  15424. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  15425. "#endif",
  15426. "#if MAX_SPOT_LIGHTS > 0",
  15427. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  15428. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  15429. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  15430. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  15431. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  15432. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  15433. "#endif",
  15434. "#ifdef WRAP_AROUND",
  15435. "uniform vec3 wrapRGB;",
  15436. "#endif",
  15437. "varying vec3 vWorldPosition;",
  15438. "varying vec3 vViewPosition;",
  15439. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  15440. THREE.ShaderChunk[ "fog_pars_fragment" ],
  15441. "void main() {",
  15442. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  15443. "vec3 specularTex = vec3( 1.0 );",
  15444. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  15445. "normalTex.xy *= uNormalScale;",
  15446. "normalTex = normalize( normalTex );",
  15447. "if( enableDiffuse ) {",
  15448. "#ifdef GAMMA_INPUT",
  15449. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  15450. "texelColor.xyz *= texelColor.xyz;",
  15451. "gl_FragColor = gl_FragColor * texelColor;",
  15452. "#else",
  15453. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  15454. "#endif",
  15455. "}",
  15456. "if( enableAO ) {",
  15457. "#ifdef GAMMA_INPUT",
  15458. "vec4 aoColor = texture2D( tAO, vUv );",
  15459. "aoColor.xyz *= aoColor.xyz;",
  15460. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  15461. "#else",
  15462. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  15463. "#endif",
  15464. "}",
  15465. "if( enableSpecular )",
  15466. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  15467. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  15468. "vec3 finalNormal = tsb * normalTex;",
  15469. "#ifdef FLIP_SIDED",
  15470. "finalNormal = -finalNormal;",
  15471. "#endif",
  15472. "vec3 normal = normalize( finalNormal );",
  15473. "vec3 viewPosition = normalize( vViewPosition );",
  15474. // point lights
  15475. "#if MAX_POINT_LIGHTS > 0",
  15476. "vec3 pointDiffuse = vec3( 0.0 );",
  15477. "vec3 pointSpecular = vec3( 0.0 );",
  15478. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  15479. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  15480. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  15481. "float pointDistance = 1.0;",
  15482. "if ( pointLightDistance[ i ] > 0.0 )",
  15483. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  15484. "pointVector = normalize( pointVector );",
  15485. // diffuse
  15486. "#ifdef WRAP_AROUND",
  15487. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  15488. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  15489. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  15490. "#else",
  15491. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  15492. "#endif",
  15493. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  15494. // specular
  15495. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  15496. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  15497. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  15498. "#ifdef PHYSICALLY_BASED_SHADING",
  15499. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15500. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15501. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  15502. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  15503. "#else",
  15504. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  15505. "#endif",
  15506. "}",
  15507. "#endif",
  15508. // spot lights
  15509. "#if MAX_SPOT_LIGHTS > 0",
  15510. "vec3 spotDiffuse = vec3( 0.0 );",
  15511. "vec3 spotSpecular = vec3( 0.0 );",
  15512. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  15513. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  15514. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  15515. "float spotDistance = 1.0;",
  15516. "if ( spotLightDistance[ i ] > 0.0 )",
  15517. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  15518. "spotVector = normalize( spotVector );",
  15519. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  15520. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  15521. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  15522. // diffuse
  15523. "#ifdef WRAP_AROUND",
  15524. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  15525. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  15526. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  15527. "#else",
  15528. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  15529. "#endif",
  15530. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  15531. // specular
  15532. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  15533. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  15534. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  15535. "#ifdef PHYSICALLY_BASED_SHADING",
  15536. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15537. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15538. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  15539. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  15540. "#else",
  15541. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  15542. "#endif",
  15543. "}",
  15544. "}",
  15545. "#endif",
  15546. // directional lights
  15547. "#if MAX_DIR_LIGHTS > 0",
  15548. "vec3 dirDiffuse = vec3( 0.0 );",
  15549. "vec3 dirSpecular = vec3( 0.0 );",
  15550. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  15551. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  15552. "vec3 dirVector = normalize( lDirection.xyz );",
  15553. // diffuse
  15554. "#ifdef WRAP_AROUND",
  15555. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  15556. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  15557. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  15558. "#else",
  15559. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  15560. "#endif",
  15561. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  15562. // specular
  15563. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  15564. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  15565. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  15566. "#ifdef PHYSICALLY_BASED_SHADING",
  15567. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15568. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15569. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  15570. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  15571. "#else",
  15572. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  15573. "#endif",
  15574. "}",
  15575. "#endif",
  15576. // hemisphere lights
  15577. "#if MAX_HEMI_LIGHTS > 0",
  15578. "vec3 hemiDiffuse = vec3( 0.0 );",
  15579. "vec3 hemiSpecular = vec3( 0.0 );" ,
  15580. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  15581. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  15582. "vec3 lVector = normalize( lDirection.xyz );",
  15583. // diffuse
  15584. "float dotProduct = dot( normal, lVector );",
  15585. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  15586. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  15587. "hemiDiffuse += uDiffuseColor * hemiColor;",
  15588. // specular (sky light)
  15589. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  15590. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  15591. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  15592. // specular (ground light)
  15593. "vec3 lVectorGround = -lVector;",
  15594. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  15595. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  15596. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  15597. "#ifdef PHYSICALLY_BASED_SHADING",
  15598. "float dotProductGround = dot( normal, lVectorGround );",
  15599. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15600. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15601. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  15602. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  15603. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  15604. "#else",
  15605. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  15606. "#endif",
  15607. "}",
  15608. "#endif",
  15609. // all lights contribution summation
  15610. "vec3 totalDiffuse = vec3( 0.0 );",
  15611. "vec3 totalSpecular = vec3( 0.0 );",
  15612. "#if MAX_DIR_LIGHTS > 0",
  15613. "totalDiffuse += dirDiffuse;",
  15614. "totalSpecular += dirSpecular;",
  15615. "#endif",
  15616. "#if MAX_HEMI_LIGHTS > 0",
  15617. "totalDiffuse += hemiDiffuse;",
  15618. "totalSpecular += hemiSpecular;",
  15619. "#endif",
  15620. "#if MAX_POINT_LIGHTS > 0",
  15621. "totalDiffuse += pointDiffuse;",
  15622. "totalSpecular += pointSpecular;",
  15623. "#endif",
  15624. "#if MAX_SPOT_LIGHTS > 0",
  15625. "totalDiffuse += spotDiffuse;",
  15626. "totalSpecular += spotSpecular;",
  15627. "#endif",
  15628. "#ifdef METAL",
  15629. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  15630. "#else",
  15631. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  15632. "#endif",
  15633. "if ( enableReflection ) {",
  15634. "vec3 vReflect;",
  15635. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  15636. "if ( useRefract ) {",
  15637. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  15638. "} else {",
  15639. "vReflect = reflect( cameraToVertex, normal );",
  15640. "}",
  15641. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  15642. "#ifdef GAMMA_INPUT",
  15643. "cubeColor.xyz *= cubeColor.xyz;",
  15644. "#endif",
  15645. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  15646. "}",
  15647. THREE.ShaderChunk[ "shadowmap_fragment" ],
  15648. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  15649. THREE.ShaderChunk[ "fog_fragment" ],
  15650. "}"
  15651. ].join("\n"),
  15652. vertexShader: [
  15653. "attribute vec4 tangent;",
  15654. "uniform vec2 uOffset;",
  15655. "uniform vec2 uRepeat;",
  15656. "uniform bool enableDisplacement;",
  15657. "#ifdef VERTEX_TEXTURES",
  15658. "uniform sampler2D tDisplacement;",
  15659. "uniform float uDisplacementScale;",
  15660. "uniform float uDisplacementBias;",
  15661. "#endif",
  15662. "varying vec3 vTangent;",
  15663. "varying vec3 vBinormal;",
  15664. "varying vec3 vNormal;",
  15665. "varying vec2 vUv;",
  15666. "varying vec3 vWorldPosition;",
  15667. "varying vec3 vViewPosition;",
  15668. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  15669. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  15670. "void main() {",
  15671. THREE.ShaderChunk[ "skinbase_vertex" ],
  15672. THREE.ShaderChunk[ "skinnormal_vertex" ],
  15673. // normal, tangent and binormal vectors
  15674. "#ifdef USE_SKINNING",
  15675. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  15676. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  15677. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  15678. "#else",
  15679. "vNormal = normalize( normalMatrix * normal );",
  15680. "vTangent = normalize( normalMatrix * tangent.xyz );",
  15681. "#endif",
  15682. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  15683. "vUv = uv * uRepeat + uOffset;",
  15684. // displacement mapping
  15685. "vec3 displacedPosition;",
  15686. "#ifdef VERTEX_TEXTURES",
  15687. "if ( enableDisplacement ) {",
  15688. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  15689. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  15690. "displacedPosition = position + normalize( normal ) * df;",
  15691. "} else {",
  15692. "#ifdef USE_SKINNING",
  15693. "vec4 skinVertex = vec4( position, 1.0 );",
  15694. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  15695. "skinned += boneMatY * skinVertex * skinWeight.y;",
  15696. "displacedPosition = skinned.xyz;",
  15697. "#else",
  15698. "displacedPosition = position;",
  15699. "#endif",
  15700. "}",
  15701. "#else",
  15702. "#ifdef USE_SKINNING",
  15703. "vec4 skinVertex = vec4( position, 1.0 );",
  15704. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  15705. "skinned += boneMatY * skinVertex * skinWeight.y;",
  15706. "displacedPosition = skinned.xyz;",
  15707. "#else",
  15708. "displacedPosition = position;",
  15709. "#endif",
  15710. "#endif",
  15711. //
  15712. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  15713. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  15714. "gl_Position = projectionMatrix * mvPosition;",
  15715. //
  15716. "vWorldPosition = worldPosition.xyz;",
  15717. "vViewPosition = -mvPosition.xyz;",
  15718. // shadows
  15719. "#ifdef USE_SHADOWMAP",
  15720. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  15721. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  15722. "}",
  15723. "#endif",
  15724. "}"
  15725. ].join("\n")
  15726. },
  15727. /* -------------------------------------------------------------------------
  15728. // Cube map shader
  15729. ------------------------------------------------------------------------- */
  15730. 'cube': {
  15731. uniforms: { "tCube": { type: "t", value: null },
  15732. "tFlip": { type: "f", value: -1 } },
  15733. vertexShader: [
  15734. "varying vec3 vWorldPosition;",
  15735. "void main() {",
  15736. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  15737. "vWorldPosition = worldPosition.xyz;",
  15738. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  15739. "}"
  15740. ].join("\n"),
  15741. fragmentShader: [
  15742. "uniform samplerCube tCube;",
  15743. "uniform float tFlip;",
  15744. "varying vec3 vWorldPosition;",
  15745. "void main() {",
  15746. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  15747. "}"
  15748. ].join("\n")
  15749. }
  15750. }
  15751. };
  15752. /**
  15753. * @author zz85 / http://www.lab4games.net/zz85/blog
  15754. * @author alteredq / http://alteredqualia.com/
  15755. *
  15756. * For Text operations in three.js (See TextGeometry)
  15757. *
  15758. * It uses techniques used in:
  15759. *
  15760. * typeface.js and canvastext
  15761. * For converting fonts and rendering with javascript
  15762. * http://typeface.neocracy.org
  15763. *
  15764. * Triangulation ported from AS3
  15765. * Simple Polygon Triangulation
  15766. * http://actionsnippet.com/?p=1462
  15767. *
  15768. * A Method to triangulate shapes with holes
  15769. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  15770. *
  15771. */
  15772. THREE.FontUtils = {
  15773. faces : {},
  15774. // Just for now. face[weight][style]
  15775. face : "helvetiker",
  15776. weight: "normal",
  15777. style : "normal",
  15778. size : 150,
  15779. divisions : 10,
  15780. getFace : function() {
  15781. return this.faces[ this.face ][ this.weight ][ this.style ];
  15782. },
  15783. loadFace : function( data ) {
  15784. var family = data.familyName.toLowerCase();
  15785. var ThreeFont = this;
  15786. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  15787. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  15788. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15789. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15790. return data;
  15791. },
  15792. drawText : function( text ) {
  15793. var characterPts = [], allPts = [];
  15794. // RenderText
  15795. var i, p,
  15796. face = this.getFace(),
  15797. scale = this.size / face.resolution,
  15798. offset = 0,
  15799. chars = String( text ).split( '' ),
  15800. length = chars.length;
  15801. var fontPaths = [];
  15802. for ( i = 0; i < length; i ++ ) {
  15803. var path = new THREE.Path();
  15804. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  15805. offset += ret.offset;
  15806. fontPaths.push( ret.path );
  15807. }
  15808. // get the width
  15809. var width = offset / 2;
  15810. //
  15811. // for ( p = 0; p < allPts.length; p++ ) {
  15812. //
  15813. // allPts[ p ].x -= width;
  15814. //
  15815. // }
  15816. //var extract = this.extractPoints( allPts, characterPts );
  15817. //extract.contour = allPts;
  15818. //extract.paths = fontPaths;
  15819. //extract.offset = width;
  15820. return { paths : fontPaths, offset : width };
  15821. },
  15822. extractGlyphPoints : function( c, face, scale, offset, path ) {
  15823. var pts = [];
  15824. var i, i2, divisions,
  15825. outline, action, length,
  15826. scaleX, scaleY,
  15827. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  15828. laste,
  15829. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  15830. if ( !glyph ) return;
  15831. if ( glyph.o ) {
  15832. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  15833. length = outline.length;
  15834. scaleX = scale;
  15835. scaleY = scale;
  15836. for ( i = 0; i < length; ) {
  15837. action = outline[ i ++ ];
  15838. //console.log( action );
  15839. switch( action ) {
  15840. case 'm':
  15841. // Move To
  15842. x = outline[ i++ ] * scaleX + offset;
  15843. y = outline[ i++ ] * scaleY;
  15844. path.moveTo( x, y );
  15845. break;
  15846. case 'l':
  15847. // Line To
  15848. x = outline[ i++ ] * scaleX + offset;
  15849. y = outline[ i++ ] * scaleY;
  15850. path.lineTo(x,y);
  15851. break;
  15852. case 'q':
  15853. // QuadraticCurveTo
  15854. cpx = outline[ i++ ] * scaleX + offset;
  15855. cpy = outline[ i++ ] * scaleY;
  15856. cpx1 = outline[ i++ ] * scaleX + offset;
  15857. cpy1 = outline[ i++ ] * scaleY;
  15858. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  15859. laste = pts[ pts.length - 1 ];
  15860. if ( laste ) {
  15861. cpx0 = laste.x;
  15862. cpy0 = laste.y;
  15863. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15864. var t = i2 / divisions;
  15865. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  15866. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  15867. }
  15868. }
  15869. break;
  15870. case 'b':
  15871. // Cubic Bezier Curve
  15872. cpx = outline[ i++ ] * scaleX + offset;
  15873. cpy = outline[ i++ ] * scaleY;
  15874. cpx1 = outline[ i++ ] * scaleX + offset;
  15875. cpy1 = outline[ i++ ] * -scaleY;
  15876. cpx2 = outline[ i++ ] * scaleX + offset;
  15877. cpy2 = outline[ i++ ] * -scaleY;
  15878. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  15879. laste = pts[ pts.length - 1 ];
  15880. if ( laste ) {
  15881. cpx0 = laste.x;
  15882. cpy0 = laste.y;
  15883. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15884. var t = i2 / divisions;
  15885. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  15886. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  15887. }
  15888. }
  15889. break;
  15890. }
  15891. }
  15892. }
  15893. return { offset: glyph.ha*scale, path:path};
  15894. }
  15895. };
  15896. THREE.FontUtils.generateShapes = function( text, parameters ) {
  15897. // Parameters
  15898. parameters = parameters || {};
  15899. var size = parameters.size !== undefined ? parameters.size : 100;
  15900. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  15901. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  15902. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  15903. var style = parameters.style !== undefined ? parameters.style : "normal";
  15904. THREE.FontUtils.size = size;
  15905. THREE.FontUtils.divisions = curveSegments;
  15906. THREE.FontUtils.face = font;
  15907. THREE.FontUtils.weight = weight;
  15908. THREE.FontUtils.style = style;
  15909. // Get a Font data json object
  15910. var data = THREE.FontUtils.drawText( text );
  15911. var paths = data.paths;
  15912. var shapes = [];
  15913. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  15914. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  15915. }
  15916. return shapes;
  15917. };
  15918. /**
  15919. * This code is a quick port of code written in C++ which was submitted to
  15920. * flipcode.com by John W. Ratcliff // July 22, 2000
  15921. * See original code and more information here:
  15922. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  15923. *
  15924. * ported to actionscript by Zevan Rosser
  15925. * www.actionsnippet.com
  15926. *
  15927. * ported to javascript by Joshua Koo
  15928. * http://www.lab4games.net/zz85/blog
  15929. *
  15930. */
  15931. ( function( namespace ) {
  15932. var EPSILON = 0.0000000001;
  15933. // takes in an contour array and returns
  15934. var process = function( contour, indices ) {
  15935. var n = contour.length;
  15936. if ( n < 3 ) return null;
  15937. var result = [],
  15938. verts = [],
  15939. vertIndices = [];
  15940. /* we want a counter-clockwise polygon in verts */
  15941. var u, v, w;
  15942. if ( area( contour ) > 0.0 ) {
  15943. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  15944. } else {
  15945. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  15946. }
  15947. var nv = n;
  15948. /* remove nv - 2 vertices, creating 1 triangle every time */
  15949. var count = 2 * nv; /* error detection */
  15950. for( v = nv - 1; nv > 2; ) {
  15951. /* if we loop, it is probably a non-simple polygon */
  15952. if ( ( count-- ) <= 0 ) {
  15953. //** Triangulate: ERROR - probable bad polygon!
  15954. //throw ( "Warning, unable to triangulate polygon!" );
  15955. //return null;
  15956. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  15957. console.log( "Warning, unable to triangulate polygon!" );
  15958. if ( indices ) return vertIndices;
  15959. return result;
  15960. }
  15961. /* three consecutive vertices in current polygon, <u,v,w> */
  15962. u = v; if ( nv <= u ) u = 0; /* previous */
  15963. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  15964. w = v + 1; if ( nv <= w ) w = 0; /* next */
  15965. if ( snip( contour, u, v, w, nv, verts ) ) {
  15966. var a, b, c, s, t;
  15967. /* true names of the vertices */
  15968. a = verts[ u ];
  15969. b = verts[ v ];
  15970. c = verts[ w ];
  15971. /* output Triangle */
  15972. result.push( [ contour[ a ],
  15973. contour[ b ],
  15974. contour[ c ] ] );
  15975. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  15976. /* remove v from the remaining polygon */
  15977. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  15978. verts[ s ] = verts[ t ];
  15979. }
  15980. nv--;
  15981. /* reset error detection counter */
  15982. count = 2 * nv;
  15983. }
  15984. }
  15985. if ( indices ) return vertIndices;
  15986. return result;
  15987. };
  15988. // calculate area of the contour polygon
  15989. var area = function ( contour ) {
  15990. var n = contour.length;
  15991. var a = 0.0;
  15992. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  15993. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  15994. }
  15995. return a * 0.5;
  15996. };
  15997. var snip = function ( contour, u, v, w, n, verts ) {
  15998. var p;
  15999. var ax, ay, bx, by;
  16000. var cx, cy, px, py;
  16001. ax = contour[ verts[ u ] ].x;
  16002. ay = contour[ verts[ u ] ].y;
  16003. bx = contour[ verts[ v ] ].x;
  16004. by = contour[ verts[ v ] ].y;
  16005. cx = contour[ verts[ w ] ].x;
  16006. cy = contour[ verts[ w ] ].y;
  16007. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16008. var aX, aY, bX, bY, cX, cY;
  16009. var apx, apy, bpx, bpy, cpx, cpy;
  16010. var cCROSSap, bCROSScp, aCROSSbp;
  16011. aX = cx - bx; aY = cy - by;
  16012. bX = ax - cx; bY = ay - cy;
  16013. cX = bx - ax; cY = by - ay;
  16014. for ( p = 0; p < n; p++ ) {
  16015. if( (p === u) || (p === v) || (p === w) ) continue;
  16016. px = contour[ verts[ p ] ].x
  16017. py = contour[ verts[ p ] ].y
  16018. apx = px - ax; apy = py - ay;
  16019. bpx = px - bx; bpy = py - by;
  16020. cpx = px - cx; cpy = py - cy;
  16021. // see if p is inside triangle abc
  16022. aCROSSbp = aX*bpy - aY*bpx;
  16023. cCROSSap = cX*apy - cY*apx;
  16024. bCROSScp = bX*cpy - bY*cpx;
  16025. if ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) ) return false;
  16026. }
  16027. return true;
  16028. };
  16029. namespace.Triangulate = process;
  16030. namespace.Triangulate.area = area;
  16031. return namespace;
  16032. })(THREE.FontUtils);
  16033. // To use the typeface.js face files, hook up the API
  16034. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };/**
  16035. * @author zz85 / http://www.lab4games.net/zz85/blog
  16036. * Extensible curve object
  16037. *
  16038. * Some common of Curve methods
  16039. * .getPoint(t), getTangent(t)
  16040. * .getPointAt(u), getTagentAt(u)
  16041. * .getPoints(), .getSpacedPoints()
  16042. * .getLength()
  16043. * .updateArcLengths()
  16044. *
  16045. * This file contains following classes:
  16046. *
  16047. * -- 2d classes --
  16048. * THREE.Curve
  16049. * THREE.LineCurve
  16050. * THREE.QuadraticBezierCurve
  16051. * THREE.CubicBezierCurve
  16052. * THREE.SplineCurve
  16053. * THREE.ArcCurve
  16054. * THREE.EllipseCurve
  16055. *
  16056. * -- 3d classes --
  16057. * THREE.LineCurve3
  16058. * THREE.QuadraticBezierCurve3
  16059. * THREE.CubicBezierCurve3
  16060. * THREE.SplineCurve3
  16061. * THREE.ClosedSplineCurve3
  16062. *
  16063. * A series of curves can be represented as a THREE.CurvePath
  16064. *
  16065. **/
  16066. /**************************************************************
  16067. * Abstract Curve base class
  16068. **************************************************************/
  16069. THREE.Curve = function () {
  16070. };
  16071. // Virtual base class method to overwrite and implement in subclasses
  16072. // - t [0 .. 1]
  16073. THREE.Curve.prototype.getPoint = function ( t ) {
  16074. console.log( "Warning, getPoint() not implemented!" );
  16075. return null;
  16076. };
  16077. // Get point at relative position in curve according to arc length
  16078. // - u [0 .. 1]
  16079. THREE.Curve.prototype.getPointAt = function ( u ) {
  16080. var t = this.getUtoTmapping( u );
  16081. return this.getPoint( t );
  16082. };
  16083. // Get sequence of points using getPoint( t )
  16084. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16085. if ( !divisions ) divisions = 5;
  16086. var d, pts = [];
  16087. for ( d = 0; d <= divisions; d ++ ) {
  16088. pts.push( this.getPoint( d / divisions ) );
  16089. }
  16090. return pts;
  16091. };
  16092. // Get sequence of points using getPointAt( u )
  16093. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16094. if ( !divisions ) divisions = 5;
  16095. var d, pts = [];
  16096. for ( d = 0; d <= divisions; d ++ ) {
  16097. pts.push( this.getPointAt( d / divisions ) );
  16098. }
  16099. return pts;
  16100. };
  16101. // Get total curve arc length
  16102. THREE.Curve.prototype.getLength = function () {
  16103. var lengths = this.getLengths();
  16104. return lengths[ lengths.length - 1 ];
  16105. };
  16106. // Get list of cumulative segment lengths
  16107. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16108. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16109. if ( this.cacheArcLengths
  16110. && ( this.cacheArcLengths.length == divisions + 1 )
  16111. && !this.needsUpdate) {
  16112. //console.log( "cached", this.cacheArcLengths );
  16113. return this.cacheArcLengths;
  16114. }
  16115. this.needsUpdate = false;
  16116. var cache = [];
  16117. var current, last = this.getPoint( 0 );
  16118. var p, sum = 0;
  16119. cache.push( 0 );
  16120. for ( p = 1; p <= divisions; p ++ ) {
  16121. current = this.getPoint ( p / divisions );
  16122. sum += current.distanceTo( last );
  16123. cache.push( sum );
  16124. last = current;
  16125. }
  16126. this.cacheArcLengths = cache;
  16127. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16128. };
  16129. THREE.Curve.prototype.updateArcLengths = function() {
  16130. this.needsUpdate = true;
  16131. this.getLengths();
  16132. };
  16133. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16134. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16135. var arcLengths = this.getLengths();
  16136. var i = 0, il = arcLengths.length;
  16137. var targetArcLength; // The targeted u distance value to get
  16138. if ( distance ) {
  16139. targetArcLength = distance;
  16140. } else {
  16141. targetArcLength = u * arcLengths[ il - 1 ];
  16142. }
  16143. //var time = Date.now();
  16144. // binary search for the index with largest value smaller than target u distance
  16145. var low = 0, high = il - 1, comparison;
  16146. while ( low <= high ) {
  16147. 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
  16148. comparison = arcLengths[ i ] - targetArcLength;
  16149. if ( comparison < 0 ) {
  16150. low = i + 1;
  16151. continue;
  16152. } else if ( comparison > 0 ) {
  16153. high = i - 1;
  16154. continue;
  16155. } else {
  16156. high = i;
  16157. break;
  16158. // DONE
  16159. }
  16160. }
  16161. i = high;
  16162. //console.log('b' , i, low, high, Date.now()- time);
  16163. if ( arcLengths[ i ] == targetArcLength ) {
  16164. var t = i / ( il - 1 );
  16165. return t;
  16166. }
  16167. // we could get finer grain at lengths, or use simple interpolatation between two points
  16168. var lengthBefore = arcLengths[ i ];
  16169. var lengthAfter = arcLengths[ i + 1 ];
  16170. var segmentLength = lengthAfter - lengthBefore;
  16171. // determine where we are between the 'before' and 'after' points
  16172. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16173. // add that fractional amount to t
  16174. var t = ( i + segmentFraction ) / ( il -1 );
  16175. return t;
  16176. };
  16177. // Returns a unit vector tangent at t
  16178. // In case any sub curve does not implement its tangent derivation,
  16179. // 2 points a small delta apart will be used to find its gradient
  16180. // which seems to give a reasonable approximation
  16181. THREE.Curve.prototype.getTangent = function( t ) {
  16182. var delta = 0.0001;
  16183. var t1 = t - delta;
  16184. var t2 = t + delta;
  16185. // Capping in case of danger
  16186. if ( t1 < 0 ) t1 = 0;
  16187. if ( t2 > 1 ) t2 = 1;
  16188. var pt1 = this.getPoint( t1 );
  16189. var pt2 = this.getPoint( t2 );
  16190. var vec = pt2.clone().sub(pt1);
  16191. return vec.normalize();
  16192. };
  16193. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16194. var t = this.getUtoTmapping( u );
  16195. return this.getTangent( t );
  16196. };
  16197. /**************************************************************
  16198. * Line
  16199. **************************************************************/
  16200. THREE.LineCurve = function ( v1, v2 ) {
  16201. this.v1 = v1;
  16202. this.v2 = v2;
  16203. };
  16204. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  16205. THREE.LineCurve.prototype.getPoint = function ( t ) {
  16206. var point = this.v2.clone().sub(this.v1);
  16207. point.multiplyScalar( t ).add( this.v1 );
  16208. return point;
  16209. };
  16210. // Line curve is linear, so we can overwrite default getPointAt
  16211. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  16212. return this.getPoint( u );
  16213. };
  16214. THREE.LineCurve.prototype.getTangent = function( t ) {
  16215. var tangent = this.v2.clone().sub(this.v1);
  16216. return tangent.normalize();
  16217. };
  16218. /**************************************************************
  16219. * Quadratic Bezier curve
  16220. **************************************************************/
  16221. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  16222. this.v0 = v0;
  16223. this.v1 = v1;
  16224. this.v2 = v2;
  16225. };
  16226. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  16227. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  16228. var tx, ty;
  16229. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  16230. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  16231. return new THREE.Vector2( tx, ty );
  16232. };
  16233. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  16234. var tx, ty;
  16235. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  16236. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  16237. // returns unit vector
  16238. var tangent = new THREE.Vector2( tx, ty );
  16239. tangent.normalize();
  16240. return tangent;
  16241. };
  16242. /**************************************************************
  16243. * Cubic Bezier curve
  16244. **************************************************************/
  16245. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  16246. this.v0 = v0;
  16247. this.v1 = v1;
  16248. this.v2 = v2;
  16249. this.v3 = v3;
  16250. };
  16251. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  16252. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  16253. var tx, ty;
  16254. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16255. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16256. return new THREE.Vector2( tx, ty );
  16257. };
  16258. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  16259. var tx, ty;
  16260. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16261. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16262. var tangent = new THREE.Vector2( tx, ty );
  16263. tangent.normalize();
  16264. return tangent;
  16265. };
  16266. /**************************************************************
  16267. * Spline curve
  16268. **************************************************************/
  16269. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  16270. this.points = (points == undefined) ? [] : points;
  16271. };
  16272. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  16273. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  16274. var v = new THREE.Vector2();
  16275. var c = [];
  16276. var points = this.points, point, intPoint, weight;
  16277. point = ( points.length - 1 ) * t;
  16278. intPoint = Math.floor( point );
  16279. weight = point - intPoint;
  16280. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16281. c[ 1 ] = intPoint;
  16282. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  16283. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  16284. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16285. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16286. return v;
  16287. };
  16288. /**************************************************************
  16289. * Ellipse curve
  16290. **************************************************************/
  16291. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  16292. aStartAngle, aEndAngle,
  16293. aClockwise ) {
  16294. this.aX = aX;
  16295. this.aY = aY;
  16296. this.xRadius = xRadius;
  16297. this.yRadius = yRadius;
  16298. this.aStartAngle = aStartAngle;
  16299. this.aEndAngle = aEndAngle;
  16300. this.aClockwise = aClockwise;
  16301. };
  16302. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  16303. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  16304. var deltaAngle = this.aEndAngle - this.aStartAngle;
  16305. if ( !this.aClockwise ) {
  16306. t = 1 - t;
  16307. }
  16308. var angle = this.aStartAngle + t * deltaAngle;
  16309. var tx = this.aX + this.xRadius * Math.cos( angle );
  16310. var ty = this.aY + this.yRadius * Math.sin( angle );
  16311. return new THREE.Vector2( tx, ty );
  16312. };
  16313. /**************************************************************
  16314. * Arc curve
  16315. **************************************************************/
  16316. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  16317. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  16318. };
  16319. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  16320. /**************************************************************
  16321. * Utils
  16322. **************************************************************/
  16323. THREE.Curve.Utils = {
  16324. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16325. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16326. },
  16327. // Puay Bing, thanks for helping with this derivative!
  16328. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16329. return -3 * p0 * (1 - t) * (1 - t) +
  16330. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  16331. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  16332. 3 * t * t * p3;
  16333. },
  16334. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16335. // To check if my formulas are correct
  16336. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16337. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16338. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  16339. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16340. return h00 + h10 + h01 + h11;
  16341. },
  16342. // Catmull-Rom
  16343. interpolate: function( p0, p1, p2, p3, t ) {
  16344. var v0 = ( p2 - p0 ) * 0.5;
  16345. var v1 = ( p3 - p1 ) * 0.5;
  16346. var t2 = t * t;
  16347. var t3 = t * t2;
  16348. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16349. }
  16350. };
  16351. // TODO: Transformation for Curves?
  16352. /**************************************************************
  16353. * 3D Curves
  16354. **************************************************************/
  16355. // A Factory method for creating new curve subclasses
  16356. THREE.Curve.create = function ( constructor, getPointFunc ) {
  16357. constructor.prototype = Object.create( THREE.Curve.prototype );
  16358. constructor.prototype.getPoint = getPointFunc;
  16359. return constructor;
  16360. };
  16361. /**************************************************************
  16362. * Line3D
  16363. **************************************************************/
  16364. THREE.LineCurve3 = THREE.Curve.create(
  16365. function ( v1, v2 ) {
  16366. this.v1 = v1;
  16367. this.v2 = v2;
  16368. },
  16369. function ( t ) {
  16370. var r = new THREE.Vector3();
  16371. r.subVectors( this.v2, this.v1 ); // diff
  16372. r.multiplyScalar( t );
  16373. r.add( this.v1 );
  16374. return r;
  16375. }
  16376. );
  16377. /**************************************************************
  16378. * Quadratic Bezier 3D curve
  16379. **************************************************************/
  16380. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  16381. function ( v0, v1, v2 ) {
  16382. this.v0 = v0;
  16383. this.v1 = v1;
  16384. this.v2 = v2;
  16385. },
  16386. function ( t ) {
  16387. var tx, ty, tz;
  16388. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  16389. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  16390. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  16391. return new THREE.Vector3( tx, ty, tz );
  16392. }
  16393. );
  16394. /**************************************************************
  16395. * Cubic Bezier 3D curve
  16396. **************************************************************/
  16397. THREE.CubicBezierCurve3 = THREE.Curve.create(
  16398. function ( v0, v1, v2, v3 ) {
  16399. this.v0 = v0;
  16400. this.v1 = v1;
  16401. this.v2 = v2;
  16402. this.v3 = v3;
  16403. },
  16404. function ( t ) {
  16405. var tx, ty, tz;
  16406. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16407. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16408. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  16409. return new THREE.Vector3( tx, ty, tz );
  16410. }
  16411. );
  16412. /**************************************************************
  16413. * Spline 3D curve
  16414. **************************************************************/
  16415. THREE.SplineCurve3 = THREE.Curve.create(
  16416. function ( points /* array of Vector3 */) {
  16417. this.points = (points == undefined) ? [] : points;
  16418. },
  16419. function ( t ) {
  16420. var v = new THREE.Vector3();
  16421. var c = [];
  16422. var points = this.points, point, intPoint, weight;
  16423. point = ( points.length - 1 ) * t;
  16424. intPoint = Math.floor( point );
  16425. weight = point - intPoint;
  16426. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16427. c[ 1 ] = intPoint;
  16428. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16429. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16430. var pt0 = points[ c[0] ],
  16431. pt1 = points[ c[1] ],
  16432. pt2 = points[ c[2] ],
  16433. pt3 = points[ c[3] ];
  16434. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  16435. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  16436. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  16437. return v;
  16438. }
  16439. );
  16440. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  16441. // var v = new THREE.Vector3();
  16442. // var c = [];
  16443. // var points = this.points, point, intPoint, weight;
  16444. // point = ( points.length - 1 ) * t;
  16445. // intPoint = Math.floor( point );
  16446. // weight = point - intPoint;
  16447. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16448. // c[ 1 ] = intPoint;
  16449. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16450. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16451. // var pt0 = points[ c[0] ],
  16452. // pt1 = points[ c[1] ],
  16453. // pt2 = points[ c[2] ],
  16454. // pt3 = points[ c[3] ];
  16455. // // t = weight;
  16456. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  16457. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  16458. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  16459. // return v;
  16460. // }
  16461. /**************************************************************
  16462. * Closed Spline 3D curve
  16463. **************************************************************/
  16464. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  16465. function ( points /* array of Vector3 */) {
  16466. this.points = (points == undefined) ? [] : points;
  16467. },
  16468. function ( t ) {
  16469. var v = new THREE.Vector3();
  16470. var c = [];
  16471. var points = this.points, point, intPoint, weight;
  16472. point = ( points.length - 0 ) * t;
  16473. // This needs to be from 0-length +1
  16474. intPoint = Math.floor( point );
  16475. weight = point - intPoint;
  16476. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  16477. c[ 0 ] = ( intPoint - 1 ) % points.length;
  16478. c[ 1 ] = ( intPoint ) % points.length;
  16479. c[ 2 ] = ( intPoint + 1 ) % points.length;
  16480. c[ 3 ] = ( intPoint + 2 ) % points.length;
  16481. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16482. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16483. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  16484. return v;
  16485. }
  16486. );
  16487. /**
  16488. * @author zz85 / http://www.lab4games.net/zz85/blog
  16489. *
  16490. **/
  16491. /**************************************************************
  16492. * Curved Path - a curve path is simply a array of connected
  16493. * curves, but retains the api of a curve
  16494. **************************************************************/
  16495. THREE.CurvePath = function () {
  16496. this.curves = [];
  16497. this.bends = [];
  16498. this.autoClose = false; // Automatically closes the path
  16499. };
  16500. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16501. THREE.CurvePath.prototype.add = function ( curve ) {
  16502. this.curves.push( curve );
  16503. };
  16504. THREE.CurvePath.prototype.checkConnection = function() {
  16505. // TODO
  16506. // If the ending of curve is not connected to the starting
  16507. // or the next curve, then, this is not a real path
  16508. };
  16509. THREE.CurvePath.prototype.closePath = function() {
  16510. // TODO Test
  16511. // and verify for vector3 (needs to implement equals)
  16512. // Add a line curve if start and end of lines are not connected
  16513. var startPoint = this.curves[0].getPoint(0);
  16514. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  16515. if (!startPoint.equals(endPoint)) {
  16516. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16517. }
  16518. };
  16519. // To get accurate point with reference to
  16520. // entire path distance at time t,
  16521. // following has to be done:
  16522. // 1. Length of each sub path have to be known
  16523. // 2. Locate and identify type of curve
  16524. // 3. Get t for the curve
  16525. // 4. Return curve.getPointAt(t')
  16526. THREE.CurvePath.prototype.getPoint = function( t ) {
  16527. var d = t * this.getLength();
  16528. var curveLengths = this.getCurveLengths();
  16529. var i = 0, diff, curve;
  16530. // To think about boundaries points.
  16531. while ( i < curveLengths.length ) {
  16532. if ( curveLengths[ i ] >= d ) {
  16533. diff = curveLengths[ i ] - d;
  16534. curve = this.curves[ i ];
  16535. var u = 1 - diff / curve.getLength();
  16536. return curve.getPointAt( u );
  16537. break;
  16538. }
  16539. i ++;
  16540. }
  16541. return null;
  16542. // loop where sum != 0, sum > d , sum+1 <d
  16543. };
  16544. /*
  16545. THREE.CurvePath.prototype.getTangent = function( t ) {
  16546. };*/
  16547. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16548. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16549. // getPoint() depends on getLength
  16550. THREE.CurvePath.prototype.getLength = function() {
  16551. var lens = this.getCurveLengths();
  16552. return lens[ lens.length - 1 ];
  16553. };
  16554. // Compute lengths and cache them
  16555. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16556. THREE.CurvePath.prototype.getCurveLengths = function() {
  16557. // We use cache values if curves and cache array are same length
  16558. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16559. return this.cacheLengths;
  16560. };
  16561. // Get length of subsurve
  16562. // Push sums into cached array
  16563. var lengths = [], sums = 0;
  16564. var i, il = this.curves.length;
  16565. for ( i = 0; i < il; i ++ ) {
  16566. sums += this.curves[ i ].getLength();
  16567. lengths.push( sums );
  16568. }
  16569. this.cacheLengths = lengths;
  16570. return lengths;
  16571. };
  16572. // Returns min and max coordinates, as well as centroid
  16573. THREE.CurvePath.prototype.getBoundingBox = function () {
  16574. var points = this.getPoints();
  16575. var maxX, maxY, maxZ;
  16576. var minX, minY, minZ;
  16577. maxX = maxY = Number.NEGATIVE_INFINITY;
  16578. minX = minY = Number.POSITIVE_INFINITY;
  16579. var p, i, il, sum;
  16580. var v3 = points[0] instanceof THREE.Vector3;
  16581. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16582. for ( i = 0, il = points.length; i < il; i ++ ) {
  16583. p = points[ i ];
  16584. if ( p.x > maxX ) maxX = p.x;
  16585. else if ( p.x < minX ) minX = p.x;
  16586. if ( p.y > maxY ) maxY = p.y;
  16587. else if ( p.y < minY ) minY = p.y;
  16588. if ( v3 ) {
  16589. if ( p.z > maxZ ) maxZ = p.z;
  16590. else if ( p.z < minZ ) minZ = p.z;
  16591. }
  16592. sum.add( p );
  16593. }
  16594. var ret = {
  16595. minX: minX,
  16596. minY: minY,
  16597. maxX: maxX,
  16598. maxY: maxY,
  16599. centroid: sum.divideScalar( il )
  16600. };
  16601. if ( v3 ) {
  16602. ret.maxZ = maxZ;
  16603. ret.minZ = minZ;
  16604. }
  16605. return ret;
  16606. };
  16607. /**************************************************************
  16608. * Create Geometries Helpers
  16609. **************************************************************/
  16610. /// Generate geometry from path points (for Line or ParticleSystem objects)
  16611. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16612. var pts = this.getPoints( divisions, true );
  16613. return this.createGeometry( pts );
  16614. };
  16615. // Generate geometry from equidistance sampling along the path
  16616. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16617. var pts = this.getSpacedPoints( divisions, true );
  16618. return this.createGeometry( pts );
  16619. };
  16620. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16621. var geometry = new THREE.Geometry();
  16622. for ( var i = 0; i < points.length; i ++ ) {
  16623. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16624. }
  16625. return geometry;
  16626. };
  16627. /**************************************************************
  16628. * Bend / Wrap Helper Methods
  16629. **************************************************************/
  16630. // Wrap path / Bend modifiers?
  16631. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16632. this.bends.push( bendpath );
  16633. };
  16634. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  16635. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  16636. var i, il;
  16637. if ( !bends ) {
  16638. bends = this.bends;
  16639. }
  16640. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16641. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16642. }
  16643. return oldPts;
  16644. };
  16645. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  16646. var oldPts = this.getSpacedPoints( segments );
  16647. var i, il;
  16648. if ( !bends ) {
  16649. bends = this.bends;
  16650. }
  16651. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16652. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16653. }
  16654. return oldPts;
  16655. };
  16656. // This returns getPoints() bend/wrapped around the contour of a path.
  16657. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  16658. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  16659. var bounds = this.getBoundingBox();
  16660. var i, il, p, oldX, oldY, xNorm;
  16661. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  16662. p = oldPts[ i ];
  16663. oldX = p.x;
  16664. oldY = p.y;
  16665. xNorm = oldX / bounds.maxX;
  16666. // If using actual distance, for length > path, requires line extrusions
  16667. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  16668. xNorm = path.getUtoTmapping( xNorm, oldX );
  16669. // check for out of bounds?
  16670. var pathPt = path.getPoint( xNorm );
  16671. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  16672. p.x = pathPt.x + normal.x;
  16673. p.y = pathPt.y + normal.y;
  16674. }
  16675. return oldPts;
  16676. };
  16677. /**
  16678. * @author alteredq / http://alteredqualia.com/
  16679. */
  16680. THREE.Gyroscope = function () {
  16681. THREE.Object3D.call( this );
  16682. };
  16683. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  16684. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  16685. this.matrixAutoUpdate && this.updateMatrix();
  16686. // update matrixWorld
  16687. if ( this.matrixWorldNeedsUpdate || force ) {
  16688. if ( this.parent ) {
  16689. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  16690. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  16691. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  16692. this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
  16693. } else {
  16694. this.matrixWorld.copy( this.matrix );
  16695. }
  16696. this.matrixWorldNeedsUpdate = false;
  16697. force = true;
  16698. }
  16699. // update children
  16700. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  16701. this.children[ i ].updateMatrixWorld( force );
  16702. }
  16703. };
  16704. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  16705. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  16706. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  16707. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  16708. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  16709. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  16710. /**
  16711. * @author zz85 / http://www.lab4games.net/zz85/blog
  16712. * Creates free form 2d path using series of points, lines or curves.
  16713. *
  16714. **/
  16715. THREE.Path = function ( points ) {
  16716. THREE.CurvePath.call(this);
  16717. this.actions = [];
  16718. if ( points ) {
  16719. this.fromPoints( points );
  16720. }
  16721. };
  16722. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16723. THREE.PathActions = {
  16724. MOVE_TO: 'moveTo',
  16725. LINE_TO: 'lineTo',
  16726. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  16727. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  16728. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  16729. ARC: 'arc', // Circle
  16730. ELLIPSE: 'ellipse'
  16731. };
  16732. // TODO Clean up PATH API
  16733. // Create path using straight lines to connect all points
  16734. // - vectors: array of Vector2
  16735. THREE.Path.prototype.fromPoints = function ( vectors ) {
  16736. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  16737. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  16738. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  16739. };
  16740. };
  16741. // startPath() endPath()?
  16742. THREE.Path.prototype.moveTo = function ( x, y ) {
  16743. var args = Array.prototype.slice.call( arguments );
  16744. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  16745. };
  16746. THREE.Path.prototype.lineTo = function ( x, y ) {
  16747. var args = Array.prototype.slice.call( arguments );
  16748. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16749. var x0 = lastargs[ lastargs.length - 2 ];
  16750. var y0 = lastargs[ lastargs.length - 1 ];
  16751. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  16752. this.curves.push( curve );
  16753. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  16754. };
  16755. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  16756. var args = Array.prototype.slice.call( arguments );
  16757. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16758. var x0 = lastargs[ lastargs.length - 2 ];
  16759. var y0 = lastargs[ lastargs.length - 1 ];
  16760. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  16761. new THREE.Vector2( aCPx, aCPy ),
  16762. new THREE.Vector2( aX, aY ) );
  16763. this.curves.push( curve );
  16764. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  16765. };
  16766. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  16767. aCP2x, aCP2y,
  16768. aX, aY ) {
  16769. var args = Array.prototype.slice.call( arguments );
  16770. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16771. var x0 = lastargs[ lastargs.length - 2 ];
  16772. var y0 = lastargs[ lastargs.length - 1 ];
  16773. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  16774. new THREE.Vector2( aCP1x, aCP1y ),
  16775. new THREE.Vector2( aCP2x, aCP2y ),
  16776. new THREE.Vector2( aX, aY ) );
  16777. this.curves.push( curve );
  16778. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  16779. };
  16780. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  16781. var args = Array.prototype.slice.call( arguments );
  16782. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16783. var x0 = lastargs[ lastargs.length - 2 ];
  16784. var y0 = lastargs[ lastargs.length - 1 ];
  16785. //---
  16786. var npts = [ new THREE.Vector2( x0, y0 ) ];
  16787. Array.prototype.push.apply( npts, pts );
  16788. var curve = new THREE.SplineCurve( npts );
  16789. this.curves.push( curve );
  16790. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  16791. };
  16792. // FUTURE: Change the API or follow canvas API?
  16793. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  16794. aStartAngle, aEndAngle, aClockwise ) {
  16795. var lastargs = this.actions[ this.actions.length - 1].args;
  16796. var x0 = lastargs[ lastargs.length - 2 ];
  16797. var y0 = lastargs[ lastargs.length - 1 ];
  16798. this.absarc(aX + x0, aY + y0, aRadius,
  16799. aStartAngle, aEndAngle, aClockwise );
  16800. };
  16801. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  16802. aStartAngle, aEndAngle, aClockwise ) {
  16803. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  16804. };
  16805. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  16806. aStartAngle, aEndAngle, aClockwise ) {
  16807. var lastargs = this.actions[ this.actions.length - 1].args;
  16808. var x0 = lastargs[ lastargs.length - 2 ];
  16809. var y0 = lastargs[ lastargs.length - 1 ];
  16810. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  16811. aStartAngle, aEndAngle, aClockwise );
  16812. };
  16813. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  16814. aStartAngle, aEndAngle, aClockwise ) {
  16815. var args = Array.prototype.slice.call( arguments );
  16816. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  16817. aStartAngle, aEndAngle, aClockwise );
  16818. this.curves.push( curve );
  16819. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  16820. args.push(lastPoint.x);
  16821. args.push(lastPoint.y);
  16822. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  16823. };
  16824. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  16825. if ( ! divisions ) divisions = 40;
  16826. var points = [];
  16827. for ( var i = 0; i < divisions; i ++ ) {
  16828. points.push( this.getPoint( i / divisions ) );
  16829. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  16830. }
  16831. // if ( closedPath ) {
  16832. //
  16833. // points.push( points[ 0 ] );
  16834. //
  16835. // }
  16836. return points;
  16837. };
  16838. /* Return an array of vectors based on contour of the path */
  16839. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  16840. if (this.useSpacedPoints) {
  16841. console.log('tata');
  16842. return this.getSpacedPoints( divisions, closedPath );
  16843. }
  16844. divisions = divisions || 12;
  16845. var points = [];
  16846. var i, il, item, action, args;
  16847. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  16848. laste, j,
  16849. t, tx, ty;
  16850. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16851. item = this.actions[ i ];
  16852. action = item.action;
  16853. args = item.args;
  16854. switch( action ) {
  16855. case THREE.PathActions.MOVE_TO:
  16856. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16857. break;
  16858. case THREE.PathActions.LINE_TO:
  16859. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16860. break;
  16861. case THREE.PathActions.QUADRATIC_CURVE_TO:
  16862. cpx = args[ 2 ];
  16863. cpy = args[ 3 ];
  16864. cpx1 = args[ 0 ];
  16865. cpy1 = args[ 1 ];
  16866. if ( points.length > 0 ) {
  16867. laste = points[ points.length - 1 ];
  16868. cpx0 = laste.x;
  16869. cpy0 = laste.y;
  16870. } else {
  16871. laste = this.actions[ i - 1 ].args;
  16872. cpx0 = laste[ laste.length - 2 ];
  16873. cpy0 = laste[ laste.length - 1 ];
  16874. }
  16875. for ( j = 1; j <= divisions; j ++ ) {
  16876. t = j / divisions;
  16877. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16878. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16879. points.push( new THREE.Vector2( tx, ty ) );
  16880. }
  16881. break;
  16882. case THREE.PathActions.BEZIER_CURVE_TO:
  16883. cpx = args[ 4 ];
  16884. cpy = args[ 5 ];
  16885. cpx1 = args[ 0 ];
  16886. cpy1 = args[ 1 ];
  16887. cpx2 = args[ 2 ];
  16888. cpy2 = args[ 3 ];
  16889. if ( points.length > 0 ) {
  16890. laste = points[ points.length - 1 ];
  16891. cpx0 = laste.x;
  16892. cpy0 = laste.y;
  16893. } else {
  16894. laste = this.actions[ i - 1 ].args;
  16895. cpx0 = laste[ laste.length - 2 ];
  16896. cpy0 = laste[ laste.length - 1 ];
  16897. }
  16898. for ( j = 1; j <= divisions; j ++ ) {
  16899. t = j / divisions;
  16900. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16901. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16902. points.push( new THREE.Vector2( tx, ty ) );
  16903. }
  16904. break;
  16905. case THREE.PathActions.CSPLINE_THRU:
  16906. laste = this.actions[ i - 1 ].args;
  16907. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  16908. var spts = [ last ];
  16909. var n = divisions * args[ 0 ].length;
  16910. spts = spts.concat( args[ 0 ] );
  16911. var spline = new THREE.SplineCurve( spts );
  16912. for ( j = 1; j <= n; j ++ ) {
  16913. points.push( spline.getPointAt( j / n ) ) ;
  16914. }
  16915. break;
  16916. case THREE.PathActions.ARC:
  16917. var aX = args[ 0 ], aY = args[ 1 ],
  16918. aRadius = args[ 2 ],
  16919. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  16920. aClockwise = !!args[ 5 ];
  16921. var deltaAngle = aEndAngle - aStartAngle;
  16922. var angle;
  16923. var tdivisions = divisions * 2;
  16924. for ( j = 1; j <= tdivisions; j ++ ) {
  16925. t = j / tdivisions;
  16926. if ( ! aClockwise ) {
  16927. t = 1 - t;
  16928. }
  16929. angle = aStartAngle + t * deltaAngle;
  16930. tx = aX + aRadius * Math.cos( angle );
  16931. ty = aY + aRadius * Math.sin( angle );
  16932. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16933. points.push( new THREE.Vector2( tx, ty ) );
  16934. }
  16935. //console.log(points);
  16936. break;
  16937. case THREE.PathActions.ELLIPSE:
  16938. var aX = args[ 0 ], aY = args[ 1 ],
  16939. xRadius = args[ 2 ],
  16940. yRadius = args[ 3 ],
  16941. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  16942. aClockwise = !!args[ 6 ];
  16943. var deltaAngle = aEndAngle - aStartAngle;
  16944. var angle;
  16945. var tdivisions = divisions * 2;
  16946. for ( j = 1; j <= tdivisions; j ++ ) {
  16947. t = j / tdivisions;
  16948. if ( ! aClockwise ) {
  16949. t = 1 - t;
  16950. }
  16951. angle = aStartAngle + t * deltaAngle;
  16952. tx = aX + xRadius * Math.cos( angle );
  16953. ty = aY + yRadius * Math.sin( angle );
  16954. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16955. points.push( new THREE.Vector2( tx, ty ) );
  16956. }
  16957. //console.log(points);
  16958. break;
  16959. } // end switch
  16960. }
  16961. // Normalize to remove the closing point by default.
  16962. var lastPoint = points[ points.length - 1];
  16963. var EPSILON = 0.0000000001;
  16964. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  16965. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  16966. points.splice( points.length - 1, 1);
  16967. if ( closedPath ) {
  16968. points.push( points[ 0 ] );
  16969. }
  16970. return points;
  16971. };
  16972. // Breaks path into shapes
  16973. THREE.Path.prototype.toShapes = function() {
  16974. var i, il, item, action, args;
  16975. var subPaths = [], lastPath = new THREE.Path();
  16976. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16977. item = this.actions[ i ];
  16978. args = item.args;
  16979. action = item.action;
  16980. if ( action == THREE.PathActions.MOVE_TO ) {
  16981. if ( lastPath.actions.length != 0 ) {
  16982. subPaths.push( lastPath );
  16983. lastPath = new THREE.Path();
  16984. }
  16985. }
  16986. lastPath[ action ].apply( lastPath, args );
  16987. }
  16988. if ( lastPath.actions.length != 0 ) {
  16989. subPaths.push( lastPath );
  16990. }
  16991. // console.log(subPaths);
  16992. if ( subPaths.length == 0 ) return [];
  16993. var tmpPath, tmpShape, shapes = [];
  16994. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  16995. // console.log("Holes first", holesFirst);
  16996. if ( subPaths.length == 1) {
  16997. tmpPath = subPaths[0];
  16998. tmpShape = new THREE.Shape();
  16999. tmpShape.actions = tmpPath.actions;
  17000. tmpShape.curves = tmpPath.curves;
  17001. shapes.push( tmpShape );
  17002. return shapes;
  17003. };
  17004. if ( holesFirst ) {
  17005. tmpShape = new THREE.Shape();
  17006. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17007. tmpPath = subPaths[ i ];
  17008. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17009. tmpShape.actions = tmpPath.actions;
  17010. tmpShape.curves = tmpPath.curves;
  17011. shapes.push( tmpShape );
  17012. tmpShape = new THREE.Shape();
  17013. //console.log('cw', i);
  17014. } else {
  17015. tmpShape.holes.push( tmpPath );
  17016. //console.log('ccw', i);
  17017. }
  17018. }
  17019. } else {
  17020. // Shapes first
  17021. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17022. tmpPath = subPaths[ i ];
  17023. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17024. if ( tmpShape ) shapes.push( tmpShape );
  17025. tmpShape = new THREE.Shape();
  17026. tmpShape.actions = tmpPath.actions;
  17027. tmpShape.curves = tmpPath.curves;
  17028. } else {
  17029. tmpShape.holes.push( tmpPath );
  17030. }
  17031. }
  17032. shapes.push( tmpShape );
  17033. }
  17034. //console.log("shape", shapes);
  17035. return shapes;
  17036. };
  17037. /**
  17038. * @author zz85 / http://www.lab4games.net/zz85/blog
  17039. * Defines a 2d shape plane using paths.
  17040. **/
  17041. // STEP 1 Create a path.
  17042. // STEP 2 Turn path into shape.
  17043. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17044. // STEP 3a - Extract points from each shape, turn to vertices
  17045. // STEP 3b - Triangulate each shape, add faces.
  17046. THREE.Shape = function ( ) {
  17047. THREE.Path.apply( this, arguments );
  17048. this.holes = [];
  17049. };
  17050. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17051. // Convenience method to return ExtrudeGeometry
  17052. THREE.Shape.prototype.extrude = function ( options ) {
  17053. var extruded = new THREE.ExtrudeGeometry( this, options );
  17054. return extruded;
  17055. };
  17056. // Convenience method to return ShapeGeometry
  17057. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17058. var geometry = new THREE.ShapeGeometry( this, options );
  17059. return geometry;
  17060. };
  17061. // Get points of holes
  17062. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17063. var i, il = this.holes.length, holesPts = [];
  17064. for ( i = 0; i < il; i ++ ) {
  17065. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17066. }
  17067. return holesPts;
  17068. };
  17069. // Get points of holes (spaced by regular distance)
  17070. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17071. var i, il = this.holes.length, holesPts = [];
  17072. for ( i = 0; i < il; i ++ ) {
  17073. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17074. }
  17075. return holesPts;
  17076. };
  17077. // Get points of shape and holes (keypoints based on segments parameter)
  17078. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17079. return {
  17080. shape: this.getTransformedPoints( divisions ),
  17081. holes: this.getPointsHoles( divisions )
  17082. };
  17083. };
  17084. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17085. if (this.useSpacedPoints) {
  17086. return this.extractAllSpacedPoints(divisions);
  17087. }
  17088. return this.extractAllPoints(divisions);
  17089. };
  17090. //
  17091. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17092. //
  17093. // return {
  17094. //
  17095. // shape: this.transform( bend, divisions ),
  17096. // holes: this.getPointsHoles( divisions, bend )
  17097. //
  17098. // };
  17099. //
  17100. // };
  17101. // Get points of shape and holes (spaced by regular distance)
  17102. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17103. return {
  17104. shape: this.getTransformedSpacedPoints( divisions ),
  17105. holes: this.getSpacedPointsHoles( divisions )
  17106. };
  17107. };
  17108. /**************************************************************
  17109. * Utils
  17110. **************************************************************/
  17111. THREE.Shape.Utils = {
  17112. /*
  17113. contour - array of vector2 for contour
  17114. holes - array of array of vector2
  17115. */
  17116. removeHoles: function ( contour, holes ) {
  17117. var shape = contour.concat(); // work on this shape
  17118. var allpoints = shape.concat();
  17119. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  17120. var prevShapeVert, nextShapeVert,
  17121. prevHoleVert, nextHoleVert,
  17122. holeIndex, shapeIndex,
  17123. shapeId, shapeGroup,
  17124. h, h2,
  17125. hole, shortest, d,
  17126. p, pts1, pts2,
  17127. tmpShape1, tmpShape2,
  17128. tmpHole1, tmpHole2,
  17129. verts = [];
  17130. for ( h = 0; h < holes.length; h ++ ) {
  17131. hole = holes[ h ];
  17132. /*
  17133. shapeholes[ h ].concat(); // preserves original
  17134. holes.push( hole );
  17135. */
  17136. Array.prototype.push.apply( allpoints, hole );
  17137. shortest = Number.POSITIVE_INFINITY;
  17138. // Find the shortest pair of pts between shape and hole
  17139. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  17140. // Using distanceToSquared() intead of distanceTo() should speed a little
  17141. // since running square roots operations are reduced.
  17142. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  17143. pts1 = hole[ h2 ];
  17144. var dist = [];
  17145. for ( p = 0; p < shape.length; p++ ) {
  17146. pts2 = shape[ p ];
  17147. d = pts1.distanceToSquared( pts2 );
  17148. dist.push( d );
  17149. if ( d < shortest ) {
  17150. shortest = d;
  17151. holeIndex = h2;
  17152. shapeIndex = p;
  17153. }
  17154. }
  17155. }
  17156. //console.log("shortest", shortest, dist);
  17157. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17158. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17159. var areaapts = [
  17160. hole[ holeIndex ],
  17161. shape[ shapeIndex ],
  17162. shape[ prevShapeVert ]
  17163. ];
  17164. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  17165. var areabpts = [
  17166. hole[ holeIndex ],
  17167. hole[ prevHoleVert ],
  17168. shape[ shapeIndex ]
  17169. ];
  17170. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  17171. var shapeOffset = 1;
  17172. var holeOffset = -1;
  17173. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  17174. shapeIndex += shapeOffset;
  17175. holeIndex += holeOffset;
  17176. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17177. shapeIndex %= shape.length;
  17178. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17179. holeIndex %= hole.length;
  17180. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17181. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17182. areaapts = [
  17183. hole[ holeIndex ],
  17184. shape[ shapeIndex ],
  17185. shape[ prevShapeVert ]
  17186. ];
  17187. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  17188. areabpts = [
  17189. hole[ holeIndex ],
  17190. hole[ prevHoleVert ],
  17191. shape[ shapeIndex ]
  17192. ];
  17193. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  17194. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  17195. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  17196. // In case areas are not correct.
  17197. //console.log("USE THIS");
  17198. shapeIndex = oldShapeIndex;
  17199. holeIndex = oldHoleIndex ;
  17200. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17201. shapeIndex %= shape.length;
  17202. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17203. holeIndex %= hole.length;
  17204. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17205. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17206. } else {
  17207. //console.log("USE THAT ")
  17208. }
  17209. tmpShape1 = shape.slice( 0, shapeIndex );
  17210. tmpShape2 = shape.slice( shapeIndex );
  17211. tmpHole1 = hole.slice( holeIndex );
  17212. tmpHole2 = hole.slice( 0, holeIndex );
  17213. // Should check orders here again?
  17214. var trianglea = [
  17215. hole[ holeIndex ],
  17216. shape[ shapeIndex ],
  17217. shape[ prevShapeVert ]
  17218. ];
  17219. var triangleb = [
  17220. hole[ holeIndex ] ,
  17221. hole[ prevHoleVert ],
  17222. shape[ shapeIndex ]
  17223. ];
  17224. verts.push( trianglea );
  17225. verts.push( triangleb );
  17226. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17227. }
  17228. return {
  17229. shape:shape, /* shape with no holes */
  17230. isolatedPts: verts, /* isolated faces */
  17231. allpoints: allpoints
  17232. }
  17233. },
  17234. triangulateShape: function ( contour, holes ) {
  17235. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  17236. var shape = shapeWithoutHoles.shape,
  17237. allpoints = shapeWithoutHoles.allpoints,
  17238. isolatedPts = shapeWithoutHoles.isolatedPts;
  17239. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  17240. // 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.
  17241. //console.log( "triangles",triangles, triangles.length );
  17242. //console.log( "allpoints",allpoints, allpoints.length );
  17243. var i, il, f, face,
  17244. key, index,
  17245. allPointsMap = {},
  17246. isolatedPointsMap = {};
  17247. // prepare all points map
  17248. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17249. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17250. if ( allPointsMap[ key ] !== undefined ) {
  17251. console.log( "Duplicate point", key );
  17252. }
  17253. allPointsMap[ key ] = i;
  17254. }
  17255. // check all face vertices against all points map
  17256. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17257. face = triangles[ i ];
  17258. for ( f = 0; f < 3; f ++ ) {
  17259. key = face[ f ].x + ":" + face[ f ].y;
  17260. index = allPointsMap[ key ];
  17261. if ( index !== undefined ) {
  17262. face[ f ] = index;
  17263. }
  17264. }
  17265. }
  17266. // check isolated points vertices against all points map
  17267. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  17268. face = isolatedPts[ i ];
  17269. for ( f = 0; f < 3; f ++ ) {
  17270. key = face[ f ].x + ":" + face[ f ].y;
  17271. index = allPointsMap[ key ];
  17272. if ( index !== undefined ) {
  17273. face[ f ] = index;
  17274. }
  17275. }
  17276. }
  17277. return triangles.concat( isolatedPts );
  17278. }, // end triangulate shapes
  17279. /*
  17280. triangulate2 : function( pts, holes ) {
  17281. // For use with Poly2Tri.js
  17282. var allpts = pts.concat();
  17283. var shape = [];
  17284. for (var p in pts) {
  17285. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  17286. }
  17287. var swctx = new js.poly2tri.SweepContext(shape);
  17288. for (var h in holes) {
  17289. var aHole = holes[h];
  17290. var newHole = []
  17291. for (i in aHole) {
  17292. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  17293. allpts.push(aHole[i]);
  17294. }
  17295. swctx.AddHole(newHole);
  17296. }
  17297. var find;
  17298. var findIndexForPt = function (pt) {
  17299. find = new THREE.Vector2(pt.x, pt.y);
  17300. var p;
  17301. for (p=0, pl = allpts.length; p<pl; p++) {
  17302. if (allpts[p].equals(find)) return p;
  17303. }
  17304. return -1;
  17305. };
  17306. // triangulate
  17307. js.poly2tri.sweep.Triangulate(swctx);
  17308. var triangles = swctx.GetTriangles();
  17309. var tr ;
  17310. var facesPts = [];
  17311. for (var t in triangles) {
  17312. tr = triangles[t];
  17313. facesPts.push([
  17314. findIndexForPt(tr.GetPoint(0)),
  17315. findIndexForPt(tr.GetPoint(1)),
  17316. findIndexForPt(tr.GetPoint(2))
  17317. ]);
  17318. }
  17319. // console.log(facesPts);
  17320. // console.log("triangles", triangles.length, triangles);
  17321. // Returns array of faces with 3 element each
  17322. return facesPts;
  17323. },
  17324. */
  17325. isClockWise: function ( pts ) {
  17326. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17327. },
  17328. // Bezier Curves formulas obtained from
  17329. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17330. // Quad Bezier Functions
  17331. b2p0: function ( t, p ) {
  17332. var k = 1 - t;
  17333. return k * k * p;
  17334. },
  17335. b2p1: function ( t, p ) {
  17336. return 2 * ( 1 - t ) * t * p;
  17337. },
  17338. b2p2: function ( t, p ) {
  17339. return t * t * p;
  17340. },
  17341. b2: function ( t, p0, p1, p2 ) {
  17342. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17343. },
  17344. // Cubic Bezier Functions
  17345. b3p0: function ( t, p ) {
  17346. var k = 1 - t;
  17347. return k * k * k * p;
  17348. },
  17349. b3p1: function ( t, p ) {
  17350. var k = 1 - t;
  17351. return 3 * k * k * t * p;
  17352. },
  17353. b3p2: function ( t, p ) {
  17354. var k = 1 - t;
  17355. return 3 * k * t * t * p;
  17356. },
  17357. b3p3: function ( t, p ) {
  17358. return t * t * t * p;
  17359. },
  17360. b3: function ( t, p0, p1, p2, p3 ) {
  17361. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17362. }
  17363. };
  17364. /**
  17365. * @author mikael emtinger / http://gomo.se/
  17366. */
  17367. THREE.AnimationHandler = (function() {
  17368. var playing = [];
  17369. var library = {};
  17370. var that = {};
  17371. //--- update ---
  17372. that.update = function( deltaTimeMS ) {
  17373. for( var i = 0; i < playing.length; i ++ )
  17374. playing[ i ].update( deltaTimeMS );
  17375. };
  17376. //--- add ---
  17377. that.addToUpdate = function( animation ) {
  17378. if ( playing.indexOf( animation ) === -1 )
  17379. playing.push( animation );
  17380. };
  17381. //--- remove ---
  17382. that.removeFromUpdate = function( animation ) {
  17383. var index = playing.indexOf( animation );
  17384. if( index !== -1 )
  17385. playing.splice( index, 1 );
  17386. };
  17387. //--- add ---
  17388. that.add = function( data ) {
  17389. if ( library[ data.name ] !== undefined )
  17390. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  17391. library[ data.name ] = data;
  17392. initData( data );
  17393. };
  17394. //--- get ---
  17395. that.get = function( name ) {
  17396. if ( typeof name === "string" ) {
  17397. if ( library[ name ] ) {
  17398. return library[ name ];
  17399. } else {
  17400. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  17401. return null;
  17402. }
  17403. } else {
  17404. // todo: add simple tween library
  17405. }
  17406. };
  17407. //--- parse ---
  17408. that.parse = function( root ) {
  17409. // setup hierarchy
  17410. var hierarchy = [];
  17411. if ( root instanceof THREE.SkinnedMesh ) {
  17412. for( var b = 0; b < root.bones.length; b++ ) {
  17413. hierarchy.push( root.bones[ b ] );
  17414. }
  17415. } else {
  17416. parseRecurseHierarchy( root, hierarchy );
  17417. }
  17418. return hierarchy;
  17419. };
  17420. var parseRecurseHierarchy = function( root, hierarchy ) {
  17421. hierarchy.push( root );
  17422. for( var c = 0; c < root.children.length; c++ )
  17423. parseRecurseHierarchy( root.children[ c ], hierarchy );
  17424. }
  17425. //--- init data ---
  17426. var initData = function( data ) {
  17427. if( data.initialized === true )
  17428. return;
  17429. // loop through all keys
  17430. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  17431. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17432. // remove minus times
  17433. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  17434. data.hierarchy[ h ].keys[ k ].time = 0;
  17435. // create quaternions
  17436. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  17437. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  17438. var quat = data.hierarchy[ h ].keys[ k ].rot;
  17439. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  17440. }
  17441. }
  17442. // prepare morph target keys
  17443. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  17444. // get all used
  17445. var usedMorphTargets = {};
  17446. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17447. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17448. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  17449. usedMorphTargets[ morphTargetName ] = -1;
  17450. }
  17451. }
  17452. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  17453. // set all used on all frames
  17454. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17455. var influences = {};
  17456. for ( var morphTargetName in usedMorphTargets ) {
  17457. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17458. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  17459. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  17460. break;
  17461. }
  17462. }
  17463. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  17464. influences[ morphTargetName ] = 0;
  17465. }
  17466. }
  17467. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  17468. }
  17469. }
  17470. // remove all keys that are on the same time
  17471. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17472. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  17473. data.hierarchy[ h ].keys.splice( k, 1 );
  17474. k --;
  17475. }
  17476. }
  17477. // set index
  17478. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17479. data.hierarchy[ h ].keys[ k ].index = k;
  17480. }
  17481. }
  17482. // JIT
  17483. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  17484. data.JIT = {};
  17485. data.JIT.hierarchy = [];
  17486. for( var h = 0; h < data.hierarchy.length; h ++ )
  17487. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  17488. // done
  17489. data.initialized = true;
  17490. };
  17491. // interpolation types
  17492. that.LINEAR = 0;
  17493. that.CATMULLROM = 1;
  17494. that.CATMULLROM_FORWARD = 2;
  17495. return that;
  17496. }());
  17497. /**
  17498. * @author mikael emtinger / http://gomo.se/
  17499. * @author mrdoob / http://mrdoob.com/
  17500. * @author alteredq / http://alteredqualia.com/
  17501. */
  17502. THREE.Animation = function ( root, name, interpolationType ) {
  17503. this.root = root;
  17504. this.data = THREE.AnimationHandler.get( name );
  17505. this.hierarchy = THREE.AnimationHandler.parse( root );
  17506. this.currentTime = 0;
  17507. this.timeScale = 1;
  17508. this.isPlaying = false;
  17509. this.isPaused = true;
  17510. this.loop = true;
  17511. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  17512. this.points = [];
  17513. this.target = new THREE.Vector3();
  17514. };
  17515. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  17516. if ( this.isPlaying === false ) {
  17517. this.isPlaying = true;
  17518. this.loop = loop !== undefined ? loop : true;
  17519. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17520. // reset key cache
  17521. var h, hl = this.hierarchy.length,
  17522. object;
  17523. for ( h = 0; h < hl; h ++ ) {
  17524. object = this.hierarchy[ h ];
  17525. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17526. object.useQuaternion = true;
  17527. }
  17528. object.matrixAutoUpdate = true;
  17529. if ( object.animationCache === undefined ) {
  17530. object.animationCache = {};
  17531. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  17532. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  17533. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17534. }
  17535. var prevKey = object.animationCache.prevKey;
  17536. var nextKey = object.animationCache.nextKey;
  17537. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  17538. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  17539. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  17540. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  17541. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  17542. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  17543. }
  17544. this.update( 0 );
  17545. }
  17546. this.isPaused = false;
  17547. THREE.AnimationHandler.addToUpdate( this );
  17548. };
  17549. THREE.Animation.prototype.pause = function() {
  17550. if ( this.isPaused === true ) {
  17551. THREE.AnimationHandler.addToUpdate( this );
  17552. } else {
  17553. THREE.AnimationHandler.removeFromUpdate( this );
  17554. }
  17555. this.isPaused = !this.isPaused;
  17556. };
  17557. THREE.Animation.prototype.stop = function() {
  17558. this.isPlaying = false;
  17559. this.isPaused = false;
  17560. THREE.AnimationHandler.removeFromUpdate( this );
  17561. };
  17562. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  17563. // early out
  17564. if ( this.isPlaying === false ) return;
  17565. // vars
  17566. var types = [ "pos", "rot", "scl" ];
  17567. var type;
  17568. var scale;
  17569. var vector;
  17570. var prevXYZ, nextXYZ;
  17571. var prevKey, nextKey;
  17572. var object;
  17573. var animationCache;
  17574. var frame;
  17575. var JIThierarchy = this.data.JIT.hierarchy;
  17576. var currentTime, unloopedCurrentTime;
  17577. var currentPoint, forwardPoint, angle;
  17578. this.currentTime += deltaTimeMS * this.timeScale;
  17579. unloopedCurrentTime = this.currentTime;
  17580. currentTime = this.currentTime = this.currentTime % this.data.length;
  17581. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17582. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17583. object = this.hierarchy[ h ];
  17584. animationCache = object.animationCache;
  17585. // loop through pos/rot/scl
  17586. for ( var t = 0; t < 3; t ++ ) {
  17587. // get keys
  17588. type = types[ t ];
  17589. prevKey = animationCache.prevKey[ type ];
  17590. nextKey = animationCache.nextKey[ type ];
  17591. // switch keys?
  17592. if ( nextKey.time <= unloopedCurrentTime ) {
  17593. // did we loop?
  17594. if ( currentTime < unloopedCurrentTime ) {
  17595. if ( this.loop ) {
  17596. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  17597. nextKey = this.getNextKeyWith( type, h, 1 );
  17598. while( nextKey.time < currentTime ) {
  17599. prevKey = nextKey;
  17600. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17601. }
  17602. } else {
  17603. this.stop();
  17604. return;
  17605. }
  17606. } else {
  17607. do {
  17608. prevKey = nextKey;
  17609. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17610. } while( nextKey.time < currentTime )
  17611. }
  17612. animationCache.prevKey[ type ] = prevKey;
  17613. animationCache.nextKey[ type ] = nextKey;
  17614. }
  17615. object.matrixAutoUpdate = true;
  17616. object.matrixWorldNeedsUpdate = true;
  17617. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  17618. prevXYZ = prevKey[ type ];
  17619. nextXYZ = nextKey[ type ];
  17620. // check scale error
  17621. if ( scale < 0 || scale > 1 ) {
  17622. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  17623. scale = scale < 0 ? 0 : 1;
  17624. }
  17625. // interpolate
  17626. if ( type === "pos" ) {
  17627. vector = object.position;
  17628. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  17629. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17630. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17631. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17632. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17633. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17634. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  17635. this.points[ 1 ] = prevXYZ;
  17636. this.points[ 2 ] = nextXYZ;
  17637. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  17638. scale = scale * 0.33 + 0.33;
  17639. currentPoint = this.interpolateCatmullRom( this.points, scale );
  17640. vector.x = currentPoint[ 0 ];
  17641. vector.y = currentPoint[ 1 ];
  17642. vector.z = currentPoint[ 2 ];
  17643. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17644. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  17645. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  17646. this.target.sub( vector );
  17647. this.target.y = 0;
  17648. this.target.normalize();
  17649. angle = Math.atan2( this.target.x, this.target.z );
  17650. object.rotation.set( 0, angle, 0 );
  17651. }
  17652. }
  17653. } else if ( type === "rot" ) {
  17654. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  17655. } else if ( type === "scl" ) {
  17656. vector = object.scale;
  17657. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17658. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17659. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17660. }
  17661. }
  17662. }
  17663. };
  17664. // Catmull-Rom spline
  17665. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  17666. var c = [], v3 = [],
  17667. point, intPoint, weight, w2, w3,
  17668. pa, pb, pc, pd;
  17669. point = ( points.length - 1 ) * scale;
  17670. intPoint = Math.floor( point );
  17671. weight = point - intPoint;
  17672. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  17673. c[ 1 ] = intPoint;
  17674. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  17675. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  17676. pa = points[ c[ 0 ] ];
  17677. pb = points[ c[ 1 ] ];
  17678. pc = points[ c[ 2 ] ];
  17679. pd = points[ c[ 3 ] ];
  17680. w2 = weight * weight;
  17681. w3 = weight * w2;
  17682. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  17683. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  17684. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  17685. return v3;
  17686. };
  17687. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  17688. var v0 = ( p2 - p0 ) * 0.5,
  17689. v1 = ( p3 - p1 ) * 0.5;
  17690. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17691. };
  17692. // Get next key with
  17693. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  17694. var keys = this.data.hierarchy[ h ].keys;
  17695. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17696. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17697. key = key < keys.length - 1 ? key : keys.length - 1;
  17698. } else {
  17699. key = key % keys.length;
  17700. }
  17701. for ( ; key < keys.length; key++ ) {
  17702. if ( keys[ key ][ type ] !== undefined ) {
  17703. return keys[ key ];
  17704. }
  17705. }
  17706. return this.data.hierarchy[ h ].keys[ 0 ];
  17707. };
  17708. // Get previous key with
  17709. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  17710. var keys = this.data.hierarchy[ h ].keys;
  17711. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17712. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17713. key = key > 0 ? key : 0;
  17714. } else {
  17715. key = key >= 0 ? key : key + keys.length;
  17716. }
  17717. for ( ; key >= 0; key -- ) {
  17718. if ( keys[ key ][ type ] !== undefined ) {
  17719. return keys[ key ];
  17720. }
  17721. }
  17722. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  17723. };
  17724. /**
  17725. * @author mikael emtinger / http://gomo.se/
  17726. * @author mrdoob / http://mrdoob.com/
  17727. * @author alteredq / http://alteredqualia.com/
  17728. * @author khang duong
  17729. * @author erik kitson
  17730. */
  17731. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  17732. this.root = root;
  17733. this.data = THREE.AnimationHandler.get( data );
  17734. this.hierarchy = THREE.AnimationHandler.parse( root );
  17735. this.currentTime = 0;
  17736. this.timeScale = 0.001;
  17737. this.isPlaying = false;
  17738. this.isPaused = true;
  17739. this.loop = true;
  17740. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  17741. // initialize to first keyframes
  17742. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17743. var keys = this.data.hierarchy[h].keys,
  17744. sids = this.data.hierarchy[h].sids,
  17745. obj = this.hierarchy[h];
  17746. if ( keys.length && sids ) {
  17747. for ( var s = 0; s < sids.length; s++ ) {
  17748. var sid = sids[ s ],
  17749. next = this.getNextKeyWith( sid, h, 0 );
  17750. if ( next ) {
  17751. next.apply( sid );
  17752. }
  17753. }
  17754. obj.matrixAutoUpdate = false;
  17755. this.data.hierarchy[h].node.updateMatrix();
  17756. obj.matrixWorldNeedsUpdate = true;
  17757. }
  17758. }
  17759. };
  17760. // Play
  17761. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  17762. if( !this.isPlaying ) {
  17763. this.isPlaying = true;
  17764. this.loop = loop !== undefined ? loop : true;
  17765. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17766. this.startTimeMs = startTimeMS;
  17767. this.startTime = 10000000;
  17768. this.endTime = -this.startTime;
  17769. // reset key cache
  17770. var h, hl = this.hierarchy.length,
  17771. object,
  17772. node;
  17773. for ( h = 0; h < hl; h++ ) {
  17774. object = this.hierarchy[ h ];
  17775. node = this.data.hierarchy[ h ];
  17776. object.useQuaternion = true;
  17777. if ( node.animationCache === undefined ) {
  17778. node.animationCache = {};
  17779. node.animationCache.prevKey = null;
  17780. node.animationCache.nextKey = null;
  17781. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17782. }
  17783. var keys = this.data.hierarchy[h].keys;
  17784. if (keys.length) {
  17785. node.animationCache.prevKey = keys[ 0 ];
  17786. node.animationCache.nextKey = keys[ 1 ];
  17787. this.startTime = Math.min( keys[0].time, this.startTime );
  17788. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  17789. }
  17790. }
  17791. this.update( 0 );
  17792. }
  17793. this.isPaused = false;
  17794. THREE.AnimationHandler.addToUpdate( this );
  17795. };
  17796. // Pause
  17797. THREE.KeyFrameAnimation.prototype.pause = function() {
  17798. if( this.isPaused ) {
  17799. THREE.AnimationHandler.addToUpdate( this );
  17800. } else {
  17801. THREE.AnimationHandler.removeFromUpdate( this );
  17802. }
  17803. this.isPaused = !this.isPaused;
  17804. };
  17805. // Stop
  17806. THREE.KeyFrameAnimation.prototype.stop = function() {
  17807. this.isPlaying = false;
  17808. this.isPaused = false;
  17809. THREE.AnimationHandler.removeFromUpdate( this );
  17810. // reset JIT matrix and remove cache
  17811. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  17812. var obj = this.hierarchy[ h ];
  17813. var node = this.data.hierarchy[ h ];
  17814. if ( node.animationCache !== undefined ) {
  17815. var original = node.animationCache.originalMatrix;
  17816. if( obj instanceof THREE.Bone ) {
  17817. original.copy( obj.skinMatrix );
  17818. obj.skinMatrix = original;
  17819. } else {
  17820. original.copy( obj.matrix );
  17821. obj.matrix = original;
  17822. }
  17823. delete node.animationCache;
  17824. }
  17825. }
  17826. };
  17827. // Update
  17828. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  17829. // early out
  17830. if( !this.isPlaying ) return;
  17831. // vars
  17832. var prevKey, nextKey;
  17833. var object;
  17834. var node;
  17835. var frame;
  17836. var JIThierarchy = this.data.JIT.hierarchy;
  17837. var currentTime, unloopedCurrentTime;
  17838. var looped;
  17839. // update
  17840. this.currentTime += deltaTimeMS * this.timeScale;
  17841. unloopedCurrentTime = this.currentTime;
  17842. currentTime = this.currentTime = this.currentTime % this.data.length;
  17843. // if looped around, the current time should be based on the startTime
  17844. if ( currentTime < this.startTimeMs ) {
  17845. currentTime = this.currentTime = this.startTimeMs + currentTime;
  17846. }
  17847. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17848. looped = currentTime < unloopedCurrentTime;
  17849. if ( looped && !this.loop ) {
  17850. // Set the animation to the last keyframes and stop
  17851. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17852. var keys = this.data.hierarchy[h].keys,
  17853. sids = this.data.hierarchy[h].sids,
  17854. end = keys.length-1,
  17855. obj = this.hierarchy[h];
  17856. if ( keys.length ) {
  17857. for ( var s = 0; s < sids.length; s++ ) {
  17858. var sid = sids[ s ],
  17859. prev = this.getPrevKeyWith( sid, h, end );
  17860. if ( prev ) {
  17861. prev.apply( sid );
  17862. }
  17863. }
  17864. this.data.hierarchy[h].node.updateMatrix();
  17865. obj.matrixWorldNeedsUpdate = true;
  17866. }
  17867. }
  17868. this.stop();
  17869. return;
  17870. }
  17871. // check pre-infinity
  17872. if ( currentTime < this.startTime ) {
  17873. return;
  17874. }
  17875. // update
  17876. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17877. object = this.hierarchy[ h ];
  17878. node = this.data.hierarchy[ h ];
  17879. var keys = node.keys,
  17880. animationCache = node.animationCache;
  17881. // use JIT?
  17882. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  17883. if( object instanceof THREE.Bone ) {
  17884. object.skinMatrix = JIThierarchy[ h ][ frame ];
  17885. object.matrixWorldNeedsUpdate = false;
  17886. } else {
  17887. object.matrix = JIThierarchy[ h ][ frame ];
  17888. object.matrixWorldNeedsUpdate = true;
  17889. }
  17890. // use interpolation
  17891. } else if ( keys.length ) {
  17892. // make sure so original matrix and not JIT matrix is set
  17893. if ( this.JITCompile && animationCache ) {
  17894. if( object instanceof THREE.Bone ) {
  17895. object.skinMatrix = animationCache.originalMatrix;
  17896. } else {
  17897. object.matrix = animationCache.originalMatrix;
  17898. }
  17899. }
  17900. prevKey = animationCache.prevKey;
  17901. nextKey = animationCache.nextKey;
  17902. if ( prevKey && nextKey ) {
  17903. // switch keys?
  17904. if ( nextKey.time <= unloopedCurrentTime ) {
  17905. // did we loop?
  17906. if ( looped && this.loop ) {
  17907. prevKey = keys[ 0 ];
  17908. nextKey = keys[ 1 ];
  17909. while ( nextKey.time < currentTime ) {
  17910. prevKey = nextKey;
  17911. nextKey = keys[ prevKey.index + 1 ];
  17912. }
  17913. } else if ( !looped ) {
  17914. var lastIndex = keys.length - 1;
  17915. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  17916. prevKey = nextKey;
  17917. nextKey = keys[ prevKey.index + 1 ];
  17918. }
  17919. }
  17920. animationCache.prevKey = prevKey;
  17921. animationCache.nextKey = nextKey;
  17922. }
  17923. if(nextKey.time >= currentTime)
  17924. prevKey.interpolate( nextKey, currentTime );
  17925. else
  17926. prevKey.interpolate( nextKey, nextKey.time);
  17927. }
  17928. this.data.hierarchy[h].node.updateMatrix();
  17929. object.matrixWorldNeedsUpdate = true;
  17930. }
  17931. }
  17932. // update JIT?
  17933. if ( this.JITCompile ) {
  17934. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  17935. this.hierarchy[ 0 ].updateMatrixWorld( true );
  17936. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  17937. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  17938. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  17939. } else {
  17940. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  17941. }
  17942. }
  17943. }
  17944. }
  17945. };
  17946. // Get next key with
  17947. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  17948. var keys = this.data.hierarchy[ h ].keys;
  17949. key = key % keys.length;
  17950. for ( ; key < keys.length; key++ ) {
  17951. if ( keys[ key ].hasTarget( sid ) ) {
  17952. return keys[ key ];
  17953. }
  17954. }
  17955. return keys[ 0 ];
  17956. };
  17957. // Get previous key with
  17958. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  17959. var keys = this.data.hierarchy[ h ].keys;
  17960. key = key >= 0 ? key : key + keys.length;
  17961. for ( ; key >= 0; key-- ) {
  17962. if ( keys[ key ].hasTarget( sid ) ) {
  17963. return keys[ key ];
  17964. }
  17965. }
  17966. return keys[ keys.length - 1 ];
  17967. };
  17968. /**
  17969. * Camera for rendering cube maps
  17970. * - renders scene into axis-aligned cube
  17971. *
  17972. * @author alteredq / http://alteredqualia.com/
  17973. */
  17974. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  17975. THREE.Object3D.call( this );
  17976. var fov = 90, aspect = 1;
  17977. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17978. cameraPX.up.set( 0, -1, 0 );
  17979. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  17980. this.add( cameraPX );
  17981. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17982. cameraNX.up.set( 0, -1, 0 );
  17983. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  17984. this.add( cameraNX );
  17985. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17986. cameraPY.up.set( 0, 0, 1 );
  17987. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  17988. this.add( cameraPY );
  17989. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17990. cameraNY.up.set( 0, 0, -1 );
  17991. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  17992. this.add( cameraNY );
  17993. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17994. cameraPZ.up.set( 0, -1, 0 );
  17995. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  17996. this.add( cameraPZ );
  17997. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17998. cameraNZ.up.set( 0, -1, 0 );
  17999. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  18000. this.add( cameraNZ );
  18001. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  18002. this.updateCubeMap = function ( renderer, scene ) {
  18003. var renderTarget = this.renderTarget;
  18004. var generateMipmaps = renderTarget.generateMipmaps;
  18005. renderTarget.generateMipmaps = false;
  18006. renderTarget.activeCubeFace = 0;
  18007. renderer.render( scene, cameraPX, renderTarget );
  18008. renderTarget.activeCubeFace = 1;
  18009. renderer.render( scene, cameraNX, renderTarget );
  18010. renderTarget.activeCubeFace = 2;
  18011. renderer.render( scene, cameraPY, renderTarget );
  18012. renderTarget.activeCubeFace = 3;
  18013. renderer.render( scene, cameraNY, renderTarget );
  18014. renderTarget.activeCubeFace = 4;
  18015. renderer.render( scene, cameraPZ, renderTarget );
  18016. renderTarget.generateMipmaps = generateMipmaps;
  18017. renderTarget.activeCubeFace = 5;
  18018. renderer.render( scene, cameraNZ, renderTarget );
  18019. };
  18020. };
  18021. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  18022. /*
  18023. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  18024. *
  18025. * A general perpose camera, for setting FOV, Lens Focal Length,
  18026. * and switching between perspective and orthographic views easily.
  18027. * Use this only if you do not wish to manage
  18028. * both a Orthographic and Perspective Camera
  18029. *
  18030. */
  18031. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  18032. THREE.Camera.call( this );
  18033. this.fov = fov;
  18034. this.left = -width / 2;
  18035. this.right = width / 2
  18036. this.top = height / 2;
  18037. this.bottom = -height / 2;
  18038. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  18039. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  18040. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  18041. this.zoom = 1;
  18042. this.toPerspective();
  18043. var aspect = width/height;
  18044. };
  18045. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  18046. THREE.CombinedCamera.prototype.toPerspective = function () {
  18047. // Switches to the Perspective Camera
  18048. this.near = this.cameraP.near;
  18049. this.far = this.cameraP.far;
  18050. this.cameraP.fov = this.fov / this.zoom ;
  18051. this.cameraP.updateProjectionMatrix();
  18052. this.projectionMatrix = this.cameraP.projectionMatrix;
  18053. this.inPerspectiveMode = true;
  18054. this.inOrthographicMode = false;
  18055. };
  18056. THREE.CombinedCamera.prototype.toOrthographic = function () {
  18057. // Switches to the Orthographic camera estimating viewport from Perspective
  18058. var fov = this.fov;
  18059. var aspect = this.cameraP.aspect;
  18060. var near = this.cameraP.near;
  18061. var far = this.cameraP.far;
  18062. // The size that we set is the mid plane of the viewing frustum
  18063. var hyperfocus = ( near + far ) / 2;
  18064. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  18065. var planeHeight = 2 * halfHeight;
  18066. var planeWidth = planeHeight * aspect;
  18067. var halfWidth = planeWidth / 2;
  18068. halfHeight /= this.zoom;
  18069. halfWidth /= this.zoom;
  18070. this.cameraO.left = -halfWidth;
  18071. this.cameraO.right = halfWidth;
  18072. this.cameraO.top = halfHeight;
  18073. this.cameraO.bottom = -halfHeight;
  18074. // this.cameraO.left = -farHalfWidth;
  18075. // this.cameraO.right = farHalfWidth;
  18076. // this.cameraO.top = farHalfHeight;
  18077. // this.cameraO.bottom = -farHalfHeight;
  18078. // this.cameraO.left = this.left / this.zoom;
  18079. // this.cameraO.right = this.right / this.zoom;
  18080. // this.cameraO.top = this.top / this.zoom;
  18081. // this.cameraO.bottom = this.bottom / this.zoom;
  18082. this.cameraO.updateProjectionMatrix();
  18083. this.near = this.cameraO.near;
  18084. this.far = this.cameraO.far;
  18085. this.projectionMatrix = this.cameraO.projectionMatrix;
  18086. this.inPerspectiveMode = false;
  18087. this.inOrthographicMode = true;
  18088. };
  18089. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  18090. this.cameraP.aspect = width / height;
  18091. this.left = -width / 2;
  18092. this.right = width / 2
  18093. this.top = height / 2;
  18094. this.bottom = -height / 2;
  18095. };
  18096. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  18097. this.fov = fov;
  18098. if ( this.inPerspectiveMode ) {
  18099. this.toPerspective();
  18100. } else {
  18101. this.toOrthographic();
  18102. }
  18103. };
  18104. // For mantaining similar API with PerspectiveCamera
  18105. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  18106. if ( this.inPerspectiveMode ) {
  18107. this.toPerspective();
  18108. } else {
  18109. this.toPerspective();
  18110. this.toOrthographic();
  18111. }
  18112. };
  18113. /*
  18114. * Uses Focal Length (in mm) to estimate and set FOV
  18115. * 35mm (fullframe) camera is used if frame size is not specified;
  18116. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  18117. */
  18118. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  18119. if ( frameHeight === undefined ) frameHeight = 24;
  18120. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  18121. this.setFov( fov );
  18122. return fov;
  18123. };
  18124. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  18125. this.zoom = zoom;
  18126. if ( this.inPerspectiveMode ) {
  18127. this.toPerspective();
  18128. } else {
  18129. this.toOrthographic();
  18130. }
  18131. };
  18132. THREE.CombinedCamera.prototype.toFrontView = function() {
  18133. this.rotation.x = 0;
  18134. this.rotation.y = 0;
  18135. this.rotation.z = 0;
  18136. // should we be modifing the matrix instead?
  18137. this.rotationAutoUpdate = false;
  18138. };
  18139. THREE.CombinedCamera.prototype.toBackView = function() {
  18140. this.rotation.x = 0;
  18141. this.rotation.y = Math.PI;
  18142. this.rotation.z = 0;
  18143. this.rotationAutoUpdate = false;
  18144. };
  18145. THREE.CombinedCamera.prototype.toLeftView = function() {
  18146. this.rotation.x = 0;
  18147. this.rotation.y = - Math.PI / 2;
  18148. this.rotation.z = 0;
  18149. this.rotationAutoUpdate = false;
  18150. };
  18151. THREE.CombinedCamera.prototype.toRightView = 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.toTopView = function() {
  18158. this.rotation.x = - Math.PI / 2;
  18159. this.rotation.y = 0;
  18160. this.rotation.z = 0;
  18161. this.rotationAutoUpdate = false;
  18162. };
  18163. THREE.CombinedCamera.prototype.toBottomView = function() {
  18164. this.rotation.x = Math.PI / 2;
  18165. this.rotation.y = 0;
  18166. this.rotation.z = 0;
  18167. this.rotationAutoUpdate = false;
  18168. };
  18169. /**
  18170. * @author alteredq / http://alteredqualia.com/
  18171. *
  18172. * - 3d asterisk shape (for line pieces THREE.Line)
  18173. */
  18174. THREE.AsteriskGeometry = function ( innerRadius, outerRadius ) {
  18175. THREE.Geometry.call( this );
  18176. var sd = innerRadius;
  18177. var ed = outerRadius;
  18178. var sd2 = 0.707 * sd;
  18179. var ed2 = 0.707 * ed;
  18180. var rays = [ [ sd, 0, 0 ], [ ed, 0, 0 ], [ -sd, 0, 0 ], [ -ed, 0, 0 ],
  18181. [ 0, sd, 0 ], [ 0, ed, 0 ], [ 0, -sd, 0 ], [ 0, -ed, 0 ],
  18182. [ 0, 0, sd ], [ 0, 0, ed ], [ 0, 0, -sd ], [ 0, 0, -ed ],
  18183. [ sd2, sd2, 0 ], [ ed2, ed2, 0 ], [ -sd2, -sd2, 0 ], [ -ed2, -ed2, 0 ],
  18184. [ sd2, -sd2, 0 ], [ ed2, -ed2, 0 ], [ -sd2, sd2, 0 ], [ -ed2, ed2, 0 ],
  18185. [ sd2, 0, sd2 ], [ ed2, 0, ed2 ], [ -sd2, 0, -sd2 ], [ -ed2, 0, -ed2 ],
  18186. [ sd2, 0, -sd2 ], [ ed2, 0, -ed2 ], [ -sd2, 0, sd2 ], [ -ed2, 0, ed2 ],
  18187. [ 0, sd2, sd2 ], [ 0, ed2, ed2 ], [ 0, -sd2, -sd2 ], [ 0, -ed2, -ed2 ],
  18188. [ 0, sd2, -sd2 ], [ 0, ed2, -ed2 ], [ 0, -sd2, sd2 ], [ 0, -ed2, ed2 ]
  18189. ];
  18190. for ( var i = 0, il = rays.length; i < il; i ++ ) {
  18191. var x = rays[ i ][ 0 ];
  18192. var y = rays[ i ][ 1 ];
  18193. var z = rays[ i ][ 2 ];
  18194. this.vertices.push( new THREE.Vector3( x, y, z ) );
  18195. }
  18196. };
  18197. THREE.AsteriskGeometry.prototype = Object.create( THREE.Geometry.prototype );/**
  18198. * @author hughes
  18199. */
  18200. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18201. THREE.Geometry.call( this );
  18202. radius = radius || 50;
  18203. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18204. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18205. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18206. var i, uvs = [],
  18207. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18208. this.vertices.push(center);
  18209. uvs.push( centerUV );
  18210. for ( i = 0; i <= segments; i ++ ) {
  18211. var vertex = new THREE.Vector3();
  18212. vertex.x = radius * Math.cos( thetaStart + i / segments * thetaLength );
  18213. vertex.y = radius * Math.sin( thetaStart + i / segments * thetaLength );
  18214. this.vertices.push( vertex );
  18215. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  18216. }
  18217. var n = new THREE.Vector3( 0, 0, -1 );
  18218. for ( i = 1; i <= segments; i ++ ) {
  18219. var v1 = i;
  18220. var v2 = i + 1 ;
  18221. var v3 = 0;
  18222. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  18223. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  18224. }
  18225. this.computeCentroids();
  18226. this.computeFaceNormals();
  18227. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18228. };
  18229. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18230. /**
  18231. * @author mrdoob / http://mrdoob.com/
  18232. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18233. */
  18234. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18235. THREE.Geometry.call( this );
  18236. var scope = this;
  18237. this.width = width;
  18238. this.height = height;
  18239. this.depth = depth;
  18240. this.widthSegments = widthSegments || 1;
  18241. this.heightSegments = heightSegments || 1;
  18242. this.depthSegments = depthSegments || 1;
  18243. var width_half = this.width / 2;
  18244. var height_half = this.height / 2;
  18245. var depth_half = this.depth / 2;
  18246. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  18247. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  18248. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  18249. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  18250. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  18251. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  18252. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18253. var w, ix, iy,
  18254. gridX = scope.widthSegments,
  18255. gridY = scope.heightSegments,
  18256. width_half = width / 2,
  18257. height_half = height / 2,
  18258. offset = scope.vertices.length;
  18259. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18260. w = 'z';
  18261. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18262. w = 'y';
  18263. gridY = scope.depthSegments;
  18264. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18265. w = 'x';
  18266. gridX = scope.depthSegments;
  18267. }
  18268. var gridX1 = gridX + 1,
  18269. gridY1 = gridY + 1,
  18270. segment_width = width / gridX,
  18271. segment_height = height / gridY,
  18272. normal = new THREE.Vector3();
  18273. normal[ w ] = depth > 0 ? 1 : - 1;
  18274. for ( iy = 0; iy < gridY1; iy ++ ) {
  18275. for ( ix = 0; ix < gridX1; ix ++ ) {
  18276. var vector = new THREE.Vector3();
  18277. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18278. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18279. vector[ w ] = depth;
  18280. scope.vertices.push( vector );
  18281. }
  18282. }
  18283. for ( iy = 0; iy < gridY; iy++ ) {
  18284. for ( ix = 0; ix < gridX; ix++ ) {
  18285. var a = ix + gridX1 * iy;
  18286. var b = ix + gridX1 * ( iy + 1 );
  18287. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18288. var d = ( ix + 1 ) + gridX1 * iy;
  18289. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  18290. face.normal.copy( normal );
  18291. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  18292. face.materialIndex = materialIndex;
  18293. scope.faces.push( face );
  18294. scope.faceVertexUvs[ 0 ].push( [
  18295. new THREE.Vector2( ix / gridX, 1 - iy / gridY ),
  18296. new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  18297. new THREE.Vector2( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  18298. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY )
  18299. ] );
  18300. }
  18301. }
  18302. }
  18303. this.computeCentroids();
  18304. this.mergeVertices();
  18305. };
  18306. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18307. /**
  18308. * @author mrdoob / http://mrdoob.com/
  18309. */
  18310. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radiusSegments, heightSegments, openEnded ) {
  18311. THREE.Geometry.call( this );
  18312. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18313. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18314. height = height !== undefined ? height : 100;
  18315. var heightHalf = height / 2;
  18316. var segmentsX = radiusSegments || 8;
  18317. var segmentsY = heightSegments || 1;
  18318. var x, y, vertices = [], uvs = [];
  18319. for ( y = 0; y <= segmentsY; y ++ ) {
  18320. var verticesRow = [];
  18321. var uvsRow = [];
  18322. var v = y / segmentsY;
  18323. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18324. for ( x = 0; x <= segmentsX; x ++ ) {
  18325. var u = x / segmentsX;
  18326. var vertex = new THREE.Vector3();
  18327. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  18328. vertex.y = - v * height + heightHalf;
  18329. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  18330. this.vertices.push( vertex );
  18331. verticesRow.push( this.vertices.length - 1 );
  18332. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  18333. }
  18334. vertices.push( verticesRow );
  18335. uvs.push( uvsRow );
  18336. }
  18337. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18338. var na, nb;
  18339. for ( x = 0; x < segmentsX; x ++ ) {
  18340. if ( radiusTop !== 0 ) {
  18341. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18342. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18343. } else {
  18344. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18345. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18346. }
  18347. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18348. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18349. for ( y = 0; y < segmentsY; y ++ ) {
  18350. var v1 = vertices[ y ][ x ];
  18351. var v2 = vertices[ y + 1 ][ x ];
  18352. var v3 = vertices[ y + 1 ][ x + 1 ];
  18353. var v4 = vertices[ y ][ x + 1 ];
  18354. var n1 = na.clone();
  18355. var n2 = na.clone();
  18356. var n3 = nb.clone();
  18357. var n4 = nb.clone();
  18358. var uv1 = uvs[ y ][ x ].clone();
  18359. var uv2 = uvs[ y + 1 ][ x ].clone();
  18360. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18361. var uv4 = uvs[ y ][ x + 1 ].clone();
  18362. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  18363. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  18364. }
  18365. }
  18366. // top cap
  18367. if ( !openEnded && radiusTop > 0 ) {
  18368. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18369. for ( x = 0; x < segmentsX; x ++ ) {
  18370. var v1 = vertices[ 0 ][ x ];
  18371. var v2 = vertices[ 0 ][ x + 1 ];
  18372. var v3 = this.vertices.length - 1;
  18373. var n1 = new THREE.Vector3( 0, 1, 0 );
  18374. var n2 = new THREE.Vector3( 0, 1, 0 );
  18375. var n3 = new THREE.Vector3( 0, 1, 0 );
  18376. var uv1 = uvs[ 0 ][ x ].clone();
  18377. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18378. var uv3 = new THREE.Vector2( uv2.u, 0 );
  18379. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18380. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18381. }
  18382. }
  18383. // bottom cap
  18384. if ( !openEnded && radiusBottom > 0 ) {
  18385. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18386. for ( x = 0; x < segmentsX; x ++ ) {
  18387. var v1 = vertices[ y ][ x + 1 ];
  18388. var v2 = vertices[ y ][ x ];
  18389. var v3 = this.vertices.length - 1;
  18390. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18391. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18392. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18393. var uv1 = uvs[ y ][ x + 1 ].clone();
  18394. var uv2 = uvs[ y ][ x ].clone();
  18395. var uv3 = new THREE.Vector2( uv2.u, 1 );
  18396. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18397. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18398. }
  18399. }
  18400. this.computeCentroids();
  18401. this.computeFaceNormals();
  18402. }
  18403. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18404. /**
  18405. * @author zz85 / http://www.lab4games.net/zz85/blog
  18406. *
  18407. * Creates extruded geometry from a path shape.
  18408. *
  18409. * parameters = {
  18410. *
  18411. * size: <float>, // size of the text
  18412. * height: <float>, // thickness to extrude text
  18413. * curveSegments: <int>, // number of points on the curves
  18414. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18415. * amount: <int>, // Amount
  18416. *
  18417. * bevelEnabled: <bool>, // turn on bevel
  18418. * bevelThickness: <float>, // how deep into text bevel goes
  18419. * bevelSize: <float>, // how far from text outline is bevel
  18420. * bevelSegments: <int>, // number of bevel layers
  18421. *
  18422. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18423. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18424. *
  18425. * material: <int> // material index for front and back faces
  18426. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18427. * uvGenerator: <Object> // object that provides UV generator functions
  18428. *
  18429. * }
  18430. **/
  18431. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18432. if ( typeof( shapes ) === "undefined" ) {
  18433. shapes = [];
  18434. return;
  18435. }
  18436. THREE.Geometry.call( this );
  18437. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18438. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18439. this.addShapeList( shapes, options );
  18440. this.computeCentroids();
  18441. this.computeFaceNormals();
  18442. // can't really use automatic vertex normals
  18443. // as then front and back sides get smoothed too
  18444. // should do separate smoothing just for sides
  18445. //this.computeVertexNormals();
  18446. //console.log( "took", ( Date.now() - startTime ) );
  18447. };
  18448. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18449. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18450. var sl = shapes.length;
  18451. for ( var s = 0; s < sl; s ++ ) {
  18452. var shape = shapes[ s ];
  18453. this.addShape( shape, options );
  18454. }
  18455. };
  18456. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18457. var amount = options.amount !== undefined ? options.amount : 100;
  18458. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18459. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18460. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18461. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18462. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18463. var steps = options.steps !== undefined ? options.steps : 1;
  18464. var extrudePath = options.extrudePath;
  18465. var extrudePts, extrudeByPath = false;
  18466. var material = options.material;
  18467. var extrudeMaterial = options.extrudeMaterial;
  18468. // Use default WorldUVGenerator if no UV generators are specified.
  18469. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18470. var shapebb = this.shapebb;
  18471. //shapebb = shape.getBoundingBox();
  18472. var splineTube, binormal, normal, position2;
  18473. if ( extrudePath ) {
  18474. extrudePts = extrudePath.getSpacedPoints( steps );
  18475. extrudeByPath = true;
  18476. bevelEnabled = false; // bevels not supported for path extrusion
  18477. // SETUP TNB variables
  18478. // Reuse TNB from TubeGeomtry for now.
  18479. // TODO1 - have a .isClosed in spline?
  18480. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18481. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18482. binormal = new THREE.Vector3();
  18483. normal = new THREE.Vector3();
  18484. position2 = new THREE.Vector3();
  18485. }
  18486. // Safeguards if bevels are not enabled
  18487. if ( ! bevelEnabled ) {
  18488. bevelSegments = 0;
  18489. bevelThickness = 0;
  18490. bevelSize = 0;
  18491. }
  18492. // Variables initalization
  18493. var ahole, h, hl; // looping of holes
  18494. var scope = this;
  18495. var bevelPoints = [];
  18496. var shapesOffset = this.vertices.length;
  18497. var shapePoints = shape.extractPoints( curveSegments );
  18498. var vertices = shapePoints.shape;
  18499. var holes = shapePoints.holes;
  18500. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  18501. if ( reverse ) {
  18502. vertices = vertices.reverse();
  18503. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18504. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18505. ahole = holes[ h ];
  18506. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18507. holes[ h ] = ahole.reverse();
  18508. }
  18509. }
  18510. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18511. }
  18512. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18513. /* Vertices */
  18514. var contour = vertices; // vertices has all points but contour has only points of circumference
  18515. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18516. ahole = holes[ h ];
  18517. vertices = vertices.concat( ahole );
  18518. }
  18519. function scalePt2 ( pt, vec, size ) {
  18520. if ( !vec ) console.log( "die" );
  18521. return vec.clone().multiplyScalar( size ).add( pt );
  18522. }
  18523. var b, bs, t, z,
  18524. vert, vlen = vertices.length,
  18525. face, flen = faces.length,
  18526. cont, clen = contour.length;
  18527. // Find directions for point movement
  18528. var RAD_TO_DEGREES = 180 / Math.PI;
  18529. function getBevelVec( pt_i, pt_j, pt_k ) {
  18530. // Algorithm 2
  18531. return getBevelVec2( pt_i, pt_j, pt_k );
  18532. }
  18533. function getBevelVec1( pt_i, pt_j, pt_k ) {
  18534. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  18535. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  18536. if ( anglea > angleb ) {
  18537. angleb += Math.PI * 2;
  18538. }
  18539. var anglec = ( anglea + angleb ) / 2;
  18540. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  18541. var x = - Math.cos( anglec );
  18542. var y = - Math.sin( anglec );
  18543. var vec = new THREE.Vector2( x, y ); //.normalize();
  18544. return vec;
  18545. }
  18546. function getBevelVec2( pt_i, pt_j, pt_k ) {
  18547. var a = THREE.ExtrudeGeometry.__v1,
  18548. b = THREE.ExtrudeGeometry.__v2,
  18549. v_hat = THREE.ExtrudeGeometry.__v3,
  18550. w_hat = THREE.ExtrudeGeometry.__v4,
  18551. p = THREE.ExtrudeGeometry.__v5,
  18552. q = THREE.ExtrudeGeometry.__v6,
  18553. v, w,
  18554. v_dot_w_hat, q_sub_p_dot_w_hat,
  18555. s, intersection;
  18556. // good reading for line-line intersection
  18557. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  18558. // define a as vector j->i
  18559. // define b as vectot k->i
  18560. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  18561. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  18562. // get unit vectors
  18563. v = a.normalize();
  18564. w = b.normalize();
  18565. // normals from pt i
  18566. v_hat.set( -v.y, v.x );
  18567. w_hat.set( w.y, -w.x );
  18568. // pts from i
  18569. p.copy( pt_i ).add( v_hat );
  18570. q.copy( pt_i ).add( w_hat );
  18571. if ( p.equals( q ) ) {
  18572. //console.log("Warning: lines are straight");
  18573. return w_hat.clone();
  18574. }
  18575. // Points from j, k. helps prevents points cross overover most of the time
  18576. p.copy( pt_j ).add( v_hat );
  18577. q.copy( pt_k ).add( w_hat );
  18578. v_dot_w_hat = v.dot( w_hat );
  18579. q_sub_p_dot_w_hat = q.sub( p ).dot( w_hat );
  18580. // We should not reach these conditions
  18581. if ( v_dot_w_hat === 0 ) {
  18582. console.log( "Either infinite or no solutions!" );
  18583. if ( q_sub_p_dot_w_hat === 0 ) {
  18584. console.log( "Its finite solutions." );
  18585. } else {
  18586. console.log( "Too bad, no solutions." );
  18587. }
  18588. }
  18589. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  18590. if ( s < 0 ) {
  18591. // in case of emergecy, revert to algorithm 1.
  18592. return getBevelVec1( pt_i, pt_j, pt_k );
  18593. }
  18594. intersection = v.multiplyScalar( s ).add( p );
  18595. return intersection.sub( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  18596. }
  18597. var contourMovements = [];
  18598. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18599. if ( j === il ) j = 0;
  18600. if ( k === il ) k = 0;
  18601. // (j)---(i)---(k)
  18602. // console.log('i,j,k', i, j , k)
  18603. var pt_i = contour[ i ];
  18604. var pt_j = contour[ j ];
  18605. var pt_k = contour[ k ];
  18606. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18607. }
  18608. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18609. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18610. ahole = holes[ h ];
  18611. oneHoleMovements = [];
  18612. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18613. if ( j === il ) j = 0;
  18614. if ( k === il ) k = 0;
  18615. // (j)---(i)---(k)
  18616. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18617. }
  18618. holesMovements.push( oneHoleMovements );
  18619. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18620. }
  18621. // Loop bevelSegments, 1 for the front, 1 for the back
  18622. for ( b = 0; b < bevelSegments; b ++ ) {
  18623. //for ( b = bevelSegments; b > 0; b -- ) {
  18624. t = b / bevelSegments;
  18625. z = bevelThickness * ( 1 - t );
  18626. //z = bevelThickness * t;
  18627. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  18628. //bs = bevelSize * t ; // linear
  18629. // contract shape
  18630. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18631. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18632. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  18633. v( vert.x, vert.y, - z );
  18634. }
  18635. // expand holes
  18636. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  18637. ahole = holes[ h ];
  18638. oneHoleMovements = holesMovements[ h ];
  18639. for ( i = 0, il = ahole.length; i < il; i++ ) {
  18640. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18641. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  18642. v( vert.x, vert.y, -z );
  18643. }
  18644. }
  18645. }
  18646. bs = bevelSize;
  18647. // Back facing vertices
  18648. for ( i = 0; i < vlen; i ++ ) {
  18649. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18650. if ( !extrudeByPath ) {
  18651. v( vert.x, vert.y, 0 );
  18652. } else {
  18653. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18654. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  18655. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  18656. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  18657. v( position2.x, position2.y, position2.z );
  18658. }
  18659. }
  18660. // Add stepped vertices...
  18661. // Including front facing vertices
  18662. var s;
  18663. for ( s = 1; s <= steps; s ++ ) {
  18664. for ( i = 0; i < vlen; i ++ ) {
  18665. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18666. if ( !extrudeByPath ) {
  18667. v( vert.x, vert.y, amount / steps * s );
  18668. } else {
  18669. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18670. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  18671. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  18672. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  18673. v( position2.x, position2.y, position2.z );
  18674. }
  18675. }
  18676. }
  18677. // Add bevel segments planes
  18678. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18679. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  18680. t = b / bevelSegments;
  18681. z = bevelThickness * ( 1 - t );
  18682. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  18683. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  18684. // contract shape
  18685. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18686. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18687. v( vert.x, vert.y, amount + z );
  18688. }
  18689. // expand holes
  18690. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18691. ahole = holes[ h ];
  18692. oneHoleMovements = holesMovements[ h ];
  18693. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18694. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18695. if ( !extrudeByPath ) {
  18696. v( vert.x, vert.y, amount + z );
  18697. } else {
  18698. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  18699. }
  18700. }
  18701. }
  18702. }
  18703. /* Faces */
  18704. // Top and bottom faces
  18705. buildLidFaces();
  18706. // Sides faces
  18707. buildSideFaces();
  18708. ///// Internal functions
  18709. function buildLidFaces() {
  18710. if ( bevelEnabled ) {
  18711. var layer = 0 ; // steps + 1
  18712. var offset = vlen * layer;
  18713. // Bottom faces
  18714. for ( i = 0; i < flen; i ++ ) {
  18715. face = faces[ i ];
  18716. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  18717. }
  18718. layer = steps + bevelSegments * 2;
  18719. offset = vlen * layer;
  18720. // Top faces
  18721. for ( i = 0; i < flen; i ++ ) {
  18722. face = faces[ i ];
  18723. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  18724. }
  18725. } else {
  18726. // Bottom faces
  18727. for ( i = 0; i < flen; i++ ) {
  18728. face = faces[ i ];
  18729. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  18730. }
  18731. // Top faces
  18732. for ( i = 0; i < flen; i ++ ) {
  18733. face = faces[ i ];
  18734. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  18735. }
  18736. }
  18737. }
  18738. // Create faces for the z-sides of the shape
  18739. function buildSideFaces() {
  18740. var layeroffset = 0;
  18741. sidewalls( contour, layeroffset );
  18742. layeroffset += contour.length;
  18743. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18744. ahole = holes[ h ];
  18745. sidewalls( ahole, layeroffset );
  18746. //, true
  18747. layeroffset += ahole.length;
  18748. }
  18749. }
  18750. function sidewalls( contour, layeroffset ) {
  18751. var j, k;
  18752. i = contour.length;
  18753. while ( --i >= 0 ) {
  18754. j = i;
  18755. k = i - 1;
  18756. if ( k < 0 ) k = contour.length - 1;
  18757. //console.log('b', i,j, i-1, k,vertices.length);
  18758. var s = 0, sl = steps + bevelSegments * 2;
  18759. for ( s = 0; s < sl; s ++ ) {
  18760. var slen1 = vlen * s;
  18761. var slen2 = vlen * ( s + 1 );
  18762. var a = layeroffset + j + slen1,
  18763. b = layeroffset + k + slen1,
  18764. c = layeroffset + k + slen2,
  18765. d = layeroffset + j + slen2;
  18766. f4( a, b, c, d, contour, s, sl, j, k );
  18767. }
  18768. }
  18769. }
  18770. function v( x, y, z ) {
  18771. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  18772. }
  18773. function f3( a, b, c, isBottom ) {
  18774. a += shapesOffset;
  18775. b += shapesOffset;
  18776. c += shapesOffset;
  18777. // normal, color, material
  18778. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18779. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  18780. scope.faceVertexUvs[ 0 ].push( uvs );
  18781. }
  18782. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  18783. a += shapesOffset;
  18784. b += shapesOffset;
  18785. c += shapesOffset;
  18786. d += shapesOffset;
  18787. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  18788. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  18789. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  18790. scope.faceVertexUvs[ 0 ].push( uvs );
  18791. }
  18792. };
  18793. THREE.ExtrudeGeometry.WorldUVGenerator = {
  18794. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18795. var ax = geometry.vertices[ indexA ].x,
  18796. ay = geometry.vertices[ indexA ].y,
  18797. bx = geometry.vertices[ indexB ].x,
  18798. by = geometry.vertices[ indexB ].y,
  18799. cx = geometry.vertices[ indexC ].x,
  18800. cy = geometry.vertices[ indexC ].y;
  18801. return [
  18802. new THREE.Vector2( ax, ay ),
  18803. new THREE.Vector2( bx, by ),
  18804. new THREE.Vector2( cx, cy )
  18805. ];
  18806. },
  18807. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18808. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  18809. },
  18810. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  18811. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  18812. contourIndex1, contourIndex2 ) {
  18813. var ax = geometry.vertices[ indexA ].x,
  18814. ay = geometry.vertices[ indexA ].y,
  18815. az = geometry.vertices[ indexA ].z,
  18816. bx = geometry.vertices[ indexB ].x,
  18817. by = geometry.vertices[ indexB ].y,
  18818. bz = geometry.vertices[ indexB ].z,
  18819. cx = geometry.vertices[ indexC ].x,
  18820. cy = geometry.vertices[ indexC ].y,
  18821. cz = geometry.vertices[ indexC ].z,
  18822. dx = geometry.vertices[ indexD ].x,
  18823. dy = geometry.vertices[ indexD ].y,
  18824. dz = geometry.vertices[ indexD ].z;
  18825. if ( Math.abs( ay - by ) < 0.01 ) {
  18826. return [
  18827. new THREE.Vector2( ax, 1 - az ),
  18828. new THREE.Vector2( bx, 1 - bz ),
  18829. new THREE.Vector2( cx, 1 - cz ),
  18830. new THREE.Vector2( dx, 1 - dz )
  18831. ];
  18832. } else {
  18833. return [
  18834. new THREE.Vector2( ay, 1 - az ),
  18835. new THREE.Vector2( by, 1 - bz ),
  18836. new THREE.Vector2( cy, 1 - cz ),
  18837. new THREE.Vector2( dy, 1 - dz )
  18838. ];
  18839. }
  18840. }
  18841. };
  18842. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  18843. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  18844. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  18845. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  18846. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  18847. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  18848. /**
  18849. * @author jonobr1 / http://jonobr1.com
  18850. *
  18851. * Creates a one-sided polygonal geometry from a path shape. Similar to
  18852. * ExtrudeGeometry.
  18853. *
  18854. * parameters = {
  18855. *
  18856. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  18857. *
  18858. * material: <int> // material index for front and back faces
  18859. * uvGenerator: <Object> // object that provides UV generator functions
  18860. *
  18861. * }
  18862. **/
  18863. THREE.ShapeGeometry = function ( shapes, options ) {
  18864. THREE.Geometry.call( this );
  18865. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  18866. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18867. this.addShapeList( shapes, options );
  18868. this.computeCentroids();
  18869. this.computeFaceNormals();
  18870. };
  18871. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18872. /**
  18873. * Add an array of shapes to THREE.ShapeGeometry.
  18874. */
  18875. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18876. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  18877. this.addShape( shapes[ i ], options );
  18878. }
  18879. return this;
  18880. };
  18881. /**
  18882. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  18883. */
  18884. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  18885. if ( options === undefined ) options = {};
  18886. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18887. var material = options.material;
  18888. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  18889. var shapebb = this.shapebb;
  18890. //
  18891. var i, l, hole, s;
  18892. var shapesOffset = this.vertices.length;
  18893. var shapePoints = shape.extractPoints( curveSegments );
  18894. var vertices = shapePoints.shape;
  18895. var holes = shapePoints.holes;
  18896. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  18897. if ( reverse ) {
  18898. vertices = vertices.reverse();
  18899. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  18900. for ( i = 0, l = holes.length; i < l; i++ ) {
  18901. hole = holes[ i ];
  18902. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  18903. holes[ i ] = hole.reverse();
  18904. }
  18905. }
  18906. reverse = false;
  18907. }
  18908. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  18909. // Vertices
  18910. var contour = vertices;
  18911. for ( i = 0, l = holes.length; i < l; i++ ) {
  18912. hole = holes[ i ];
  18913. vertices = vertices.concat( hole );
  18914. }
  18915. //
  18916. var vert, vlen = vertices.length;
  18917. var face, flen = faces.length;
  18918. var cont, clen = contour.length;
  18919. for ( i = 0; i < vlen; i++ ) {
  18920. vert = vertices[ i ];
  18921. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  18922. }
  18923. for ( i = 0; i < flen; i++ ) {
  18924. face = faces[ i ];
  18925. var a = face[ 0 ] + shapesOffset;
  18926. var b = face[ 1 ] + shapesOffset;
  18927. var c = face[ 2 ] + shapesOffset;
  18928. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18929. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  18930. }
  18931. };
  18932. /**
  18933. * @author astrodud / http://astrodud.isgreat.org/
  18934. * @author zz85 / https://github.com/zz85
  18935. * @author bhouston / http://exocortex.com
  18936. */
  18937. // points - to create a closed torus, one must use a set of points
  18938. // like so: [ a, b, c, d, a ], see first is the same as last.
  18939. // segments - the number of circumference segments to create
  18940. // phiStart - the starting radian
  18941. // phiLength - the radian (0 to 2*PI) range of the lathed section
  18942. // 2*pi is a closed lathe, less than 2PI is a portion.
  18943. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  18944. THREE.Geometry.call( this );
  18945. segments = segments || 12;
  18946. phiStart = phiStart || 0;
  18947. phiLength = phiLength || 2 * Math.PI;
  18948. var inversePointLength = 1.0 / ( points.length - 1 );
  18949. var inverseSegments = 1.0 / segments;
  18950. for ( var i = 0, il = segments; i <= il; i ++ ) {
  18951. var phi = phiStart + i * inverseSegments * phiLength;
  18952. var c = Math.cos( phi ),
  18953. s = Math.sin( phi );
  18954. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  18955. var pt = points[ j ];
  18956. var vertex = new THREE.Vector3();
  18957. vertex.x = c * pt.x - s * pt.y;
  18958. vertex.y = s * pt.x + c * pt.y;
  18959. vertex.z = pt.z;
  18960. this.vertices.push( vertex );
  18961. }
  18962. }
  18963. var np = points.length;
  18964. for ( var i = 0, il = segments; i < il; i ++ ) {
  18965. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  18966. var base = j + np * i;
  18967. var a = base;
  18968. var b = base + np;
  18969. var c = base + 1 + np;
  18970. var d = base + 1;
  18971. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18972. var u0 = i * inverseSegments;
  18973. var v0 = j * inversePointLength;
  18974. var u1 = u0 + inverseSegments;
  18975. var v1 = v0 + inversePointLength;
  18976. this.faceVertexUvs[ 0 ].push( [
  18977. new THREE.Vector2( u0, v0 ),
  18978. new THREE.Vector2( u1, v0 ),
  18979. new THREE.Vector2( u1, v1 ),
  18980. new THREE.Vector2( u0, v1 )
  18981. ] );
  18982. }
  18983. }
  18984. this.mergeVertices();
  18985. this.computeCentroids();
  18986. this.computeFaceNormals();
  18987. this.computeVertexNormals();
  18988. };
  18989. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18990. /**
  18991. * @author mrdoob / http://mrdoob.com/
  18992. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  18993. */
  18994. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  18995. THREE.Geometry.call( this );
  18996. this.width = width;
  18997. this.height = height;
  18998. this.widthSegments = widthSegments || 1;
  18999. this.heightSegments = heightSegments || 1;
  19000. var ix, iz;
  19001. var width_half = width / 2;
  19002. var height_half = height / 2;
  19003. var gridX = this.widthSegments;
  19004. var gridZ = this.heightSegments;
  19005. var gridX1 = gridX + 1;
  19006. var gridZ1 = gridZ + 1;
  19007. var segment_width = this.width / gridX;
  19008. var segment_height = this.height / gridZ;
  19009. var normal = new THREE.Vector3( 0, 0, 1 );
  19010. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19011. for ( ix = 0; ix < gridX1; ix ++ ) {
  19012. var x = ix * segment_width - width_half;
  19013. var y = iz * segment_height - height_half;
  19014. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19015. }
  19016. }
  19017. for ( iz = 0; iz < gridZ; iz ++ ) {
  19018. for ( ix = 0; ix < gridX; ix ++ ) {
  19019. var a = ix + gridX1 * iz;
  19020. var b = ix + gridX1 * ( iz + 1 );
  19021. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19022. var d = ( ix + 1 ) + gridX1 * iz;
  19023. var face = new THREE.Face4( a, b, c, d );
  19024. face.normal.copy( normal );
  19025. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  19026. this.faces.push( face );
  19027. this.faceVertexUvs[ 0 ].push( [
  19028. new THREE.Vector2( ix / gridX, 1 - iz / gridZ ),
  19029. new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  19030. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  19031. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  19032. ] );
  19033. }
  19034. }
  19035. this.computeCentroids();
  19036. };
  19037. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19038. /**
  19039. * @author mrdoob / http://mrdoob.com/
  19040. */
  19041. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19042. THREE.Geometry.call( this );
  19043. this.radius = radius || 50;
  19044. this.widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19045. this.heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19046. phiStart = phiStart !== undefined ? phiStart : 0;
  19047. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19048. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19049. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19050. var x, y, vertices = [], uvs = [];
  19051. for ( y = 0; y <= this.heightSegments; y ++ ) {
  19052. var verticesRow = [];
  19053. var uvsRow = [];
  19054. for ( x = 0; x <= this.widthSegments; x ++ ) {
  19055. var u = x / this.widthSegments;
  19056. var v = y / this.heightSegments;
  19057. var vertex = new THREE.Vector3();
  19058. vertex.x = - this.radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19059. vertex.y = this.radius * Math.cos( thetaStart + v * thetaLength );
  19060. vertex.z = this.radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19061. this.vertices.push( vertex );
  19062. verticesRow.push( this.vertices.length - 1 );
  19063. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19064. }
  19065. vertices.push( verticesRow );
  19066. uvs.push( uvsRow );
  19067. }
  19068. for ( y = 0; y < this.heightSegments; y ++ ) {
  19069. for ( x = 0; x < this.widthSegments; x ++ ) {
  19070. var v1 = vertices[ y ][ x + 1 ];
  19071. var v2 = vertices[ y ][ x ];
  19072. var v3 = vertices[ y + 1 ][ x ];
  19073. var v4 = vertices[ y + 1 ][ x + 1 ];
  19074. var n1 = this.vertices[ v1 ].clone().normalize();
  19075. var n2 = this.vertices[ v2 ].clone().normalize();
  19076. var n3 = this.vertices[ v3 ].clone().normalize();
  19077. var n4 = this.vertices[ v4 ].clone().normalize();
  19078. var uv1 = uvs[ y ][ x + 1 ].clone();
  19079. var uv2 = uvs[ y ][ x ].clone();
  19080. var uv3 = uvs[ y + 1 ][ x ].clone();
  19081. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19082. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  19083. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19084. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19085. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  19086. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19087. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19088. } else {
  19089. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  19090. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  19091. }
  19092. }
  19093. }
  19094. this.computeCentroids();
  19095. this.computeFaceNormals();
  19096. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19097. };
  19098. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19099. /**
  19100. * @author zz85 / http://www.lab4games.net/zz85/blog
  19101. * @author alteredq / http://alteredqualia.com/
  19102. *
  19103. * For creating 3D text geometry in three.js
  19104. *
  19105. * Text = 3D Text
  19106. *
  19107. * parameters = {
  19108. * size: <float>, // size of the text
  19109. * height: <float>, // thickness to extrude text
  19110. * curveSegments: <int>, // number of points on the curves
  19111. *
  19112. * font: <string>, // font name
  19113. * weight: <string>, // font weight (normal, bold)
  19114. * style: <string>, // font style (normal, italics)
  19115. *
  19116. * bevelEnabled: <bool>, // turn on bevel
  19117. * bevelThickness: <float>, // how deep into text bevel goes
  19118. * bevelSize: <float>, // how far from text outline is bevel
  19119. * }
  19120. *
  19121. */
  19122. /* Usage Examples
  19123. // TextGeometry wrapper
  19124. var text3d = new TextGeometry( text, options );
  19125. // Complete manner
  19126. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19127. var text3d = new ExtrudeGeometry( textShapes, options );
  19128. */
  19129. THREE.TextGeometry = function ( text, parameters ) {
  19130. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19131. // translate parameters to ExtrudeGeometry API
  19132. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19133. // defaults
  19134. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19135. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19136. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19137. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19138. };
  19139. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19140. /**
  19141. * @author oosmoxiecode
  19142. * @author mrdoob / http://mrdoob.com/
  19143. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19144. */
  19145. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19146. THREE.Geometry.call( this );
  19147. var scope = this;
  19148. this.radius = radius || 100;
  19149. this.tube = tube || 40;
  19150. this.radialSegments = radialSegments || 8;
  19151. this.tubularSegments = tubularSegments || 6;
  19152. this.arc = arc || Math.PI * 2;
  19153. var center = new THREE.Vector3(), uvs = [], normals = [];
  19154. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  19155. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  19156. var u = i / this.tubularSegments * this.arc;
  19157. var v = j / this.radialSegments * Math.PI * 2;
  19158. center.x = this.radius * Math.cos( u );
  19159. center.y = this.radius * Math.sin( u );
  19160. var vertex = new THREE.Vector3();
  19161. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  19162. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  19163. vertex.z = this.tube * Math.sin( v );
  19164. this.vertices.push( vertex );
  19165. uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
  19166. normals.push( vertex.clone().sub( center ).normalize() );
  19167. }
  19168. }
  19169. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  19170. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  19171. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  19172. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19173. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  19174. var d = ( this.tubularSegments + 1 ) * j + i;
  19175. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  19176. face.normal.add( normals[ a ] );
  19177. face.normal.add( normals[ b ] );
  19178. face.normal.add( normals[ c ] );
  19179. face.normal.add( normals[ d ] );
  19180. face.normal.normalize();
  19181. this.faces.push( face );
  19182. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19183. }
  19184. }
  19185. this.computeCentroids();
  19186. };
  19187. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19188. /**
  19189. * @author oosmoxiecode
  19190. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19191. */
  19192. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19193. THREE.Geometry.call( this );
  19194. var scope = this;
  19195. this.radius = radius || 100;
  19196. this.tube = tube || 40;
  19197. this.radialSegments = radialSegments || 64;
  19198. this.tubularSegments = tubularSegments || 8;
  19199. this.p = p || 2;
  19200. this.q = q || 3;
  19201. this.heightScale = heightScale || 1;
  19202. this.grid = new Array( this.radialSegments );
  19203. var tang = new THREE.Vector3();
  19204. var n = new THREE.Vector3();
  19205. var bitan = new THREE.Vector3();
  19206. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19207. this.grid[ i ] = new Array( this.tubularSegments );
  19208. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19209. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  19210. var v = j / this.tubularSegments * 2 * Math.PI;
  19211. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  19212. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  19213. var cx, cy;
  19214. tang.subVectors( p2, p1 );
  19215. n.addVectors( p2, p1 );
  19216. bitan.crossVectors( tang, n );
  19217. n.crossVectors( bitan, tang );
  19218. bitan.normalize();
  19219. n.normalize();
  19220. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19221. cy = this.tube * Math.sin( v );
  19222. p1.x += cx * n.x + cy * bitan.x;
  19223. p1.y += cx * n.y + cy * bitan.y;
  19224. p1.z += cx * n.z + cy * bitan.z;
  19225. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  19226. }
  19227. }
  19228. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19229. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19230. var ip = ( i + 1 ) % this.radialSegments;
  19231. var jp = ( j + 1 ) % this.tubularSegments;
  19232. var a = this.grid[ i ][ j ];
  19233. var b = this.grid[ ip ][ j ];
  19234. var c = this.grid[ ip ][ jp ];
  19235. var d = this.grid[ i ][ jp ];
  19236. var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
  19237. var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  19238. var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19239. var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19240. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19241. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  19242. }
  19243. }
  19244. this.computeCentroids();
  19245. this.computeFaceNormals();
  19246. this.computeVertexNormals();
  19247. function vert( x, y, z ) {
  19248. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19249. }
  19250. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  19251. var cu = Math.cos( u );
  19252. var cv = Math.cos( v );
  19253. var su = Math.sin( u );
  19254. var quOverP = in_q / in_p * u;
  19255. var cs = Math.cos( quOverP );
  19256. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19257. var ty = radius * ( 2 + cs ) * su * 0.5;
  19258. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19259. return new THREE.Vector3( tx, ty, tz );
  19260. }
  19261. };
  19262. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19263. /**
  19264. * @author WestLangley / https://github.com/WestLangley
  19265. * @author zz85 / https://github.com/zz85
  19266. * @author miningold / https://github.com/miningold
  19267. *
  19268. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19269. *
  19270. * Creates a tube which extrudes along a 3d spline
  19271. *
  19272. * Uses parallel transport frames as described in
  19273. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19274. */
  19275. THREE.TubeGeometry = function( path, segments, radius, radiusSegments, closed, debug ) {
  19276. THREE.Geometry.call( this );
  19277. this.path = path;
  19278. this.segments = segments || 64;
  19279. this.radius = radius || 1;
  19280. this.radiusSegments = radiusSegments || 8;
  19281. this.closed = closed || false;
  19282. if ( debug ) this.debug = new THREE.Object3D();
  19283. this.grid = [];
  19284. var scope = this,
  19285. tangent,
  19286. normal,
  19287. binormal,
  19288. numpoints = this.segments + 1,
  19289. x, y, z,
  19290. tx, ty, tz,
  19291. u, v,
  19292. cx, cy,
  19293. pos, pos2 = new THREE.Vector3(),
  19294. i, j,
  19295. ip, jp,
  19296. a, b, c, d,
  19297. uva, uvb, uvc, uvd;
  19298. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  19299. tangents = frames.tangents,
  19300. normals = frames.normals,
  19301. binormals = frames.binormals;
  19302. // proxy internals
  19303. this.tangents = tangents;
  19304. this.normals = normals;
  19305. this.binormals = binormals;
  19306. function vert( x, y, z ) {
  19307. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19308. }
  19309. // consruct the grid
  19310. for ( i = 0; i < numpoints; i++ ) {
  19311. this.grid[ i ] = [];
  19312. u = i / ( numpoints - 1 );
  19313. pos = path.getPointAt( u );
  19314. tangent = tangents[ i ];
  19315. normal = normals[ i ];
  19316. binormal = binormals[ i ];
  19317. if ( this.debug ) {
  19318. this.debug.add( new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff ) );
  19319. this.debug.add( new THREE.ArrowHelper(normal, pos, radius, 0xff0000 ) );
  19320. this.debug.add( new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00 ) );
  19321. }
  19322. for ( j = 0; j < this.radiusSegments; j++ ) {
  19323. v = j / this.radiusSegments * 2 * Math.PI;
  19324. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19325. cy = this.radius * Math.sin( v );
  19326. pos2.copy( pos );
  19327. pos2.x += cx * normal.x + cy * binormal.x;
  19328. pos2.y += cx * normal.y + cy * binormal.y;
  19329. pos2.z += cx * normal.z + cy * binormal.z;
  19330. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  19331. }
  19332. }
  19333. // construct the mesh
  19334. for ( i = 0; i < this.segments; i++ ) {
  19335. for ( j = 0; j < this.radiusSegments; j++ ) {
  19336. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  19337. jp = (j + 1) % this.radiusSegments;
  19338. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  19339. b = this.grid[ ip ][ j ];
  19340. c = this.grid[ ip ][ jp ];
  19341. d = this.grid[ i ][ jp ];
  19342. uva = new THREE.Vector2( i / this.segments, j / this.radiusSegments );
  19343. uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radiusSegments );
  19344. uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radiusSegments );
  19345. uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radiusSegments );
  19346. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19347. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  19348. }
  19349. }
  19350. this.computeCentroids();
  19351. this.computeFaceNormals();
  19352. this.computeVertexNormals();
  19353. };
  19354. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19355. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19356. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  19357. var tangent = new THREE.Vector3(),
  19358. normal = new THREE.Vector3(),
  19359. binormal = new THREE.Vector3(),
  19360. tangents = [],
  19361. normals = [],
  19362. binormals = [],
  19363. vec = new THREE.Vector3(),
  19364. mat = new THREE.Matrix4(),
  19365. numpoints = segments + 1,
  19366. theta,
  19367. epsilon = 0.0001,
  19368. smallest,
  19369. tx, ty, tz,
  19370. i, u, v;
  19371. // expose internals
  19372. this.tangents = tangents;
  19373. this.normals = normals;
  19374. this.binormals = binormals;
  19375. // compute the tangent vectors for each segment on the path
  19376. for ( i = 0; i < numpoints; i++ ) {
  19377. u = i / ( numpoints - 1 );
  19378. tangents[ i ] = path.getTangentAt( u );
  19379. tangents[ i ].normalize();
  19380. }
  19381. initialNormal3();
  19382. function initialNormal1(lastBinormal) {
  19383. // fixed start binormal. Has dangers of 0 vectors
  19384. normals[ 0 ] = new THREE.Vector3();
  19385. binormals[ 0 ] = new THREE.Vector3();
  19386. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19387. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  19388. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19389. }
  19390. function initialNormal2() {
  19391. // This uses the Frenet-Serret formula for deriving binormal
  19392. var t2 = path.getTangentAt( epsilon );
  19393. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  19394. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  19395. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  19396. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19397. }
  19398. function initialNormal3() {
  19399. // select an initial normal vector perpenicular to the first tangent vector,
  19400. // and in the direction of the smallest tangent xyz component
  19401. normals[ 0 ] = new THREE.Vector3();
  19402. binormals[ 0 ] = new THREE.Vector3();
  19403. smallest = Number.MAX_VALUE;
  19404. tx = Math.abs( tangents[ 0 ].x );
  19405. ty = Math.abs( tangents[ 0 ].y );
  19406. tz = Math.abs( tangents[ 0 ].z );
  19407. if ( tx <= smallest ) {
  19408. smallest = tx;
  19409. normal.set( 1, 0, 0 );
  19410. }
  19411. if ( ty <= smallest ) {
  19412. smallest = ty;
  19413. normal.set( 0, 1, 0 );
  19414. }
  19415. if ( tz <= smallest ) {
  19416. normal.set( 0, 0, 1 );
  19417. }
  19418. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19419. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19420. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19421. }
  19422. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19423. for ( i = 1; i < numpoints; i++ ) {
  19424. normals[ i ] = normals[ i-1 ].clone();
  19425. binormals[ i ] = binormals[ i-1 ].clone();
  19426. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  19427. if ( vec.length() > epsilon ) {
  19428. vec.normalize();
  19429. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  19430. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19431. }
  19432. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19433. }
  19434. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19435. if ( closed ) {
  19436. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  19437. theta /= ( numpoints - 1 );
  19438. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  19439. theta = -theta;
  19440. }
  19441. for ( i = 1; i < numpoints; i++ ) {
  19442. // twist a little...
  19443. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19444. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19445. }
  19446. }
  19447. };
  19448. /**
  19449. * @author clockworkgeek / https://github.com/clockworkgeek
  19450. * @author timothypratley / https://github.com/timothypratley
  19451. */
  19452. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  19453. THREE.Geometry.call( this );
  19454. radius = radius || 1;
  19455. detail = detail || 0;
  19456. var that = this;
  19457. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  19458. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  19459. }
  19460. var midpoints = [], p = this.vertices;
  19461. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19462. make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );
  19463. }
  19464. this.mergeVertices();
  19465. // Apply radius
  19466. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19467. this.vertices[ i ].multiplyScalar( radius );
  19468. }
  19469. // Project vector onto sphere's surface
  19470. function prepare( vector ) {
  19471. var vertex = vector.normalize().clone();
  19472. vertex.index = that.vertices.push( vertex ) - 1;
  19473. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19474. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19475. var v = inclination( vector ) / Math.PI + 0.5;
  19476. vertex.uv = new THREE.Vector2( u, 1 - v );
  19477. return vertex;
  19478. }
  19479. // Approximate a curved face with recursively sub-divided triangles.
  19480. function make( v1, v2, v3, detail ) {
  19481. if ( detail < 1 ) {
  19482. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19483. face.centroid.add( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  19484. face.normal = face.centroid.clone().normalize();
  19485. that.faces.push( face );
  19486. var azi = azimuth( face.centroid );
  19487. that.faceVertexUvs[ 0 ].push( [
  19488. correctUV( v1.uv, v1, azi ),
  19489. correctUV( v2.uv, v2, azi ),
  19490. correctUV( v3.uv, v3, azi )
  19491. ] );
  19492. } else {
  19493. detail -= 1;
  19494. // split triangle into 4 smaller triangles
  19495. make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
  19496. make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
  19497. make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
  19498. make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant
  19499. }
  19500. }
  19501. function midpoint( v1, v2 ) {
  19502. if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
  19503. if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];
  19504. var mid = midpoints[ v1.index ][ v2.index ];
  19505. if ( mid === undefined ) {
  19506. // generate mean point and project to surface with prepare()
  19507. midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
  19508. new THREE.Vector3().addVectors( v1, v2 ).divideScalar( 2 )
  19509. );
  19510. }
  19511. return mid;
  19512. }
  19513. // Angle around the Y axis, counter-clockwise when looking from above.
  19514. function azimuth( vector ) {
  19515. return Math.atan2( vector.z, -vector.x );
  19516. }
  19517. // Angle above the XZ plane.
  19518. function inclination( vector ) {
  19519. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19520. }
  19521. // Texture fixing helper. Spheres have some odd behaviours.
  19522. function correctUV( uv, vector, azimuth ) {
  19523. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  19524. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  19525. return uv;
  19526. }
  19527. this.computeCentroids();
  19528. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19529. };
  19530. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19531. /**
  19532. * @author timothypratley / https://github.com/timothypratley
  19533. */
  19534. THREE.IcosahedronGeometry = function ( radius, detail ) {
  19535. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19536. var vertices = [
  19537. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  19538. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  19539. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  19540. ];
  19541. var faces = [
  19542. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  19543. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  19544. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  19545. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  19546. ];
  19547. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19548. };
  19549. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19550. /**
  19551. * @author timothypratley / https://github.com/timothypratley
  19552. */
  19553. THREE.OctahedronGeometry = function ( radius, detail ) {
  19554. var vertices = [
  19555. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  19556. ];
  19557. var faces = [
  19558. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  19559. ];
  19560. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19561. };
  19562. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19563. /**
  19564. * @author timothypratley / https://github.com/timothypratley
  19565. */
  19566. THREE.TetrahedronGeometry = function ( radius, detail ) {
  19567. var vertices = [
  19568. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  19569. ];
  19570. var faces = [
  19571. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  19572. ];
  19573. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19574. };
  19575. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19576. /**
  19577. * @author zz85 / https://github.com/zz85
  19578. * Parametric Surfaces Geometry
  19579. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  19580. *
  19581. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  19582. *
  19583. */
  19584. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  19585. THREE.Geometry.call( this );
  19586. var verts = this.vertices;
  19587. var faces = this.faces;
  19588. var uvs = this.faceVertexUvs[ 0 ];
  19589. useTris = (useTris === undefined) ? false : useTris;
  19590. var i, il, j, p;
  19591. var u, v;
  19592. var stackCount = stacks + 1;
  19593. var sliceCount = slices + 1;
  19594. for ( i = 0; i <= stacks; i ++ ) {
  19595. v = i / stacks;
  19596. for ( j = 0; j <= slices; j ++ ) {
  19597. u = j / slices;
  19598. p = func( u, v );
  19599. verts.push( p );
  19600. }
  19601. }
  19602. var a, b, c, d;
  19603. var uva, uvb, uvc, uvd;
  19604. for ( i = 0; i < stacks; i ++ ) {
  19605. for ( j = 0; j < slices; j ++ ) {
  19606. a = i * sliceCount + j;
  19607. b = i * sliceCount + j + 1;
  19608. c = (i + 1) * sliceCount + j;
  19609. d = (i + 1) * sliceCount + j + 1;
  19610. uva = new THREE.Vector2( j / slices, i / stacks );
  19611. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  19612. uvc = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  19613. uvd = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  19614. if ( useTris ) {
  19615. faces.push( new THREE.Face3( a, b, c ) );
  19616. faces.push( new THREE.Face3( b, d, c ) );
  19617. uvs.push( [ uva, uvb, uvc ] );
  19618. uvs.push( [ uvb, uvd, uvc ] );
  19619. } else {
  19620. faces.push( new THREE.Face4( a, b, d, c ) );
  19621. uvs.push( [ uva, uvb, uvd, uvc ] );
  19622. }
  19623. }
  19624. }
  19625. // console.log(this);
  19626. // magic bullet
  19627. // var diff = this.mergeVertices();
  19628. // console.log('removed ', diff, ' vertices by merging');
  19629. this.computeCentroids();
  19630. this.computeFaceNormals();
  19631. this.computeVertexNormals();
  19632. };
  19633. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19634. /**
  19635. * @author qiao / https://github.com/qiao
  19636. * @fileoverview This is a convex hull generator using the incremental method.
  19637. * The complexity is O(n^2) where n is the number of vertices.
  19638. * O(nlogn) algorithms do exist, but they are much more complicated.
  19639. *
  19640. * Benchmark:
  19641. *
  19642. * Platform: CPU: P7350 @2.00GHz Engine: V8
  19643. *
  19644. * Num Vertices Time(ms)
  19645. *
  19646. * 10 1
  19647. * 20 3
  19648. * 30 19
  19649. * 40 48
  19650. * 50 107
  19651. */
  19652. THREE.ConvexGeometry = function( vertices ) {
  19653. THREE.Geometry.call( this );
  19654. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  19655. for ( var i = 3; i < vertices.length; i++ ) {
  19656. addPoint( i );
  19657. }
  19658. function addPoint( vertexId ) {
  19659. var vertex = vertices[ vertexId ].clone();
  19660. var mag = vertex.length();
  19661. vertex.x += mag * randomOffset();
  19662. vertex.y += mag * randomOffset();
  19663. vertex.z += mag * randomOffset();
  19664. var hole = [];
  19665. for ( var f = 0; f < faces.length; ) {
  19666. var face = faces[ f ];
  19667. // for each face, if the vertex can see it,
  19668. // then we try to add the face's edges into the hole.
  19669. if ( visible( face, vertex ) ) {
  19670. for ( var e = 0; e < 3; e++ ) {
  19671. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  19672. var boundary = true;
  19673. // remove duplicated edges.
  19674. for ( var h = 0; h < hole.length; h++ ) {
  19675. if ( equalEdge( hole[ h ], edge ) ) {
  19676. hole[ h ] = hole[ hole.length - 1 ];
  19677. hole.pop();
  19678. boundary = false;
  19679. break;
  19680. }
  19681. }
  19682. if ( boundary ) {
  19683. hole.push( edge );
  19684. }
  19685. }
  19686. // remove faces[ f ]
  19687. faces[ f ] = faces[ faces.length - 1 ];
  19688. faces.pop();
  19689. } else { // not visible
  19690. f++;
  19691. }
  19692. }
  19693. // construct the new faces formed by the edges of the hole and the vertex
  19694. for ( var h = 0; h < hole.length; h++ ) {
  19695. faces.push( [
  19696. hole[ h ][ 0 ],
  19697. hole[ h ][ 1 ],
  19698. vertexId
  19699. ] );
  19700. }
  19701. }
  19702. /**
  19703. * Whether the face is visible from the vertex
  19704. */
  19705. function visible( face, vertex ) {
  19706. var va = vertices[ face[ 0 ] ];
  19707. var vb = vertices[ face[ 1 ] ];
  19708. var vc = vertices[ face[ 2 ] ];
  19709. var n = normal( va, vb, vc );
  19710. // distance from face to origin
  19711. var dist = n.dot( va );
  19712. return n.dot( vertex ) >= dist;
  19713. }
  19714. /**
  19715. * Face normal
  19716. */
  19717. function normal( va, vb, vc ) {
  19718. var cb = new THREE.Vector3();
  19719. var ab = new THREE.Vector3();
  19720. cb.subVectors( vc, vb );
  19721. ab.subVectors( va, vb );
  19722. cb.cross( ab );
  19723. cb.normalize();
  19724. return cb;
  19725. }
  19726. /**
  19727. * Detect whether two edges are equal.
  19728. * Note that when constructing the convex hull, two same edges can only
  19729. * be of the negative direction.
  19730. */
  19731. function equalEdge( ea, eb ) {
  19732. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  19733. }
  19734. /**
  19735. * Create a random offset between -1e-6 and 1e-6.
  19736. */
  19737. function randomOffset() {
  19738. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  19739. }
  19740. /**
  19741. * XXX: Not sure if this is the correct approach. Need someone to review.
  19742. */
  19743. function vertexUv( vertex ) {
  19744. var mag = vertex.length();
  19745. return new THREE.Vector2( vertex.x / mag, vertex.y / mag );
  19746. }
  19747. // Push vertices into `this.vertices`, skipping those inside the hull
  19748. var id = 0;
  19749. var newId = new Array( vertices.length ); // map from old vertex id to new id
  19750. for ( var i = 0; i < faces.length; i++ ) {
  19751. var face = faces[ i ];
  19752. for ( var j = 0; j < 3; j++ ) {
  19753. if ( newId[ face[ j ] ] === undefined ) {
  19754. newId[ face[ j ] ] = id++;
  19755. this.vertices.push( vertices[ face[ j ] ] );
  19756. }
  19757. face[ j ] = newId[ face[ j ] ];
  19758. }
  19759. }
  19760. // Convert faces into instances of THREE.Face3
  19761. for ( var i = 0; i < faces.length; i++ ) {
  19762. this.faces.push( new THREE.Face3(
  19763. faces[ i ][ 0 ],
  19764. faces[ i ][ 1 ],
  19765. faces[ i ][ 2 ]
  19766. ) );
  19767. }
  19768. // Compute UVs
  19769. for ( var i = 0; i < this.faces.length; i++ ) {
  19770. var face = this.faces[ i ];
  19771. this.faceVertexUvs[ 0 ].push( [
  19772. vertexUv( this.vertices[ face.a ] ),
  19773. vertexUv( this.vertices[ face.b ] ),
  19774. vertexUv( this.vertices[ face.c ])
  19775. ] );
  19776. }
  19777. this.computeCentroids();
  19778. this.computeFaceNormals();
  19779. this.computeVertexNormals();
  19780. };
  19781. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19782. /**
  19783. * @author sroucheray / http://sroucheray.org/
  19784. * @author mrdoob / http://mrdoob.com/
  19785. */
  19786. THREE.AxisHelper = function ( size ) {
  19787. var geometry = new THREE.Geometry();
  19788. geometry.vertices.push(
  19789. new THREE.Vector3(), new THREE.Vector3( size || 1, 0, 0 ),
  19790. new THREE.Vector3(), new THREE.Vector3( 0, size || 1, 0 ),
  19791. new THREE.Vector3(), new THREE.Vector3( 0, 0, size || 1 )
  19792. );
  19793. geometry.colors.push(
  19794. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  19795. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  19796. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  19797. );
  19798. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  19799. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  19800. };
  19801. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  19802. /**
  19803. * @author WestLangley / http://github.com/WestLangley
  19804. * @author zz85 / https://github.com/zz85
  19805. * @author bhouston / https://exocortex.com
  19806. *
  19807. * Creates an arrow for visualizing directions
  19808. *
  19809. * Parameters:
  19810. * dir - Vector3
  19811. * origin - Vector3
  19812. * length - Number
  19813. * hex - color in hex value
  19814. */
  19815. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  19816. THREE.Object3D.call( this );
  19817. if ( length === undefined ) length = 20;
  19818. if ( hex === undefined ) hex = 0xffff00;
  19819. var lineGeometry = new THREE.Geometry();
  19820. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  19821. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  19822. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  19823. this.add( this.line );
  19824. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  19825. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  19826. this.cone.position.set( 0, 1, 0 );
  19827. this.add( this.cone );
  19828. if ( origin instanceof THREE.Vector3 ) this.position = origin;
  19829. this.setDirection( dir );
  19830. this.setLength( length );
  19831. };
  19832. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  19833. THREE.ArrowHelper.prototype.setDirection = function ( dir ) {
  19834. var d = THREE.ArrowHelper.__v1.copy( dir ).normalize();
  19835. if ( d.y > 0.999 ) {
  19836. this.rotation.set( 0, 0, 0 );
  19837. } else if ( d.y < - 0.999 ) {
  19838. this.rotation.set( Math.PI, 0, 0 );
  19839. } else {
  19840. var axis = THREE.ArrowHelper.__v2.set( d.z, 0, - d.x ).normalize();
  19841. var radians = Math.acos( d.y );
  19842. var quaternion = THREE.ArrowHelper.__q1.setFromAxisAngle( axis, radians );
  19843. this.rotation.setEulerFromQuaternion( quaternion, this.eulerOrder );
  19844. }
  19845. };
  19846. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  19847. this.scale.set( length, length, length );
  19848. };
  19849. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  19850. this.line.material.color.setHex( hex );
  19851. this.cone.material.color.setHex( hex );
  19852. };
  19853. THREE.ArrowHelper.__v1 = new THREE.Vector3();
  19854. THREE.ArrowHelper.__v2 = new THREE.Vector3();
  19855. THREE.ArrowHelper.__q1 = new THREE.Quaternion();
  19856. /**
  19857. * @author alteredq / http://alteredqualia.com/
  19858. *
  19859. * - shows frustum, line of sight and up of the camera
  19860. * - suitable for fast updates
  19861. * - based on frustum visualization in lightgl.js shadowmap example
  19862. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  19863. */
  19864. THREE.CameraHelper = function ( camera ) {
  19865. THREE.Line.call( this );
  19866. var scope = this;
  19867. this.geometry = new THREE.Geometry();
  19868. this.material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  19869. this.type = THREE.LinePieces;
  19870. this.matrixWorld = camera.matrixWorld;
  19871. this.matrixAutoUpdate = false;
  19872. this.pointMap = {};
  19873. // colors
  19874. var hexFrustum = 0xffaa00;
  19875. var hexCone = 0xff0000;
  19876. var hexUp = 0x00aaff;
  19877. var hexTarget = 0xffffff;
  19878. var hexCross = 0x333333;
  19879. // near
  19880. addLine( "n1", "n2", hexFrustum );
  19881. addLine( "n2", "n4", hexFrustum );
  19882. addLine( "n4", "n3", hexFrustum );
  19883. addLine( "n3", "n1", hexFrustum );
  19884. // far
  19885. addLine( "f1", "f2", hexFrustum );
  19886. addLine( "f2", "f4", hexFrustum );
  19887. addLine( "f4", "f3", hexFrustum );
  19888. addLine( "f3", "f1", hexFrustum );
  19889. // sides
  19890. addLine( "n1", "f1", hexFrustum );
  19891. addLine( "n2", "f2", hexFrustum );
  19892. addLine( "n3", "f3", hexFrustum );
  19893. addLine( "n4", "f4", hexFrustum );
  19894. // cone
  19895. addLine( "p", "n1", hexCone );
  19896. addLine( "p", "n2", hexCone );
  19897. addLine( "p", "n3", hexCone );
  19898. addLine( "p", "n4", hexCone );
  19899. // up
  19900. addLine( "u1", "u2", hexUp );
  19901. addLine( "u2", "u3", hexUp );
  19902. addLine( "u3", "u1", hexUp );
  19903. // target
  19904. addLine( "c", "t", hexTarget );
  19905. addLine( "p", "c", hexCross );
  19906. // cross
  19907. addLine( "cn1", "cn2", hexCross );
  19908. addLine( "cn3", "cn4", hexCross );
  19909. addLine( "cf1", "cf2", hexCross );
  19910. addLine( "cf3", "cf4", hexCross );
  19911. this.camera = camera;
  19912. function addLine( a, b, hex ) {
  19913. addPoint( a, hex );
  19914. addPoint( b, hex );
  19915. }
  19916. function addPoint( id, hex ) {
  19917. scope.geometry.vertices.push( new THREE.Vector3() );
  19918. scope.geometry.colors.push( new THREE.Color( hex ) );
  19919. if ( scope.pointMap[ id ] === undefined ) scope.pointMap[ id ] = [];
  19920. scope.pointMap[ id ].push( scope.geometry.vertices.length - 1 );
  19921. }
  19922. this.update( camera );
  19923. };
  19924. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  19925. THREE.CameraHelper.prototype.update = function () {
  19926. var scope = this;
  19927. var w = 1, h = 1;
  19928. // we need just camera projection matrix
  19929. // world matrix must be identity
  19930. THREE.CameraHelper.__c.projectionMatrix.copy( this.camera.projectionMatrix );
  19931. // center / target
  19932. setPoint( "c", 0, 0, -1 );
  19933. setPoint( "t", 0, 0, 1 );
  19934. // near
  19935. setPoint( "n1", -w, -h, -1 );
  19936. setPoint( "n2", w, -h, -1 );
  19937. setPoint( "n3", -w, h, -1 );
  19938. setPoint( "n4", w, h, -1 );
  19939. // far
  19940. setPoint( "f1", -w, -h, 1 );
  19941. setPoint( "f2", w, -h, 1 );
  19942. setPoint( "f3", -w, h, 1 );
  19943. setPoint( "f4", w, h, 1 );
  19944. // up
  19945. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  19946. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  19947. setPoint( "u3", 0, h * 2, -1 );
  19948. // cross
  19949. setPoint( "cf1", -w, 0, 1 );
  19950. setPoint( "cf2", w, 0, 1 );
  19951. setPoint( "cf3", 0, -h, 1 );
  19952. setPoint( "cf4", 0, h, 1 );
  19953. setPoint( "cn1", -w, 0, -1 );
  19954. setPoint( "cn2", w, 0, -1 );
  19955. setPoint( "cn3", 0, -h, -1 );
  19956. setPoint( "cn4", 0, h, -1 );
  19957. function setPoint( point, x, y, z ) {
  19958. THREE.CameraHelper.__v.set( x, y, z );
  19959. THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
  19960. var points = scope.pointMap[ point ];
  19961. if ( points !== undefined ) {
  19962. for ( var i = 0, il = points.length; i < il; i ++ ) {
  19963. scope.geometry.vertices[ points[ i ] ].copy( THREE.CameraHelper.__v );
  19964. }
  19965. }
  19966. }
  19967. this.geometry.verticesNeedUpdate = true;
  19968. };
  19969. THREE.CameraHelper.__projector = new THREE.Projector();
  19970. THREE.CameraHelper.__v = new THREE.Vector3();
  19971. THREE.CameraHelper.__c = new THREE.Camera();
  19972. /**
  19973. * @author alteredq / http://alteredqualia.com/
  19974. *
  19975. * - shows directional light color, intensity, position, orientation and target
  19976. */
  19977. THREE.DirectionalLightHelper = function ( light, sphereSize ) {
  19978. THREE.Object3D.call( this );
  19979. this.light = light;
  19980. // position
  19981. this.position = light.position;
  19982. // direction
  19983. this.direction = new THREE.Vector3();
  19984. this.direction.subVectors( light.target.position, light.position );
  19985. // color
  19986. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  19987. this.color = light.color.clone();
  19988. this.color.multiplyScalar( intensity );
  19989. var hexColor = this.color.getHex();
  19990. // light helper
  19991. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  19992. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  19993. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  19994. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  19995. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  19996. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  19997. this.add( this.lightSphere );
  19998. this.add( this.lightRays );
  19999. this.lightSphere.properties.isGizmo = true;
  20000. this.lightSphere.properties.gizmoSubject = light;
  20001. this.lightSphere.properties.gizmoRoot = this;
  20002. // light target helper
  20003. this.targetSphere = null;
  20004. if ( light.target.properties.targetInverse !== undefined ) {
  20005. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  20006. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  20007. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  20008. this.targetSphere.position = light.target.position;
  20009. this.targetSphere.properties.isGizmo = true;
  20010. this.targetSphere.properties.gizmoSubject = light.target;
  20011. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  20012. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20013. var lineGeometry = new THREE.Geometry();
  20014. lineGeometry.vertices.push( this.position.clone() );
  20015. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  20016. lineGeometry.computeLineDistances();
  20017. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  20018. this.targetLine.properties.isGizmo = true;
  20019. }
  20020. //
  20021. this.properties.isGizmo = true;
  20022. }
  20023. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20024. THREE.DirectionalLightHelper.prototype.update = function () {
  20025. // update arrow orientation
  20026. // pointing from light to target
  20027. this.direction.subVectors( this.light.target.position, this.light.position );
  20028. // update arrow, spheres, rays and line colors to light color * light intensity
  20029. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20030. this.color.copy( this.light.color );
  20031. this.color.multiplyScalar( intensity );
  20032. this.lightSphere.material.color.copy( this.color );
  20033. this.lightRays.material.color.copy( this.color );
  20034. // Only update targetSphere and targetLine if available
  20035. if ( this.targetSphere !== null ) {
  20036. this.targetSphere.material.color.copy( this.color );
  20037. this.targetLine.material.color.copy( this.color );
  20038. // update target line vertices
  20039. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  20040. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  20041. this.targetLine.geometry.computeLineDistances();
  20042. this.targetLine.geometry.verticesNeedUpdate = true;
  20043. }
  20044. }
  20045. /**
  20046. * @author alteredq / http://alteredqualia.com/
  20047. *
  20048. * - shows hemisphere light intensity, sky and ground colors and directions
  20049. */
  20050. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  20051. THREE.Object3D.call( this );
  20052. this.light = light;
  20053. // position
  20054. this.position = light.position;
  20055. //
  20056. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20057. // sky color
  20058. this.color = light.color.clone();
  20059. this.color.multiplyScalar( intensity );
  20060. var hexColor = this.color.getHex();
  20061. // ground color
  20062. this.groundColor = light.groundColor.clone();
  20063. this.groundColor.multiplyScalar( intensity );
  20064. var hexColorGround = this.groundColor.getHex();
  20065. // double colored light bulb
  20066. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, 0, Math.PI * 0.5 );
  20067. var bulbGroundGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, Math.PI * 0.5, Math.PI );
  20068. var bulbSkyMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20069. var bulbGroundMaterial = new THREE.MeshBasicMaterial( { color: hexColorGround, fog: false } );
  20070. for ( var i = 0, il = bulbGeometry.faces.length; i < il; i ++ ) {
  20071. bulbGeometry.faces[ i ].materialIndex = 0;
  20072. }
  20073. for ( var i = 0, il = bulbGroundGeometry.faces.length; i < il; i ++ ) {
  20074. bulbGroundGeometry.faces[ i ].materialIndex = 1;
  20075. }
  20076. THREE.GeometryUtils.merge( bulbGeometry, bulbGroundGeometry );
  20077. this.lightSphere = new THREE.Mesh( bulbGeometry, new THREE.MeshFaceMaterial( [ bulbSkyMaterial, bulbGroundMaterial ] ) );
  20078. // arrows for sky and ground light directions
  20079. this.lightArrow = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * 1.1, 0 ), arrowLength, hexColor );
  20080. this.lightArrow.rotation.x = Math.PI;
  20081. this.lightArrowGround = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * -1.1, 0 ), arrowLength, hexColorGround );
  20082. var joint = new THREE.Object3D();
  20083. joint.rotation.x = -Math.PI * 0.5;
  20084. joint.add( this.lightSphere );
  20085. joint.add( this.lightArrow );
  20086. joint.add( this.lightArrowGround );
  20087. this.add( joint );
  20088. //
  20089. this.lightSphere.properties.isGizmo = true;
  20090. this.lightSphere.properties.gizmoSubject = light;
  20091. this.lightSphere.properties.gizmoRoot = this;
  20092. //
  20093. this.properties.isGizmo = true;
  20094. //
  20095. this.target = new THREE.Vector3();
  20096. this.lookAt( this.target );
  20097. }
  20098. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20099. THREE.HemisphereLightHelper.prototype.update = function () {
  20100. // update sphere sky and ground colors to light color * light intensity
  20101. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20102. this.color.copy( this.light.color );
  20103. this.color.multiplyScalar( intensity );
  20104. this.groundColor.copy( this.light.groundColor );
  20105. this.groundColor.multiplyScalar( intensity );
  20106. this.lightSphere.material.materials[ 0 ].color.copy( this.color );
  20107. this.lightSphere.material.materials[ 1 ].color.copy( this.groundColor );
  20108. this.lightArrow.setColor( this.color.getHex() );
  20109. this.lightArrowGround.setColor( this.groundColor.getHex() );
  20110. this.lookAt( this.target );
  20111. }
  20112. /**
  20113. * @author alteredq / http://alteredqualia.com/
  20114. *
  20115. * - shows point light color, intensity, position and distance
  20116. */
  20117. THREE.PointLightHelper = function ( light, sphereSize ) {
  20118. THREE.Object3D.call( this );
  20119. this.light = light;
  20120. // position
  20121. this.position = light.position;
  20122. // color
  20123. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20124. this.color = light.color.clone();
  20125. this.color.multiplyScalar( intensity );
  20126. var hexColor = this.color.getHex();
  20127. // light helper
  20128. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20129. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20130. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20131. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20132. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20133. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20134. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20135. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20136. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20137. var d = light.distance;
  20138. if ( d === 0.0 ) {
  20139. this.lightDistance.visible = false;
  20140. } else {
  20141. this.lightDistance.scale.set( d, d, d );
  20142. }
  20143. this.add( this.lightSphere );
  20144. this.add( this.lightRays );
  20145. this.add( this.lightDistance );
  20146. //
  20147. this.lightSphere.properties.isGizmo = true;
  20148. this.lightSphere.properties.gizmoSubject = light;
  20149. this.lightSphere.properties.gizmoRoot = this;
  20150. //
  20151. this.properties.isGizmo = true;
  20152. }
  20153. THREE.PointLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20154. THREE.PointLightHelper.prototype.update = function () {
  20155. // update sphere and rays colors to light color * light intensity
  20156. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20157. this.color.copy( this.light.color );
  20158. this.color.multiplyScalar( intensity );
  20159. this.lightSphere.material.color.copy( this.color );
  20160. this.lightRays.material.color.copy( this.color );
  20161. this.lightDistance.material.color.copy( this.color );
  20162. //
  20163. var d = this.light.distance;
  20164. if ( d === 0.0 ) {
  20165. this.lightDistance.visible = false;
  20166. } else {
  20167. this.lightDistance.visible = true;
  20168. this.lightDistance.scale.set( d, d, d );
  20169. }
  20170. }
  20171. /**
  20172. * @author alteredq / http://alteredqualia.com/
  20173. *
  20174. * - shows spot light color, intensity, position, orientation, light cone and target
  20175. */
  20176. THREE.SpotLightHelper = function ( light, sphereSize ) {
  20177. THREE.Object3D.call( this );
  20178. this.light = light;
  20179. // position
  20180. this.position = light.position;
  20181. // direction
  20182. this.direction = new THREE.Vector3();
  20183. this.direction.subVectors( light.target.position, light.position );
  20184. // color
  20185. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20186. this.color = light.color.clone();
  20187. this.color.multiplyScalar( intensity );
  20188. var hexColor = this.color.getHex();
  20189. // light helper
  20190. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20191. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20192. var coneGeometry = new THREE.CylinderGeometry( 0.0001, 1, 1, 8, 1, true );
  20193. var coneMatrix = new THREE.Matrix4();
  20194. coneMatrix.rotateX( -Math.PI/2 );
  20195. coneMatrix.translate( new THREE.Vector3( 0, -0.5, 0 ) );
  20196. coneGeometry.applyMatrix( coneMatrix );
  20197. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20198. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20199. var coneMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.3, transparent: true } );
  20200. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20201. this.lightCone = new THREE.Mesh( coneGeometry, coneMaterial );
  20202. var coneLength = light.distance ? light.distance : 10000;
  20203. var coneWidth = coneLength * Math.tan( light.angle * 0.5 ) * 2;
  20204. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  20205. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20206. this.gyroscope = new THREE.Gyroscope();
  20207. this.gyroscope.add( this.lightSphere );
  20208. this.gyroscope.add( this.lightRays );
  20209. this.add( this.gyroscope );
  20210. this.add( this.lightCone );
  20211. this.lookAt( light.target.position );
  20212. this.lightSphere.properties.isGizmo = true;
  20213. this.lightSphere.properties.gizmoSubject = light;
  20214. this.lightSphere.properties.gizmoRoot = this;
  20215. // light target helper
  20216. this.targetSphere = null;
  20217. if ( light.target.properties.targetInverse !== undefined ) {
  20218. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  20219. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  20220. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  20221. this.targetSphere.position = light.target.position;
  20222. this.targetSphere.properties.isGizmo = true;
  20223. this.targetSphere.properties.gizmoSubject = light.target;
  20224. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  20225. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20226. var lineGeometry = new THREE.Geometry();
  20227. lineGeometry.vertices.push( this.position.clone() );
  20228. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  20229. lineGeometry.computeLineDistances();
  20230. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  20231. this.targetLine.properties.isGizmo = true;
  20232. }
  20233. //
  20234. this.properties.isGizmo = true;
  20235. }
  20236. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20237. THREE.SpotLightHelper.prototype.update = function () {
  20238. // update arrow orientation
  20239. // pointing from light to target
  20240. this.direction.subVectors( this.light.target.position, this.light.position );
  20241. // update light cone orientation and size
  20242. this.lookAt( this.light.target.position );
  20243. var coneLength = this.light.distance ? this.light.distance : 10000;
  20244. var coneWidth = coneLength * Math.tan( this.light.angle * 0.5 ) * 2;
  20245. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  20246. // update arrow, spheres, rays and line colors to light color * light intensity
  20247. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20248. this.color.copy( this.light.color );
  20249. this.color.multiplyScalar( intensity );
  20250. this.lightSphere.material.color.copy( this.color );
  20251. this.lightRays.material.color.copy( this.color );
  20252. this.lightCone.material.color.copy( this.color );
  20253. // Only update targetSphere and targetLine if available
  20254. if ( this.targetSphere !== null ) {
  20255. this.targetSphere.material.color.copy( this.color );
  20256. this.targetLine.material.color.copy( this.color );
  20257. // update target line vertices
  20258. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  20259. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  20260. this.targetLine.geometry.computeLineDistances();
  20261. this.targetLine.geometry.verticesNeedUpdate = true;
  20262. }
  20263. };
  20264. /**
  20265. * @author alteredq / http://alteredqualia.com/
  20266. */
  20267. THREE.ImmediateRenderObject = function ( ) {
  20268. THREE.Object3D.call( this );
  20269. this.render = function ( renderCallback ) { };
  20270. };
  20271. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20272. /**
  20273. * @author mikael emtinger / http://gomo.se/
  20274. * @author alteredq / http://alteredqualia.com/
  20275. */
  20276. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20277. THREE.Object3D.call( this );
  20278. this.lensFlares = [];
  20279. this.positionScreen = new THREE.Vector3();
  20280. this.customUpdateCallback = undefined;
  20281. if( texture !== undefined ) {
  20282. this.add( texture, size, distance, blending, color );
  20283. }
  20284. };
  20285. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20286. /*
  20287. * Add: adds another flare
  20288. */
  20289. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20290. if( size === undefined ) size = -1;
  20291. if( distance === undefined ) distance = 0;
  20292. if( opacity === undefined ) opacity = 1;
  20293. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20294. if( blending === undefined ) blending = THREE.NormalBlending;
  20295. distance = Math.min( distance, Math.max( 0, distance ) );
  20296. this.lensFlares.push( { texture: texture, // THREE.Texture
  20297. size: size, // size in pixels (-1 = use texture.width)
  20298. distance: distance, // distance (0-1) from light source (0=at light source)
  20299. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20300. scale: 1, // scale
  20301. rotation: 1, // rotation
  20302. opacity: opacity, // opacity
  20303. color: color, // color
  20304. blending: blending } ); // blending
  20305. };
  20306. /*
  20307. * Update lens flares update positions on all flares based on the screen position
  20308. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20309. */
  20310. THREE.LensFlare.prototype.updateLensFlares = function () {
  20311. var f, fl = this.lensFlares.length;
  20312. var flare;
  20313. var vecX = -this.positionScreen.x * 2;
  20314. var vecY = -this.positionScreen.y * 2;
  20315. for( f = 0; f < fl; f ++ ) {
  20316. flare = this.lensFlares[ f ];
  20317. flare.x = this.positionScreen.x + vecX * flare.distance;
  20318. flare.y = this.positionScreen.y + vecY * flare.distance;
  20319. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20320. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20321. }
  20322. };
  20323. /**
  20324. * @author alteredq / http://alteredqualia.com/
  20325. */
  20326. THREE.MorphBlendMesh = function( geometry, material ) {
  20327. THREE.Mesh.call( this, geometry, material );
  20328. this.animationsMap = {};
  20329. this.animationsList = [];
  20330. // prepare default animation
  20331. // (all frames played together in 1 second)
  20332. var numFrames = this.geometry.morphTargets.length;
  20333. var name = "__default";
  20334. var startFrame = 0;
  20335. var endFrame = numFrames - 1;
  20336. var fps = numFrames / 1;
  20337. this.createAnimation( name, startFrame, endFrame, fps );
  20338. this.setAnimationWeight( name, 1 );
  20339. };
  20340. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20341. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20342. var animation = {
  20343. startFrame: start,
  20344. endFrame: end,
  20345. length: end - start + 1,
  20346. fps: fps,
  20347. duration: ( end - start ) / fps,
  20348. lastFrame: 0,
  20349. currentFrame: 0,
  20350. active: false,
  20351. time: 0,
  20352. direction: 1,
  20353. weight: 1,
  20354. directionBackwards: false,
  20355. mirroredLoop: false
  20356. };
  20357. this.animationsMap[ name ] = animation;
  20358. this.animationsList.push( animation );
  20359. };
  20360. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20361. var pattern = /([a-z]+)(\d+)/;
  20362. var firstAnimation, frameRanges = {};
  20363. var geometry = this.geometry;
  20364. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20365. var morph = geometry.morphTargets[ i ];
  20366. var chunks = morph.name.match( pattern );
  20367. if ( chunks && chunks.length > 1 ) {
  20368. var name = chunks[ 1 ];
  20369. var num = chunks[ 2 ];
  20370. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20371. var range = frameRanges[ name ];
  20372. if ( i < range.start ) range.start = i;
  20373. if ( i > range.end ) range.end = i;
  20374. if ( ! firstAnimation ) firstAnimation = name;
  20375. }
  20376. }
  20377. for ( var name in frameRanges ) {
  20378. var range = frameRanges[ name ];
  20379. this.createAnimation( name, range.start, range.end, fps );
  20380. }
  20381. this.firstAnimation = firstAnimation;
  20382. };
  20383. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20384. var animation = this.animationsMap[ name ];
  20385. if ( animation ) {
  20386. animation.direction = 1;
  20387. animation.directionBackwards = false;
  20388. }
  20389. };
  20390. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20391. var animation = this.animationsMap[ name ];
  20392. if ( animation ) {
  20393. animation.direction = -1;
  20394. animation.directionBackwards = true;
  20395. }
  20396. };
  20397. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20398. var animation = this.animationsMap[ name ];
  20399. if ( animation ) {
  20400. animation.fps = fps;
  20401. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20402. }
  20403. };
  20404. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20405. var animation = this.animationsMap[ name ];
  20406. if ( animation ) {
  20407. animation.duration = duration;
  20408. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20409. }
  20410. };
  20411. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20412. var animation = this.animationsMap[ name ];
  20413. if ( animation ) {
  20414. animation.weight = weight;
  20415. }
  20416. };
  20417. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20418. var animation = this.animationsMap[ name ];
  20419. if ( animation ) {
  20420. animation.time = time;
  20421. }
  20422. };
  20423. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20424. var time = 0;
  20425. var animation = this.animationsMap[ name ];
  20426. if ( animation ) {
  20427. time = animation.time;
  20428. }
  20429. return time;
  20430. };
  20431. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20432. var duration = -1;
  20433. var animation = this.animationsMap[ name ];
  20434. if ( animation ) {
  20435. duration = animation.duration;
  20436. }
  20437. return duration;
  20438. };
  20439. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20440. var animation = this.animationsMap[ name ];
  20441. if ( animation ) {
  20442. animation.time = 0;
  20443. animation.active = true;
  20444. } else {
  20445. console.warn( "animation[" + name + "] undefined" );
  20446. }
  20447. };
  20448. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20449. var animation = this.animationsMap[ name ];
  20450. if ( animation ) {
  20451. animation.active = false;
  20452. }
  20453. };
  20454. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20455. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20456. var animation = this.animationsList[ i ];
  20457. if ( ! animation.active ) continue;
  20458. var frameTime = animation.duration / animation.length;
  20459. animation.time += animation.direction * delta;
  20460. if ( animation.mirroredLoop ) {
  20461. if ( animation.time > animation.duration || animation.time < 0 ) {
  20462. animation.direction *= -1;
  20463. if ( animation.time > animation.duration ) {
  20464. animation.time = animation.duration;
  20465. animation.directionBackwards = true;
  20466. }
  20467. if ( animation.time < 0 ) {
  20468. animation.time = 0;
  20469. animation.directionBackwards = false;
  20470. }
  20471. }
  20472. } else {
  20473. animation.time = animation.time % animation.duration;
  20474. if ( animation.time < 0 ) animation.time += animation.duration;
  20475. }
  20476. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20477. var weight = animation.weight;
  20478. if ( keyframe !== animation.currentFrame ) {
  20479. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20480. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20481. this.morphTargetInfluences[ keyframe ] = 0;
  20482. animation.lastFrame = animation.currentFrame;
  20483. animation.currentFrame = keyframe;
  20484. }
  20485. var mix = ( animation.time % frameTime ) / frameTime;
  20486. if ( animation.directionBackwards ) mix = 1 - mix;
  20487. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  20488. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  20489. }
  20490. };
  20491. /**
  20492. * @author mikael emtinger / http://gomo.se/
  20493. * @author alteredq / http://alteredqualia.com/
  20494. */
  20495. THREE.LensFlarePlugin = function ( ) {
  20496. var _gl, _renderer, _precision, _lensFlare = {};
  20497. this.init = function ( renderer ) {
  20498. _gl = renderer.context;
  20499. _renderer = renderer;
  20500. _precision = renderer.getPrecision();
  20501. _lensFlare.vertices = new Float32Array( 8 + 8 );
  20502. _lensFlare.faces = new Uint16Array( 6 );
  20503. var i = 0;
  20504. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  20505. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  20506. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  20507. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  20508. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20509. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20510. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  20511. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  20512. i = 0;
  20513. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  20514. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  20515. // buffers
  20516. _lensFlare.vertexBuffer = _gl.createBuffer();
  20517. _lensFlare.elementBuffer = _gl.createBuffer();
  20518. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20519. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  20520. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20521. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  20522. // textures
  20523. _lensFlare.tempTexture = _gl.createTexture();
  20524. _lensFlare.occlusionTexture = _gl.createTexture();
  20525. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20526. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  20527. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20528. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20529. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20530. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20531. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20532. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _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. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  20538. _lensFlare.hasVertexTexture = false;
  20539. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  20540. } else {
  20541. _lensFlare.hasVertexTexture = true;
  20542. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  20543. }
  20544. _lensFlare.attributes = {};
  20545. _lensFlare.uniforms = {};
  20546. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  20547. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  20548. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  20549. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  20550. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  20551. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  20552. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  20553. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  20554. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  20555. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  20556. };
  20557. /*
  20558. * Render lens flares
  20559. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  20560. * reads these back and calculates occlusion.
  20561. * Then _lensFlare.update_lensFlares() is called to re-position and
  20562. * update transparency of flares. Then they are rendered.
  20563. *
  20564. */
  20565. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20566. var flares = scene.__webglFlares,
  20567. nFlares = flares.length;
  20568. if ( ! nFlares ) return;
  20569. var tempPosition = new THREE.Vector3();
  20570. var invAspect = viewportHeight / viewportWidth,
  20571. halfViewportWidth = viewportWidth * 0.5,
  20572. halfViewportHeight = viewportHeight * 0.5;
  20573. var size = 16 / viewportHeight,
  20574. scale = new THREE.Vector2( size * invAspect, size );
  20575. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  20576. screenPositionPixels = new THREE.Vector2( 1, 1 );
  20577. var uniforms = _lensFlare.uniforms,
  20578. attributes = _lensFlare.attributes;
  20579. // set _lensFlare program and reset blending
  20580. _gl.useProgram( _lensFlare.program );
  20581. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  20582. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  20583. // loop through all lens flares to update their occlusion and positions
  20584. // setup gl and common used attribs/unforms
  20585. _gl.uniform1i( uniforms.occlusionMap, 0 );
  20586. _gl.uniform1i( uniforms.map, 1 );
  20587. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20588. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  20589. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  20590. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20591. _gl.disable( _gl.CULL_FACE );
  20592. _gl.depthMask( false );
  20593. var i, j, jl, flare, sprite;
  20594. for ( i = 0; i < nFlares; i ++ ) {
  20595. size = 16 / viewportHeight;
  20596. scale.set( size * invAspect, size );
  20597. // calc object screen position
  20598. flare = flares[ i ];
  20599. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  20600. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  20601. tempPosition.applyMatrix4( camera.projectionMatrix );
  20602. // setup arrays for gl programs
  20603. screenPosition.copy( tempPosition )
  20604. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  20605. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  20606. // screen cull
  20607. if ( _lensFlare.hasVertexTexture || (
  20608. screenPositionPixels.x > 0 &&
  20609. screenPositionPixels.x < viewportWidth &&
  20610. screenPositionPixels.y > 0 &&
  20611. screenPositionPixels.y < viewportHeight ) ) {
  20612. // save current RGB to temp texture
  20613. _gl.activeTexture( _gl.TEXTURE1 );
  20614. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20615. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20616. // render pink quad
  20617. _gl.uniform1i( uniforms.renderType, 0 );
  20618. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20619. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20620. _gl.disable( _gl.BLEND );
  20621. _gl.enable( _gl.DEPTH_TEST );
  20622. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20623. // copy result to occlusionMap
  20624. _gl.activeTexture( _gl.TEXTURE0 );
  20625. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20626. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20627. // restore graphics
  20628. _gl.uniform1i( uniforms.renderType, 1 );
  20629. _gl.disable( _gl.DEPTH_TEST );
  20630. _gl.activeTexture( _gl.TEXTURE1 );
  20631. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20632. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20633. // update object positions
  20634. flare.positionScreen.copy( screenPosition )
  20635. if ( flare.customUpdateCallback ) {
  20636. flare.customUpdateCallback( flare );
  20637. } else {
  20638. flare.updateLensFlares();
  20639. }
  20640. // render flares
  20641. _gl.uniform1i( uniforms.renderType, 2 );
  20642. _gl.enable( _gl.BLEND );
  20643. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  20644. sprite = flare.lensFlares[ j ];
  20645. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  20646. screenPosition.x = sprite.x;
  20647. screenPosition.y = sprite.y;
  20648. screenPosition.z = sprite.z;
  20649. size = sprite.size * sprite.scale / viewportHeight;
  20650. scale.x = size * invAspect;
  20651. scale.y = size;
  20652. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20653. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20654. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  20655. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  20656. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  20657. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  20658. _renderer.setTexture( sprite.texture, 1 );
  20659. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20660. }
  20661. }
  20662. }
  20663. }
  20664. // restore gl
  20665. _gl.enable( _gl.CULL_FACE );
  20666. _gl.enable( _gl.DEPTH_TEST );
  20667. _gl.depthMask( true );
  20668. };
  20669. function createProgram ( shader, precision ) {
  20670. var program = _gl.createProgram();
  20671. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  20672. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  20673. var prefix = "precision " + precision + " float;\n";
  20674. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  20675. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  20676. _gl.compileShader( fragmentShader );
  20677. _gl.compileShader( vertexShader );
  20678. _gl.attachShader( program, fragmentShader );
  20679. _gl.attachShader( program, vertexShader );
  20680. _gl.linkProgram( program );
  20681. return program;
  20682. };
  20683. };
  20684. /**
  20685. * @author alteredq / http://alteredqualia.com/
  20686. */
  20687. THREE.ShadowMapPlugin = function ( ) {
  20688. var _gl,
  20689. _renderer,
  20690. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  20691. _frustum = new THREE.Frustum(),
  20692. _projScreenMatrix = new THREE.Matrix4(),
  20693. _min = new THREE.Vector3(),
  20694. _max = new THREE.Vector3();
  20695. this.init = function ( renderer ) {
  20696. _gl = renderer.context;
  20697. _renderer = renderer;
  20698. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  20699. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  20700. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  20701. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  20702. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  20703. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  20704. _depthMaterial._shadowPass = true;
  20705. _depthMaterialMorph._shadowPass = true;
  20706. _depthMaterialSkin._shadowPass = true;
  20707. _depthMaterialMorphSkin._shadowPass = true;
  20708. };
  20709. this.render = function ( scene, camera ) {
  20710. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  20711. this.update( scene, camera );
  20712. };
  20713. this.update = function ( scene, camera ) {
  20714. var i, il, j, jl, n,
  20715. shadowMap, shadowMatrix, shadowCamera,
  20716. program, buffer, material,
  20717. webglObject, object, light,
  20718. renderList,
  20719. lights = [],
  20720. k = 0,
  20721. fog = null;
  20722. // set GL state for depth map
  20723. _gl.clearColor( 1, 1, 1, 1 );
  20724. _gl.disable( _gl.BLEND );
  20725. _gl.enable( _gl.CULL_FACE );
  20726. _gl.frontFace( _gl.CCW );
  20727. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  20728. _gl.cullFace( _gl.FRONT );
  20729. } else {
  20730. _gl.cullFace( _gl.BACK );
  20731. }
  20732. _renderer.setDepthTest( true );
  20733. // preprocess lights
  20734. // - skip lights that are not casting shadows
  20735. // - create virtual lights for cascaded shadow maps
  20736. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  20737. light = scene.__lights[ i ];
  20738. if ( ! light.castShadow ) continue;
  20739. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  20740. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  20741. var virtualLight;
  20742. if ( ! light.shadowCascadeArray[ n ] ) {
  20743. virtualLight = createVirtualLight( light, n );
  20744. virtualLight.originalCamera = camera;
  20745. var gyro = new THREE.Gyroscope();
  20746. gyro.position = light.shadowCascadeOffset;
  20747. gyro.add( virtualLight );
  20748. gyro.add( virtualLight.target );
  20749. camera.add( gyro );
  20750. light.shadowCascadeArray[ n ] = virtualLight;
  20751. console.log( "Created virtualLight", virtualLight );
  20752. } else {
  20753. virtualLight = light.shadowCascadeArray[ n ];
  20754. }
  20755. updateVirtualLight( light, n );
  20756. lights[ k ] = virtualLight;
  20757. k ++;
  20758. }
  20759. } else {
  20760. lights[ k ] = light;
  20761. k ++;
  20762. }
  20763. }
  20764. // render depth map
  20765. for ( i = 0, il = lights.length; i < il; i ++ ) {
  20766. light = lights[ i ];
  20767. if ( ! light.shadowMap ) {
  20768. var shadowFilter = THREE.LinearFilter;
  20769. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  20770. shadowFilter = THREE.NearestFilter;
  20771. }
  20772. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  20773. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  20774. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  20775. light.shadowMatrix = new THREE.Matrix4();
  20776. }
  20777. if ( ! light.shadowCamera ) {
  20778. if ( light instanceof THREE.SpotLight ) {
  20779. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  20780. } else if ( light instanceof THREE.DirectionalLight ) {
  20781. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  20782. } else {
  20783. console.error( "Unsupported light type for shadow" );
  20784. continue;
  20785. }
  20786. scene.add( light.shadowCamera );
  20787. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  20788. }
  20789. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  20790. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  20791. light.shadowCamera.add( light.cameraHelper );
  20792. }
  20793. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  20794. updateShadowCamera( camera, light );
  20795. }
  20796. shadowMap = light.shadowMap;
  20797. shadowMatrix = light.shadowMatrix;
  20798. shadowCamera = light.shadowCamera;
  20799. shadowCamera.position.copy( light.matrixWorld.getPosition() );
  20800. shadowCamera.lookAt( light.target.matrixWorld.getPosition() );
  20801. shadowCamera.updateMatrixWorld();
  20802. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  20803. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  20804. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  20805. // compute shadow matrix
  20806. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  20807. 0.0, 0.5, 0.0, 0.5,
  20808. 0.0, 0.0, 0.5, 0.5,
  20809. 0.0, 0.0, 0.0, 1.0 );
  20810. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  20811. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  20812. // update camera matrices and frustum
  20813. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  20814. _frustum.setFromMatrix( _projScreenMatrix );
  20815. // render shadow map
  20816. _renderer.setRenderTarget( shadowMap );
  20817. _renderer.clear();
  20818. // set object matrices & frustum culling
  20819. renderList = scene.__webglObjects;
  20820. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20821. webglObject = renderList[ j ];
  20822. object = webglObject.object;
  20823. webglObject.render = false;
  20824. if ( object.visible && object.castShadow ) {
  20825. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  20826. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  20827. webglObject.render = true;
  20828. }
  20829. }
  20830. }
  20831. // render regular objects
  20832. var objectMaterial, useMorphing, useSkinning;
  20833. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20834. webglObject = renderList[ j ];
  20835. if ( webglObject.render ) {
  20836. object = webglObject.object;
  20837. buffer = webglObject.buffer;
  20838. // culling is overriden globally for all objects
  20839. // while rendering depth map
  20840. // need to deal with MeshFaceMaterial somehow
  20841. // in that case just use the first of material.materials for now
  20842. // (proper solution would require to break objects by materials
  20843. // similarly to regular rendering and then set corresponding
  20844. // depth materials per each chunk instead of just once per object)
  20845. objectMaterial = getObjectMaterial( object );
  20846. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  20847. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  20848. if ( object.customDepthMaterial ) {
  20849. material = object.customDepthMaterial;
  20850. } else if ( useSkinning ) {
  20851. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  20852. } else if ( useMorphing ) {
  20853. material = _depthMaterialMorph;
  20854. } else {
  20855. material = _depthMaterial;
  20856. }
  20857. if ( buffer instanceof THREE.BufferGeometry ) {
  20858. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  20859. } else {
  20860. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  20861. }
  20862. }
  20863. }
  20864. // set matrices and render immediate objects
  20865. renderList = scene.__webglObjectsImmediate;
  20866. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20867. webglObject = renderList[ j ];
  20868. object = webglObject.object;
  20869. if ( object.visible && object.castShadow ) {
  20870. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  20871. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  20872. }
  20873. }
  20874. }
  20875. // restore GL state
  20876. var clearColor = _renderer.getClearColor(),
  20877. clearAlpha = _renderer.getClearAlpha();
  20878. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  20879. _gl.enable( _gl.BLEND );
  20880. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  20881. _gl.cullFace( _gl.BACK );
  20882. }
  20883. };
  20884. function createVirtualLight( light, cascade ) {
  20885. var virtualLight = new THREE.DirectionalLight();
  20886. virtualLight.isVirtual = true;
  20887. virtualLight.onlyShadow = true;
  20888. virtualLight.castShadow = true;
  20889. virtualLight.shadowCameraNear = light.shadowCameraNear;
  20890. virtualLight.shadowCameraFar = light.shadowCameraFar;
  20891. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  20892. virtualLight.shadowCameraRight = light.shadowCameraRight;
  20893. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  20894. virtualLight.shadowCameraTop = light.shadowCameraTop;
  20895. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  20896. virtualLight.shadowDarkness = light.shadowDarkness;
  20897. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  20898. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  20899. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  20900. virtualLight.pointsWorld = [];
  20901. virtualLight.pointsFrustum = [];
  20902. var pointsWorld = virtualLight.pointsWorld,
  20903. pointsFrustum = virtualLight.pointsFrustum;
  20904. for ( var i = 0; i < 8; i ++ ) {
  20905. pointsWorld[ i ] = new THREE.Vector3();
  20906. pointsFrustum[ i ] = new THREE.Vector3();
  20907. }
  20908. var nearZ = light.shadowCascadeNearZ[ cascade ];
  20909. var farZ = light.shadowCascadeFarZ[ cascade ];
  20910. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  20911. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  20912. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  20913. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  20914. pointsFrustum[ 4 ].set( -1, -1, farZ );
  20915. pointsFrustum[ 5 ].set( 1, -1, farZ );
  20916. pointsFrustum[ 6 ].set( -1, 1, farZ );
  20917. pointsFrustum[ 7 ].set( 1, 1, farZ );
  20918. return virtualLight;
  20919. }
  20920. // Synchronize virtual light with the original light
  20921. function updateVirtualLight( light, cascade ) {
  20922. var virtualLight = light.shadowCascadeArray[ cascade ];
  20923. virtualLight.position.copy( light.position );
  20924. virtualLight.target.position.copy( light.target.position );
  20925. virtualLight.lookAt( virtualLight.target );
  20926. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  20927. virtualLight.shadowDarkness = light.shadowDarkness;
  20928. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  20929. var nearZ = light.shadowCascadeNearZ[ cascade ];
  20930. var farZ = light.shadowCascadeFarZ[ cascade ];
  20931. var pointsFrustum = virtualLight.pointsFrustum;
  20932. pointsFrustum[ 0 ].z = nearZ;
  20933. pointsFrustum[ 1 ].z = nearZ;
  20934. pointsFrustum[ 2 ].z = nearZ;
  20935. pointsFrustum[ 3 ].z = nearZ;
  20936. pointsFrustum[ 4 ].z = farZ;
  20937. pointsFrustum[ 5 ].z = farZ;
  20938. pointsFrustum[ 6 ].z = farZ;
  20939. pointsFrustum[ 7 ].z = farZ;
  20940. }
  20941. // Fit shadow camera's ortho frustum to camera frustum
  20942. function updateShadowCamera( camera, light ) {
  20943. var shadowCamera = light.shadowCamera,
  20944. pointsFrustum = light.pointsFrustum,
  20945. pointsWorld = light.pointsWorld;
  20946. _min.set( Infinity, Infinity, Infinity );
  20947. _max.set( -Infinity, -Infinity, -Infinity );
  20948. for ( var i = 0; i < 8; i ++ ) {
  20949. var p = pointsWorld[ i ];
  20950. p.copy( pointsFrustum[ i ] );
  20951. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  20952. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  20953. if ( p.x < _min.x ) _min.x = p.x;
  20954. if ( p.x > _max.x ) _max.x = p.x;
  20955. if ( p.y < _min.y ) _min.y = p.y;
  20956. if ( p.y > _max.y ) _max.y = p.y;
  20957. if ( p.z < _min.z ) _min.z = p.z;
  20958. if ( p.z > _max.z ) _max.z = p.z;
  20959. }
  20960. shadowCamera.left = _min.x;
  20961. shadowCamera.right = _max.x;
  20962. shadowCamera.top = _max.y;
  20963. shadowCamera.bottom = _min.y;
  20964. // can't really fit near/far
  20965. //shadowCamera.near = _min.z;
  20966. //shadowCamera.far = _max.z;
  20967. shadowCamera.updateProjectionMatrix();
  20968. }
  20969. // For the moment just ignore objects that have multiple materials with different animation methods
  20970. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  20971. function getObjectMaterial( object ) {
  20972. return object.material instanceof THREE.MeshFaceMaterial
  20973. ? object.material.materials[ 0 ]
  20974. : object.material;
  20975. };
  20976. };
  20977. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  20978. /**
  20979. * @author mikael emtinger / http://gomo.se/
  20980. * @author alteredq / http://alteredqualia.com/
  20981. */
  20982. THREE.SpritePlugin = function ( ) {
  20983. var _gl, _renderer, _precision, _sprite = {};
  20984. this.init = function ( renderer ) {
  20985. _gl = renderer.context;
  20986. _renderer = renderer;
  20987. _precision = renderer.getPrecision();
  20988. _sprite.vertices = new Float32Array( 8 + 8 );
  20989. _sprite.faces = new Uint16Array( 6 );
  20990. var i = 0;
  20991. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  20992. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  20993. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  20994. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  20995. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  20996. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  20997. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  20998. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  20999. i = 0;
  21000. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  21001. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  21002. _sprite.vertexBuffer = _gl.createBuffer();
  21003. _sprite.elementBuffer = _gl.createBuffer();
  21004. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21005. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  21006. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21007. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  21008. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ], _precision );
  21009. _sprite.attributes = {};
  21010. _sprite.uniforms = {};
  21011. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  21012. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  21013. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  21014. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  21015. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  21016. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  21017. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  21018. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  21019. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  21020. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  21021. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  21022. _sprite.uniforms.sizeAttenuation = _gl.getUniformLocation( _sprite.program, "sizeAttenuation" );
  21023. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  21024. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  21025. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  21026. _sprite.uniforms.fogType = _gl.getUniformLocation( _sprite.program, "fogType" );
  21027. _sprite.uniforms.fogDensity = _gl.getUniformLocation( _sprite.program, "fogDensity" );
  21028. _sprite.uniforms.fogNear = _gl.getUniformLocation( _sprite.program, "fogNear" );
  21029. _sprite.uniforms.fogFar = _gl.getUniformLocation( _sprite.program, "fogFar" );
  21030. _sprite.uniforms.fogColor = _gl.getUniformLocation( _sprite.program, "fogColor" );
  21031. _sprite.uniforms.alphaTest = _gl.getUniformLocation( _sprite.program, "alphaTest" );
  21032. };
  21033. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21034. var sprites = scene.__webglSprites,
  21035. nSprites = sprites.length;
  21036. if ( ! nSprites ) return;
  21037. var attributes = _sprite.attributes,
  21038. uniforms = _sprite.uniforms;
  21039. var invAspect = viewportHeight / viewportWidth;
  21040. var halfViewportWidth = viewportWidth * 0.5,
  21041. halfViewportHeight = viewportHeight * 0.5;
  21042. // setup gl
  21043. _gl.useProgram( _sprite.program );
  21044. _gl.enableVertexAttribArray( attributes.position );
  21045. _gl.enableVertexAttribArray( attributes.uv );
  21046. _gl.disable( _gl.CULL_FACE );
  21047. _gl.enable( _gl.BLEND );
  21048. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21049. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21050. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21051. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21052. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  21053. _gl.activeTexture( _gl.TEXTURE0 );
  21054. _gl.uniform1i( uniforms.map, 0 );
  21055. var oldFogType = 0;
  21056. var sceneFogType = 0;
  21057. var fog = scene.fog;
  21058. if ( fog ) {
  21059. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  21060. if ( fog instanceof THREE.Fog ) {
  21061. _gl.uniform1f( uniforms.fogNear, fog.near );
  21062. _gl.uniform1f( uniforms.fogFar, fog.far );
  21063. _gl.uniform1i( uniforms.fogType, 1 );
  21064. oldFogType = 1;
  21065. sceneFogType = 1;
  21066. } else if ( fog instanceof THREE.FogExp2 ) {
  21067. _gl.uniform1f( uniforms.fogDensity, fog.density );
  21068. _gl.uniform1i( uniforms.fogType, 2 );
  21069. oldFogType = 2;
  21070. sceneFogType = 2;
  21071. }
  21072. } else {
  21073. _gl.uniform1i( uniforms.fogType, 0 );
  21074. oldFogType = 0;
  21075. sceneFogType = 0;
  21076. }
  21077. // update positions and sort
  21078. var i, sprite, material, screenPosition, size, fogType, scale = [];
  21079. for( i = 0; i < nSprites; i ++ ) {
  21080. sprite = sprites[ i ];
  21081. material = sprite.material;
  21082. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21083. if ( ! material.useScreenCoordinates ) {
  21084. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  21085. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  21086. } else {
  21087. sprite.z = - sprite.position.z;
  21088. }
  21089. }
  21090. sprites.sort( painterSortStable );
  21091. // render all sprites
  21092. for( i = 0; i < nSprites; i ++ ) {
  21093. sprite = sprites[ i ];
  21094. material = sprite.material;
  21095. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21096. if ( material.map && material.map.image && material.map.image.width ) {
  21097. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  21098. if ( material.useScreenCoordinates === true ) {
  21099. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  21100. _gl.uniform3f(
  21101. uniforms.screenPosition,
  21102. ( ( sprite.position.x * _renderer.devicePixelRatio ) - halfViewportWidth ) / halfViewportWidth,
  21103. ( halfViewportHeight - ( sprite.position.y * _renderer.devicePixelRatio ) ) / halfViewportHeight,
  21104. Math.max( 0, Math.min( 1, sprite.position.z ) )
  21105. );
  21106. scale[ 0 ] = _renderer.devicePixelRatio;
  21107. scale[ 1 ] = _renderer.devicePixelRatio;
  21108. } else {
  21109. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  21110. _gl.uniform1i( uniforms.sizeAttenuation, material.sizeAttenuation ? 1 : 0 );
  21111. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  21112. scale[ 0 ] = 1;
  21113. scale[ 1 ] = 1;
  21114. }
  21115. if ( scene.fog && material.fog ) {
  21116. fogType = sceneFogType;
  21117. } else {
  21118. fogType = 0;
  21119. }
  21120. if ( oldFogType !== fogType ) {
  21121. _gl.uniform1i( uniforms.fogType, fogType );
  21122. oldFogType = fogType;
  21123. }
  21124. size = 1 / ( material.scaleByViewport ? viewportHeight : 1 );
  21125. scale[ 0 ] *= size * invAspect * sprite.scale.x
  21126. scale[ 1 ] *= size * sprite.scale.y;
  21127. _gl.uniform2f( uniforms.uvScale, material.uvScale.x, material.uvScale.y );
  21128. _gl.uniform2f( uniforms.uvOffset, material.uvOffset.x, material.uvOffset.y );
  21129. _gl.uniform2f( uniforms.alignment, material.alignment.x, material.alignment.y );
  21130. _gl.uniform1f( uniforms.opacity, material.opacity );
  21131. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  21132. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21133. _gl.uniform2fv( uniforms.scale, scale );
  21134. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  21135. _renderer.setDepthTest( material.depthTest );
  21136. _renderer.setDepthWrite( material.depthWrite );
  21137. _renderer.setTexture( material.map, 0 );
  21138. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21139. }
  21140. }
  21141. // restore gl
  21142. _gl.enable( _gl.CULL_FACE );
  21143. };
  21144. function createProgram ( shader, precision ) {
  21145. var program = _gl.createProgram();
  21146. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21147. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21148. var prefix = "precision " + precision + " float;\n";
  21149. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21150. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21151. _gl.compileShader( fragmentShader );
  21152. _gl.compileShader( vertexShader );
  21153. _gl.attachShader( program, fragmentShader );
  21154. _gl.attachShader( program, vertexShader );
  21155. _gl.linkProgram( program );
  21156. return program;
  21157. };
  21158. function painterSortStable ( a, b ) {
  21159. if ( a.z !== b.z ) {
  21160. return b.z - a.z;
  21161. } else {
  21162. return b.id - a.id;
  21163. }
  21164. };
  21165. };
  21166. /**
  21167. * @author alteredq / http://alteredqualia.com/
  21168. */
  21169. THREE.DepthPassPlugin = function ( ) {
  21170. this.enabled = false;
  21171. this.renderTarget = null;
  21172. var _gl,
  21173. _renderer,
  21174. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21175. _frustum = new THREE.Frustum(),
  21176. _projScreenMatrix = new THREE.Matrix4();
  21177. this.init = function ( renderer ) {
  21178. _gl = renderer.context;
  21179. _renderer = renderer;
  21180. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21181. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21182. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21183. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21184. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21185. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21186. _depthMaterial._shadowPass = true;
  21187. _depthMaterialMorph._shadowPass = true;
  21188. _depthMaterialSkin._shadowPass = true;
  21189. _depthMaterialMorphSkin._shadowPass = true;
  21190. };
  21191. this.render = function ( scene, camera ) {
  21192. if ( ! this.enabled ) return;
  21193. this.update( scene, camera );
  21194. };
  21195. this.update = function ( scene, camera ) {
  21196. var i, il, j, jl, n,
  21197. program, buffer, material,
  21198. webglObject, object, light,
  21199. renderList,
  21200. fog = null;
  21201. // set GL state for depth map
  21202. _gl.clearColor( 1, 1, 1, 1 );
  21203. _gl.disable( _gl.BLEND );
  21204. _renderer.setDepthTest( true );
  21205. // update scene
  21206. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21207. // update camera matrices and frustum
  21208. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21209. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  21210. _frustum.setFromMatrix( _projScreenMatrix );
  21211. // render depth map
  21212. _renderer.setRenderTarget( this.renderTarget );
  21213. _renderer.clear();
  21214. // set object matrices & frustum culling
  21215. renderList = scene.__webglObjects;
  21216. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21217. webglObject = renderList[ j ];
  21218. object = webglObject.object;
  21219. webglObject.render = false;
  21220. if ( object.visible ) {
  21221. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21222. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21223. webglObject.render = true;
  21224. }
  21225. }
  21226. }
  21227. // render regular objects
  21228. var objectMaterial, useMorphing, useSkinning;
  21229. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21230. webglObject = renderList[ j ];
  21231. if ( webglObject.render ) {
  21232. object = webglObject.object;
  21233. buffer = webglObject.buffer;
  21234. // todo: create proper depth material for particles
  21235. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  21236. objectMaterial = getObjectMaterial( object );
  21237. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  21238. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21239. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21240. if ( object.customDepthMaterial ) {
  21241. material = object.customDepthMaterial;
  21242. } else if ( useSkinning ) {
  21243. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21244. } else if ( useMorphing ) {
  21245. material = _depthMaterialMorph;
  21246. } else {
  21247. material = _depthMaterial;
  21248. }
  21249. if ( buffer instanceof THREE.BufferGeometry ) {
  21250. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21251. } else {
  21252. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21253. }
  21254. }
  21255. }
  21256. // set matrices and render immediate objects
  21257. renderList = scene.__webglObjectsImmediate;
  21258. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21259. webglObject = renderList[ j ];
  21260. object = webglObject.object;
  21261. if ( object.visible ) {
  21262. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21263. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21264. }
  21265. }
  21266. // restore GL state
  21267. var clearColor = _renderer.getClearColor(),
  21268. clearAlpha = _renderer.getClearAlpha();
  21269. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21270. _gl.enable( _gl.BLEND );
  21271. };
  21272. // For the moment just ignore objects that have multiple materials with different animation methods
  21273. // Only the first material will be taken into account for deciding which depth material to use
  21274. function getObjectMaterial( object ) {
  21275. return object.material instanceof THREE.MeshFaceMaterial
  21276. ? object.material.materials[ 0 ]
  21277. : object.material;
  21278. };
  21279. };
  21280. /**
  21281. * @author mikael emtinger / http://gomo.se/
  21282. *
  21283. */
  21284. THREE.ShaderFlares = {
  21285. 'lensFlareVertexTexture': {
  21286. vertexShader: [
  21287. "uniform lowp int renderType;",
  21288. "uniform vec3 screenPosition;",
  21289. "uniform vec2 scale;",
  21290. "uniform float rotation;",
  21291. "uniform sampler2D occlusionMap;",
  21292. "attribute vec2 position;",
  21293. "attribute vec2 uv;",
  21294. "varying vec2 vUV;",
  21295. "varying float vVisibility;",
  21296. "void main() {",
  21297. "vUV = uv;",
  21298. "vec2 pos = position;",
  21299. "if( renderType == 2 ) {",
  21300. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  21301. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  21302. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  21303. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  21304. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  21305. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  21306. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  21307. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  21308. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21309. "vVisibility = ( visibility.r / 9.0 ) *",
  21310. "( 1.0 - visibility.g / 9.0 ) *",
  21311. "( visibility.b / 9.0 ) *",
  21312. "( 1.0 - visibility.a / 9.0 );",
  21313. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21314. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21315. "}",
  21316. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21317. "}"
  21318. ].join( "\n" ),
  21319. fragmentShader: [
  21320. "uniform lowp int renderType;",
  21321. "uniform sampler2D map;",
  21322. "uniform float opacity;",
  21323. "uniform vec3 color;",
  21324. "varying vec2 vUV;",
  21325. "varying float vVisibility;",
  21326. "void main() {",
  21327. // pink square
  21328. "if( renderType == 0 ) {",
  21329. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21330. // restore
  21331. "} else if( renderType == 1 ) {",
  21332. "gl_FragColor = texture2D( map, vUV );",
  21333. // flare
  21334. "} else {",
  21335. "vec4 texture = texture2D( map, vUV );",
  21336. "texture.a *= opacity * vVisibility;",
  21337. "gl_FragColor = texture;",
  21338. "gl_FragColor.rgb *= color;",
  21339. "}",
  21340. "}"
  21341. ].join( "\n" )
  21342. },
  21343. 'lensFlare': {
  21344. vertexShader: [
  21345. "uniform lowp int renderType;",
  21346. "uniform vec3 screenPosition;",
  21347. "uniform vec2 scale;",
  21348. "uniform float rotation;",
  21349. "attribute vec2 position;",
  21350. "attribute vec2 uv;",
  21351. "varying vec2 vUV;",
  21352. "void main() {",
  21353. "vUV = uv;",
  21354. "vec2 pos = position;",
  21355. "if( renderType == 2 ) {",
  21356. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21357. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21358. "}",
  21359. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21360. "}"
  21361. ].join( "\n" ),
  21362. fragmentShader: [
  21363. "precision mediump float;",
  21364. "uniform lowp int renderType;",
  21365. "uniform sampler2D map;",
  21366. "uniform sampler2D occlusionMap;",
  21367. "uniform float opacity;",
  21368. "uniform vec3 color;",
  21369. "varying vec2 vUV;",
  21370. "void main() {",
  21371. // pink square
  21372. "if( renderType == 0 ) {",
  21373. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  21374. // restore
  21375. "} else if( renderType == 1 ) {",
  21376. "gl_FragColor = texture2D( map, vUV );",
  21377. // flare
  21378. "} else {",
  21379. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  21380. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  21381. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  21382. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  21383. "visibility = ( 1.0 - visibility / 4.0 );",
  21384. "vec4 texture = texture2D( map, vUV );",
  21385. "texture.a *= opacity * visibility;",
  21386. "gl_FragColor = texture;",
  21387. "gl_FragColor.rgb *= color;",
  21388. "}",
  21389. "}"
  21390. ].join( "\n" )
  21391. }
  21392. };
  21393. /**
  21394. * @author mikael emtinger / http://gomo.se/
  21395. * @author alteredq / http://alteredqualia.com/
  21396. *
  21397. */
  21398. THREE.ShaderSprite = {
  21399. 'sprite': {
  21400. vertexShader: [
  21401. "uniform int useScreenCoordinates;",
  21402. "uniform int sizeAttenuation;",
  21403. "uniform vec3 screenPosition;",
  21404. "uniform mat4 modelViewMatrix;",
  21405. "uniform mat4 projectionMatrix;",
  21406. "uniform float rotation;",
  21407. "uniform vec2 scale;",
  21408. "uniform vec2 alignment;",
  21409. "uniform vec2 uvOffset;",
  21410. "uniform vec2 uvScale;",
  21411. "attribute vec2 position;",
  21412. "attribute vec2 uv;",
  21413. "varying vec2 vUV;",
  21414. "void main() {",
  21415. "vUV = uvOffset + uv * uvScale;",
  21416. "vec2 alignedPosition = position + alignment;",
  21417. "vec2 rotatedPosition;",
  21418. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  21419. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  21420. "vec4 finalPosition;",
  21421. "if( useScreenCoordinates != 0 ) {",
  21422. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  21423. "} else {",
  21424. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  21425. "finalPosition.xy += rotatedPosition * ( sizeAttenuation == 1 ? 1.0 : finalPosition.z );",
  21426. "}",
  21427. "gl_Position = finalPosition;",
  21428. "}"
  21429. ].join( "\n" ),
  21430. fragmentShader: [
  21431. "uniform vec3 color;",
  21432. "uniform sampler2D map;",
  21433. "uniform float opacity;",
  21434. "uniform int fogType;",
  21435. "uniform vec3 fogColor;",
  21436. "uniform float fogDensity;",
  21437. "uniform float fogNear;",
  21438. "uniform float fogFar;",
  21439. "uniform float alphaTest;",
  21440. "varying vec2 vUV;",
  21441. "void main() {",
  21442. "vec4 texture = texture2D( map, vUV );",
  21443. "if ( texture.a < alphaTest ) discard;",
  21444. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  21445. "if ( fogType > 0 ) {",
  21446. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  21447. "float fogFactor = 0.0;",
  21448. "if ( fogType == 1 ) {",
  21449. "fogFactor = smoothstep( fogNear, fogFar, depth );",
  21450. "} else {",
  21451. "const float LOG2 = 1.442695;",
  21452. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  21453. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  21454. "}",
  21455. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  21456. "}",
  21457. "}"
  21458. ].join( "\n" )
  21459. }
  21460. };
粤ICP备19079148号