three.js 796 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. */
  5. var THREE = THREE || { REVISION: '56dev' };
  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. // based on https://github.com/documentcloud/underscore/blob/bf657be243a075b5e72acc8a83e6f12a564d8f55/underscore.js#L767
  32. THREE.extend = function ( obj, source ) {
  33. // ECMAScript5 compatibility based on: http://www.nczonline.net/blog/2012/12/11/are-your-mixins-ecmascript-5-compatible/
  34. if ( Object.keys ) {
  35. var keys = Object.keys( source );
  36. for (var i = 0, il = keys.length; i < il; i++) {
  37. var prop = keys[i];
  38. Object.defineProperty( obj, prop, Object.getOwnPropertyDescriptor( source, prop ) );
  39. }
  40. }
  41. else {
  42. var safeHasOwnProperty = {}.hasOwnProperty;
  43. for ( var prop in source ) {
  44. if ( safeHasOwnProperty.call( source, prop ) ) {
  45. obj[prop] = source[prop];
  46. }
  47. }
  48. }
  49. return obj;
  50. };
  51. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  52. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  53. // requestAnimationFrame polyfill by Erik Möller
  54. // fixes from Paul Irish and Tino Zijdel
  55. ( function () {
  56. var lastTime = 0;
  57. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  58. for ( var x = 0; x < vendors.length && !window.requestAnimationFrame; ++ x ) {
  59. window.requestAnimationFrame = window[ vendors[ x ] + 'RequestAnimationFrame' ];
  60. window.cancelAnimationFrame = window[ vendors[ x ] + 'CancelAnimationFrame' ] || window[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  61. }
  62. if ( window.requestAnimationFrame === undefined ) {
  63. window.requestAnimationFrame = function ( callback, element ) {
  64. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  65. var id = window.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  66. lastTime = currTime + timeToCall;
  67. return id;
  68. };
  69. }
  70. window.cancelAnimationFrame = window.cancelAnimationFrame || function ( id ) { window.clearTimeout( id ) };
  71. }() );
  72. // GL STATE CONSTANTS
  73. THREE.CullFaceNone = 0;
  74. THREE.CullFaceBack = 1;
  75. THREE.CullFaceFront = 2;
  76. THREE.CullFaceFrontBack = 3;
  77. THREE.FrontFaceDirectionCW = 0;
  78. THREE.FrontFaceDirectionCCW = 1;
  79. // SHADOWING TYPES
  80. THREE.BasicShadowMap = 0;
  81. THREE.PCFShadowMap = 1;
  82. THREE.PCFSoftShadowMap = 2;
  83. // MATERIAL CONSTANTS
  84. // side
  85. THREE.FrontSide = 0;
  86. THREE.BackSide = 1;
  87. THREE.DoubleSide = 2;
  88. // shading
  89. THREE.NoShading = 0;
  90. THREE.FlatShading = 1;
  91. THREE.SmoothShading = 2;
  92. // colors
  93. THREE.NoColors = 0;
  94. THREE.FaceColors = 1;
  95. THREE.VertexColors = 2;
  96. // blending modes
  97. THREE.NoBlending = 0;
  98. THREE.NormalBlending = 1;
  99. THREE.AdditiveBlending = 2;
  100. THREE.SubtractiveBlending = 3;
  101. THREE.MultiplyBlending = 4;
  102. THREE.CustomBlending = 5;
  103. // custom blending equations
  104. // (numbers start from 100 not to clash with other
  105. // mappings to OpenGL constants defined in Texture.js)
  106. THREE.AddEquation = 100;
  107. THREE.SubtractEquation = 101;
  108. THREE.ReverseSubtractEquation = 102;
  109. // custom blending destination factors
  110. THREE.ZeroFactor = 200;
  111. THREE.OneFactor = 201;
  112. THREE.SrcColorFactor = 202;
  113. THREE.OneMinusSrcColorFactor = 203;
  114. THREE.SrcAlphaFactor = 204;
  115. THREE.OneMinusSrcAlphaFactor = 205;
  116. THREE.DstAlphaFactor = 206;
  117. THREE.OneMinusDstAlphaFactor = 207;
  118. // custom blending source factors
  119. //THREE.ZeroFactor = 200;
  120. //THREE.OneFactor = 201;
  121. //THREE.SrcAlphaFactor = 204;
  122. //THREE.OneMinusSrcAlphaFactor = 205;
  123. //THREE.DstAlphaFactor = 206;
  124. //THREE.OneMinusDstAlphaFactor = 207;
  125. THREE.DstColorFactor = 208;
  126. THREE.OneMinusDstColorFactor = 209;
  127. THREE.SrcAlphaSaturateFactor = 210;
  128. // TEXTURE CONSTANTS
  129. THREE.MultiplyOperation = 0;
  130. THREE.MixOperation = 1;
  131. THREE.AddOperation = 2;
  132. // Mapping modes
  133. THREE.UVMapping = function () {};
  134. THREE.CubeReflectionMapping = function () {};
  135. THREE.CubeRefractionMapping = function () {};
  136. THREE.SphericalReflectionMapping = function () {};
  137. THREE.SphericalRefractionMapping = function () {};
  138. // Wrapping modes
  139. THREE.RepeatWrapping = 1000;
  140. THREE.ClampToEdgeWrapping = 1001;
  141. THREE.MirroredRepeatWrapping = 1002;
  142. // Filters
  143. THREE.NearestFilter = 1003;
  144. THREE.NearestMipMapNearestFilter = 1004;
  145. THREE.NearestMipMapLinearFilter = 1005;
  146. THREE.LinearFilter = 1006;
  147. THREE.LinearMipMapNearestFilter = 1007;
  148. THREE.LinearMipMapLinearFilter = 1008;
  149. // Data types
  150. THREE.UnsignedByteType = 1009;
  151. THREE.ByteType = 1010;
  152. THREE.ShortType = 1011;
  153. THREE.UnsignedShortType = 1012;
  154. THREE.IntType = 1013;
  155. THREE.UnsignedIntType = 1014;
  156. THREE.FloatType = 1015;
  157. // Pixel types
  158. //THREE.UnsignedByteType = 1009;
  159. THREE.UnsignedShort4444Type = 1016;
  160. THREE.UnsignedShort5551Type = 1017;
  161. THREE.UnsignedShort565Type = 1018;
  162. // Pixel formats
  163. THREE.AlphaFormat = 1019;
  164. THREE.RGBFormat = 1020;
  165. THREE.RGBAFormat = 1021;
  166. THREE.LuminanceFormat = 1022;
  167. THREE.LuminanceAlphaFormat = 1023;
  168. // Compressed texture formats
  169. THREE.RGB_S3TC_DXT1_Format = 2001;
  170. THREE.RGBA_S3TC_DXT1_Format = 2002;
  171. THREE.RGBA_S3TC_DXT3_Format = 2003;
  172. THREE.RGBA_S3TC_DXT5_Format = 2004;
  173. /*
  174. // Potential future PVRTC compressed texture formats
  175. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  176. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  177. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  178. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  179. */
  180. /**
  181. * @author mrdoob / http://mrdoob.com/
  182. */
  183. THREE.Color = function ( value ) {
  184. if ( value !== undefined ) this.set( value );
  185. return this;
  186. };
  187. THREE.extend( THREE.Color.prototype, {
  188. r: 1, g: 1, b: 1,
  189. set: function ( value ) {
  190. switch ( typeof value ) {
  191. case "number":
  192. this.setHex( value );
  193. break;
  194. case "string":
  195. this.setStyle( value );
  196. break;
  197. }
  198. },
  199. setHex: function ( hex ) {
  200. hex = Math.floor( hex );
  201. this.r = ( hex >> 16 & 255 ) / 255;
  202. this.g = ( hex >> 8 & 255 ) / 255;
  203. this.b = ( hex & 255 ) / 255;
  204. return this;
  205. },
  206. setRGB: function ( r, g, b ) {
  207. this.r = r;
  208. this.g = g;
  209. this.b = b;
  210. return this;
  211. },
  212. setHSV: function ( h, s, v ) {
  213. // based on MochiKit implementation by Bob Ippolito
  214. // h,s,v ranges are < 0.0 - 1.0 >
  215. var i, f, p, q, t;
  216. if ( v === 0 ) {
  217. this.r = this.g = this.b = 0;
  218. } else {
  219. i = Math.floor( h * 6 );
  220. f = ( h * 6 ) - i;
  221. p = v * ( 1 - s );
  222. q = v * ( 1 - ( s * f ) );
  223. t = v * ( 1 - ( s * ( 1 - f ) ) );
  224. if ( i === 0 ) {
  225. this.r = v;
  226. this.g = t;
  227. this.b = p;
  228. } else if ( i === 1 ) {
  229. this.r = q;
  230. this.g = v;
  231. this.b = p;
  232. } else if ( i === 2 ) {
  233. this.r = p;
  234. this.g = v;
  235. this.b = t;
  236. } else if ( i === 3 ) {
  237. this.r = p;
  238. this.g = q;
  239. this.b = v;
  240. } else if ( i === 4 ) {
  241. this.r = t;
  242. this.g = p;
  243. this.b = v;
  244. } else if ( i === 5 ) {
  245. this.r = v;
  246. this.g = p;
  247. this.b = q;
  248. }
  249. }
  250. return this;
  251. },
  252. setStyle: function ( style ) {
  253. // rgb(255,0,0)
  254. if ( /^rgb\((\d+),(\d+),(\d+)\)$/i.test( style ) ) {
  255. var color = /^rgb\((\d+),(\d+),(\d+)\)$/i.exec( style );
  256. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  257. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  258. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  259. return this;
  260. }
  261. // rgb(100%,0%,0%)
  262. if ( /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.test( style ) ) {
  263. var color = /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.exec( style );
  264. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  265. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  266. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  267. return this;
  268. }
  269. // #ff0000
  270. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  271. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  272. this.setHex( parseInt( color[ 1 ], 16 ) );
  273. return this;
  274. }
  275. // #f00
  276. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  277. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  278. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  279. return this;
  280. }
  281. // red
  282. if ( /^(\w+)$/i.test( style ) ) {
  283. this.setHex( THREE.ColorKeywords[ style ] );
  284. return this;
  285. }
  286. },
  287. copy: function ( color ) {
  288. this.r = color.r;
  289. this.g = color.g;
  290. this.b = color.b;
  291. return this;
  292. },
  293. copyGammaToLinear: function ( color ) {
  294. this.r = color.r * color.r;
  295. this.g = color.g * color.g;
  296. this.b = color.b * color.b;
  297. return this;
  298. },
  299. copyLinearToGamma: function ( color ) {
  300. this.r = Math.sqrt( color.r );
  301. this.g = Math.sqrt( color.g );
  302. this.b = Math.sqrt( color.b );
  303. return this;
  304. },
  305. convertGammaToLinear: function () {
  306. var r = this.r, g = this.g, b = this.b;
  307. this.r = r * r;
  308. this.g = g * g;
  309. this.b = b * b;
  310. return this;
  311. },
  312. convertLinearToGamma: function () {
  313. this.r = Math.sqrt( this.r );
  314. this.g = Math.sqrt( this.g );
  315. this.b = Math.sqrt( this.b );
  316. return this;
  317. },
  318. getHex: function () {
  319. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  320. },
  321. getHexString: function () {
  322. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  323. },
  324. getStyle: function () {
  325. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  326. },
  327. getHSV: function ( hsv ) {
  328. // based on MochiKit implementation by Bob Ippolito
  329. // h,s,v ranges are < 0.0 - 1.0 >
  330. var r = this.r;
  331. var g = this.g;
  332. var b = this.b;
  333. var max = Math.max( Math.max( r, g ), b );
  334. var min = Math.min( Math.min( r, g ), b );
  335. var hue;
  336. var saturation;
  337. var value = max;
  338. if ( min === max ) {
  339. hue = 0;
  340. saturation = 0;
  341. } else {
  342. var delta = ( max - min );
  343. saturation = delta / max;
  344. if ( r === max ) {
  345. hue = ( g - b ) / delta;
  346. } else if ( g === max ) {
  347. hue = 2 + ( ( b - r ) / delta );
  348. } else {
  349. hue = 4 + ( ( r - g ) / delta );
  350. }
  351. hue /= 6;
  352. if ( hue < 0 ) {
  353. hue += 1;
  354. }
  355. if ( hue > 1 ) {
  356. hue -= 1;
  357. }
  358. }
  359. if ( hsv === undefined ) {
  360. hsv = { h: 0, s: 0, v: 0 };
  361. }
  362. hsv.h = hue;
  363. hsv.s = saturation;
  364. hsv.v = value;
  365. return hsv;
  366. },
  367. add: function ( color ) {
  368. this.r += color.r;
  369. this.g += color.g;
  370. this.b += color.b;
  371. return this;
  372. },
  373. addColors: function ( color1, color2 ) {
  374. this.r = color1.r + color2.r;
  375. this.g = color1.g + color2.g;
  376. this.b = color1.b + color2.b;
  377. return this;
  378. },
  379. addScalar: function ( s ) {
  380. this.r += s;
  381. this.g += s;
  382. this.b += s;
  383. return this;
  384. },
  385. multiply: function ( color ) {
  386. this.r *= color.r;
  387. this.g *= color.g;
  388. this.b *= color.b;
  389. return this;
  390. },
  391. multiplyScalar: function ( s ) {
  392. this.r *= s;
  393. this.g *= s;
  394. this.b *= s;
  395. return this;
  396. },
  397. lerp: function ( color, alpha ) {
  398. this.r += ( color.r - this.r ) * alpha;
  399. this.g += ( color.g - this.g ) * alpha;
  400. this.b += ( color.b - this.b ) * alpha;
  401. return this;
  402. },
  403. clone: function () {
  404. return new THREE.Color().setRGB( this.r, this.g, this.b );
  405. }
  406. } );
  407. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF,
  408. "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2,
  409. "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50,
  410. "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B,
  411. "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B,
  412. "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F,
  413. "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3,
  414. "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222,
  415. "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700,
  416. "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4,
  417. "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00,
  418. "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3,
  419. "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA,
  420. "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32,
  421. "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3,
  422. "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC,
  423. "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD,
  424. "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6,
  425. "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9,
  426. "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F,
  427. "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE,
  428. "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA,
  429. "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0,
  430. "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  431. /**
  432. * @author mikael emtinger / http://gomo.se/
  433. * @author alteredq / http://alteredqualia.com/
  434. * @author WestLangley / http://github.com/WestLangley
  435. * @author bhouston / http://exocortex.com
  436. */
  437. THREE.Quaternion = function( x, y, z, w ) {
  438. this.x = x || 0;
  439. this.y = y || 0;
  440. this.z = z || 0;
  441. this.w = ( w !== undefined ) ? w : 1;
  442. };
  443. THREE.extend( THREE.Quaternion.prototype, {
  444. set: function ( x, y, z, w ) {
  445. this.x = x;
  446. this.y = y;
  447. this.z = z;
  448. this.w = w;
  449. return this;
  450. },
  451. copy: function ( q ) {
  452. this.x = q.x;
  453. this.y = q.y;
  454. this.z = q.z;
  455. this.w = q.w;
  456. return this;
  457. },
  458. setFromEuler: function ( v, order ) {
  459. // http://www.mathworks.com/matlabcentral/fileexchange/
  460. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  461. // content/SpinCalc.m
  462. var c1 = Math.cos( v.x / 2 );
  463. var c2 = Math.cos( v.y / 2 );
  464. var c3 = Math.cos( v.z / 2 );
  465. var s1 = Math.sin( v.x / 2 );
  466. var s2 = Math.sin( v.y / 2 );
  467. var s3 = Math.sin( v.z / 2 );
  468. if ( order === undefined || order === 'XYZ' ) {
  469. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  470. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  471. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  472. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  473. } else if ( order === 'YXZ' ) {
  474. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  475. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  476. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  477. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  478. } else if ( order === 'ZXY' ) {
  479. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  480. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  481. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  482. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  483. } else if ( order === 'ZYX' ) {
  484. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  485. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  486. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  487. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  488. } else if ( order === 'YZX' ) {
  489. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  490. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  491. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  492. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  493. } else if ( order === 'XZY' ) {
  494. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  495. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  496. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  497. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  498. }
  499. return this;
  500. },
  501. setFromAxisAngle: function ( axis, angle ) {
  502. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  503. // axis have to be normalized
  504. var halfAngle = angle / 2,
  505. s = Math.sin( halfAngle );
  506. this.x = axis.x * s;
  507. this.y = axis.y * s;
  508. this.z = axis.z * s;
  509. this.w = Math.cos( halfAngle );
  510. return this;
  511. },
  512. setFromRotationMatrix: function ( m ) {
  513. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  514. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  515. var te = m.elements,
  516. m11 = te[0], m12 = te[4], m13 = te[8],
  517. m21 = te[1], m22 = te[5], m23 = te[9],
  518. m31 = te[2], m32 = te[6], m33 = te[10],
  519. trace = m11 + m22 + m33,
  520. s;
  521. if ( trace > 0 ) {
  522. s = 0.5 / Math.sqrt( trace + 1.0 );
  523. this.w = 0.25 / s;
  524. this.x = ( m32 - m23 ) * s;
  525. this.y = ( m13 - m31 ) * s;
  526. this.z = ( m21 - m12 ) * s;
  527. } else if ( m11 > m22 && m11 > m33 ) {
  528. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  529. this.w = (m32 - m23 ) / s;
  530. this.x = 0.25 * s;
  531. this.y = (m12 + m21 ) / s;
  532. this.z = (m13 + m31 ) / s;
  533. } else if ( m22 > m33 ) {
  534. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  535. this.w = (m13 - m31 ) / s;
  536. this.x = (m12 + m21 ) / s;
  537. this.y = 0.25 * s;
  538. this.z = (m23 + m32 ) / s;
  539. } else {
  540. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  541. this.w = ( m21 - m12 ) / s;
  542. this.x = ( m13 + m31 ) / s;
  543. this.y = ( m23 + m32 ) / s;
  544. this.z = 0.25 * s;
  545. }
  546. return this;
  547. },
  548. inverse: function () {
  549. this.conjugate().normalize();
  550. return this;
  551. },
  552. conjugate: function () {
  553. this.x *= -1;
  554. this.y *= -1;
  555. this.z *= -1;
  556. return this;
  557. },
  558. lengthSq: function () {
  559. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  560. },
  561. length: function () {
  562. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  563. },
  564. normalize: function () {
  565. var l = this.length();
  566. if ( l === 0 ) {
  567. this.x = 0;
  568. this.y = 0;
  569. this.z = 0;
  570. this.w = 1;
  571. } else {
  572. l = 1 / l;
  573. this.x = this.x * l;
  574. this.y = this.y * l;
  575. this.z = this.z * l;
  576. this.w = this.w * l;
  577. }
  578. return this;
  579. },
  580. multiply: function ( q, p ) {
  581. if ( p !== undefined ) {
  582. console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  583. return this.multiplyQuaternions( q, p );
  584. }
  585. return this.multiplyQuaternions( this, q );
  586. },
  587. multiplyQuaternions: function ( a, b ) {
  588. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  589. var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w;
  590. var qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  591. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  592. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  593. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  594. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  595. return this;
  596. },
  597. multiplyVector3: function ( vector ) {
  598. console.warn( 'DEPRECATED: Quaternion\'s .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  599. return vector.applyQuaternion( this );
  600. },
  601. slerp: function ( qb, t ) {
  602. var x = this.x, y = this.y, z = this.z, w = this.w;
  603. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  604. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  605. if ( cosHalfTheta < 0 ) {
  606. this.w = -qb.w;
  607. this.x = -qb.x;
  608. this.y = -qb.y;
  609. this.z = -qb.z;
  610. cosHalfTheta = -cosHalfTheta;
  611. } else {
  612. this.copy( qb );
  613. }
  614. if ( cosHalfTheta >= 1.0 ) {
  615. this.w = w;
  616. this.x = x;
  617. this.y = y;
  618. this.z = z;
  619. return this;
  620. }
  621. var halfTheta = Math.acos( cosHalfTheta );
  622. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  623. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  624. this.w = 0.5 * ( w + this.w );
  625. this.x = 0.5 * ( x + this.x );
  626. this.y = 0.5 * ( y + this.y );
  627. this.z = 0.5 * ( z + this.z );
  628. return this;
  629. }
  630. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  631. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  632. this.w = ( w * ratioA + this.w * ratioB );
  633. this.x = ( x * ratioA + this.x * ratioB );
  634. this.y = ( y * ratioA + this.y * ratioB );
  635. this.z = ( z * ratioA + this.z * ratioB );
  636. return this;
  637. },
  638. equals: function ( v ) {
  639. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  640. },
  641. clone: function () {
  642. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  643. }
  644. } );
  645. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  646. return qm.copy( qa ).slerp( qb, t );
  647. }
  648. /**
  649. * @author mrdoob / http://mrdoob.com/
  650. * @author philogb / http://blog.thejit.org/
  651. * @author egraether / http://egraether.com/
  652. * @author zz85 / http://www.lab4games.net/zz85/blog
  653. */
  654. THREE.Vector2 = function ( x, y ) {
  655. this.x = x || 0;
  656. this.y = y || 0;
  657. };
  658. THREE.extend( THREE.Vector2.prototype, {
  659. set: function ( x, y ) {
  660. this.x = x;
  661. this.y = y;
  662. return this;
  663. },
  664. setX: function ( x ) {
  665. this.x = x;
  666. return this;
  667. },
  668. setY: function ( y ) {
  669. this.y = y;
  670. return this;
  671. },
  672. setComponent: function ( index, value ) {
  673. switch ( index ) {
  674. case 0: this.x = value; break;
  675. case 1: this.y = value; break;
  676. default: throw new Error( "index is out of range: " + index );
  677. }
  678. },
  679. getComponent: function ( index ) {
  680. switch ( index ) {
  681. case 0: return this.x;
  682. case 1: return this.y;
  683. default: throw new Error( "index is out of range: " + index );
  684. }
  685. },
  686. copy: function ( v ) {
  687. this.x = v.x;
  688. this.y = v.y;
  689. return this;
  690. },
  691. add: function ( v, w ) {
  692. if ( w !== undefined ) {
  693. console.warn( 'DEPRECATED: Vector2\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  694. return this.addVectors( v, w );
  695. }
  696. this.x += v.x;
  697. this.y += v.y;
  698. return this;
  699. },
  700. addVectors: function ( a, b ) {
  701. this.x = a.x + b.x;
  702. this.y = a.y + b.y;
  703. return this;
  704. },
  705. addScalar: function ( s ) {
  706. this.x += s;
  707. this.y += s;
  708. return this;
  709. },
  710. sub: function ( v, w ) {
  711. if ( w !== undefined ) {
  712. console.warn( 'DEPRECATED: Vector2\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  713. return this.subVectors( v, w );
  714. }
  715. this.x -= v.x;
  716. this.y -= v.y;
  717. return this;
  718. },
  719. subVectors: function ( a, b ) {
  720. this.x = a.x - b.x;
  721. this.y = a.y - b.y;
  722. return this;
  723. },
  724. multiplyScalar: function ( s ) {
  725. this.x *= s;
  726. this.y *= s;
  727. return this;
  728. },
  729. divideScalar: function ( s ) {
  730. if ( s !== 0 ) {
  731. this.x /= s;
  732. this.y /= s;
  733. } else {
  734. this.set( 0, 0 );
  735. }
  736. return this;
  737. },
  738. min: function ( v ) {
  739. if ( this.x > v.x ) {
  740. this.x = v.x;
  741. }
  742. if ( this.y > v.y ) {
  743. this.y = v.y;
  744. }
  745. return this;
  746. },
  747. max: function ( v ) {
  748. if ( this.x < v.x ) {
  749. this.x = v.x;
  750. }
  751. if ( this.y < v.y ) {
  752. this.y = v.y;
  753. }
  754. return this;
  755. },
  756. clamp: function ( min, max ) {
  757. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  758. if ( this.x < min.x ) {
  759. this.x = min.x;
  760. } else if ( this.x > max.x ) {
  761. this.x = max.x;
  762. }
  763. if ( this.y < min.y ) {
  764. this.y = min.y;
  765. } else if ( this.y > max.y ) {
  766. this.y = max.y;
  767. }
  768. return this;
  769. },
  770. negate: function() {
  771. return this.multiplyScalar( - 1 );
  772. },
  773. dot: function ( v ) {
  774. return this.x * v.x + this.y * v.y;
  775. },
  776. lengthSq: function () {
  777. return this.x * this.x + this.y * this.y;
  778. },
  779. length: function () {
  780. return Math.sqrt( this.x * this.x + this.y * this.y );
  781. },
  782. normalize: function () {
  783. return this.divideScalar( this.length() );
  784. },
  785. distanceTo: function ( v ) {
  786. return Math.sqrt( this.distanceToSquared( v ) );
  787. },
  788. distanceToSquared: function ( v ) {
  789. var dx = this.x - v.x, dy = this.y - v.y;
  790. return dx * dx + dy * dy;
  791. },
  792. setLength: function ( l ) {
  793. var oldLength = this.length();
  794. if ( oldLength !== 0 && l !== oldLength ) {
  795. this.multiplyScalar( l / oldLength );
  796. }
  797. return this;
  798. },
  799. lerp: function ( v, alpha ) {
  800. this.x += ( v.x - this.x ) * alpha;
  801. this.y += ( v.y - this.y ) * alpha;
  802. return this;
  803. },
  804. equals: function( v ) {
  805. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  806. },
  807. toArray: function () {
  808. return [ this.x, this.y ];
  809. },
  810. clone: function () {
  811. return new THREE.Vector2( this.x, this.y );
  812. }
  813. } );
  814. /**
  815. * @author mrdoob / http://mrdoob.com/
  816. * @author *kile / http://kile.stravaganza.org/
  817. * @author philogb / http://blog.thejit.org/
  818. * @author mikael emtinger / http://gomo.se/
  819. * @author egraether / http://egraether.com/
  820. * @author WestLangley / http://github.com/WestLangley
  821. */
  822. THREE.Vector3 = function ( x, y, z ) {
  823. this.x = x || 0;
  824. this.y = y || 0;
  825. this.z = z || 0;
  826. };
  827. THREE.extend( THREE.Vector3.prototype, {
  828. set: function ( x, y, z ) {
  829. this.x = x;
  830. this.y = y;
  831. this.z = z;
  832. return this;
  833. },
  834. setX: function ( x ) {
  835. this.x = x;
  836. return this;
  837. },
  838. setY: function ( y ) {
  839. this.y = y;
  840. return this;
  841. },
  842. setZ: function ( z ) {
  843. this.z = z;
  844. return this;
  845. },
  846. setComponent: function ( index, value ) {
  847. switch ( index ) {
  848. case 0: this.x = value; break;
  849. case 1: this.y = value; break;
  850. case 2: this.z = value; break;
  851. default: throw new Error( "index is out of range: " + index );
  852. }
  853. },
  854. getComponent: function ( index ) {
  855. switch ( index ) {
  856. case 0: return this.x;
  857. case 1: return this.y;
  858. case 2: return this.z;
  859. default: throw new Error( "index is out of range: " + index );
  860. }
  861. },
  862. copy: function ( v ) {
  863. this.x = v.x;
  864. this.y = v.y;
  865. this.z = v.z;
  866. return this;
  867. },
  868. add: function ( v, w ) {
  869. if ( w !== undefined ) {
  870. console.warn( 'DEPRECATED: Vector3\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  871. return this.addVectors( v, w );
  872. }
  873. this.x += v.x;
  874. this.y += v.y;
  875. this.z += v.z;
  876. return this;
  877. },
  878. addScalar: function ( s ) {
  879. this.x += s;
  880. this.y += s;
  881. this.z += s;
  882. return this;
  883. },
  884. addVectors: function ( a, b ) {
  885. this.x = a.x + b.x;
  886. this.y = a.y + b.y;
  887. this.z = a.z + b.z;
  888. return this;
  889. },
  890. sub: function ( v, w ) {
  891. if ( w !== undefined ) {
  892. console.warn( 'DEPRECATED: Vector3\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  893. return this.subVectors( v, w );
  894. }
  895. this.x -= v.x;
  896. this.y -= v.y;
  897. this.z -= v.z;
  898. return this;
  899. },
  900. subVectors: function ( a, b ) {
  901. this.x = a.x - b.x;
  902. this.y = a.y - b.y;
  903. this.z = a.z - b.z;
  904. return this;
  905. },
  906. multiply: function ( v, w ) {
  907. if ( w !== undefined ) {
  908. console.warn( 'DEPRECATED: Vector3\'s .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  909. return this.multiplyVectors( v, w );
  910. }
  911. this.x *= v.x;
  912. this.y *= v.y;
  913. this.z *= v.z;
  914. return this;
  915. },
  916. multiplyScalar: function ( s ) {
  917. this.x *= s;
  918. this.y *= s;
  919. this.z *= s;
  920. return this;
  921. },
  922. multiplyVectors: function ( a, b ) {
  923. this.x = a.x * b.x;
  924. this.y = a.y * b.y;
  925. this.z = a.z * b.z;
  926. return this;
  927. },
  928. applyMatrix3: function ( m ) {
  929. var x = this.x;
  930. var y = this.y;
  931. var z = this.z;
  932. var e = m.elements;
  933. this.x = e[0] * x + e[3] * y + e[6] * z;
  934. this.y = e[1] * x + e[4] * y + e[7] * z;
  935. this.z = e[2] * x + e[5] * y + e[8] * z;
  936. return this;
  937. },
  938. applyMatrix4: function ( m ) {
  939. // input: THREE.Matrix4 affine matrix
  940. var x = this.x, y = this.y, z = this.z;
  941. var e = m.elements;
  942. this.x = e[0] * x + e[4] * y + e[8] * z + e[12];
  943. this.y = e[1] * x + e[5] * y + e[9] * z + e[13];
  944. this.z = e[2] * x + e[6] * y + e[10] * z + e[14];
  945. return this;
  946. },
  947. applyProjection: function ( m ) {
  948. // input: THREE.Matrix4 projection matrix
  949. var x = this.x, y = this.y, z = this.z;
  950. var e = m.elements;
  951. var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] ); // perspective divide
  952. this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
  953. this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
  954. this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
  955. return this;
  956. },
  957. applyQuaternion: function ( q ) {
  958. var x = this.x;
  959. var y = this.y;
  960. var z = this.z;
  961. var qx = q.x;
  962. var qy = q.y;
  963. var qz = q.z;
  964. var qw = q.w;
  965. // calculate quat * vector
  966. var ix = qw * x + qy * z - qz * y;
  967. var iy = qw * y + qz * x - qx * z;
  968. var iz = qw * z + qx * y - qy * x;
  969. var iw = -qx * x - qy * y - qz * z;
  970. // calculate result * inverse quat
  971. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  972. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  973. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  974. return this;
  975. },
  976. applyEuler: function () {
  977. var q1 = new THREE.Quaternion();
  978. return function ( v, eulerOrder ) {
  979. var quaternion = q1.setFromEuler( v, eulerOrder );
  980. this.applyQuaternion( quaternion );
  981. return this;
  982. };
  983. }(),
  984. applyAxisAngle: function () {
  985. var q1 = new THREE.Quaternion();
  986. return function ( axis, angle ) {
  987. var quaternion = q1.setFromAxisAngle( axis, angle );
  988. this.applyQuaternion( quaternion );
  989. return this;
  990. };
  991. }(),
  992. transformDirection: function ( m ) {
  993. // input: THREE.Matrix4 affine matrix
  994. // vector interpreted as a direction
  995. var x = this.x, y = this.y, z = this.z;
  996. var e = m.elements;
  997. this.x = e[0] * x + e[4] * y + e[8] * z;
  998. this.y = e[1] * x + e[5] * y + e[9] * z;
  999. this.z = e[2] * x + e[6] * y + e[10] * z;
  1000. this.normalize();
  1001. return this;
  1002. },
  1003. divide: function ( v ) {
  1004. this.x /= v.x;
  1005. this.y /= v.y;
  1006. this.z /= v.z;
  1007. return this;
  1008. },
  1009. divideScalar: function ( s ) {
  1010. if ( s !== 0 ) {
  1011. this.x /= s;
  1012. this.y /= s;
  1013. this.z /= s;
  1014. } else {
  1015. this.x = 0;
  1016. this.y = 0;
  1017. this.z = 0;
  1018. }
  1019. return this;
  1020. },
  1021. min: function ( v ) {
  1022. if ( this.x > v.x ) {
  1023. this.x = v.x;
  1024. }
  1025. if ( this.y > v.y ) {
  1026. this.y = v.y;
  1027. }
  1028. if ( this.z > v.z ) {
  1029. this.z = v.z;
  1030. }
  1031. return this;
  1032. },
  1033. max: function ( v ) {
  1034. if ( this.x < v.x ) {
  1035. this.x = v.x;
  1036. }
  1037. if ( this.y < v.y ) {
  1038. this.y = v.y;
  1039. }
  1040. if ( this.z < v.z ) {
  1041. this.z = v.z;
  1042. }
  1043. return this;
  1044. },
  1045. clamp: function ( min, max ) {
  1046. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1047. if ( this.x < min.x ) {
  1048. this.x = min.x;
  1049. } else if ( this.x > max.x ) {
  1050. this.x = max.x;
  1051. }
  1052. if ( this.y < min.y ) {
  1053. this.y = min.y;
  1054. } else if ( this.y > max.y ) {
  1055. this.y = max.y;
  1056. }
  1057. if ( this.z < min.z ) {
  1058. this.z = min.z;
  1059. } else if ( this.z > max.z ) {
  1060. this.z = max.z;
  1061. }
  1062. return this;
  1063. },
  1064. negate: function () {
  1065. return this.multiplyScalar( - 1 );
  1066. },
  1067. dot: function ( v ) {
  1068. return this.x * v.x + this.y * v.y + this.z * v.z;
  1069. },
  1070. lengthSq: function () {
  1071. return this.x * this.x + this.y * this.y + this.z * this.z;
  1072. },
  1073. length: function () {
  1074. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1075. },
  1076. lengthManhattan: function () {
  1077. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1078. },
  1079. normalize: function () {
  1080. return this.divideScalar( this.length() );
  1081. },
  1082. setLength: function ( l ) {
  1083. var oldLength = this.length();
  1084. if ( oldLength !== 0 && l !== oldLength ) {
  1085. this.multiplyScalar( l / oldLength );
  1086. }
  1087. return this;
  1088. },
  1089. lerp: function ( v, alpha ) {
  1090. this.x += ( v.x - this.x ) * alpha;
  1091. this.y += ( v.y - this.y ) * alpha;
  1092. this.z += ( v.z - this.z ) * alpha;
  1093. return this;
  1094. },
  1095. cross: function ( v, w ) {
  1096. if ( w !== undefined ) {
  1097. console.warn( 'DEPRECATED: Vector3\'s .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1098. return this.crossVectors( v, w );
  1099. }
  1100. var x = this.x, y = this.y, z = this.z;
  1101. this.x = y * v.z - z * v.y;
  1102. this.y = z * v.x - x * v.z;
  1103. this.z = x * v.y - y * v.x;
  1104. return this;
  1105. },
  1106. crossVectors: function ( a, b ) {
  1107. this.x = a.y * b.z - a.z * b.y;
  1108. this.y = a.z * b.x - a.x * b.z;
  1109. this.z = a.x * b.y - a.y * b.x;
  1110. return this;
  1111. },
  1112. projectOnVector: function () {
  1113. var v1 = new THREE.Vector3();
  1114. return function( vector ) {
  1115. v1.copy( vector ).normalize();
  1116. var d = this.dot( v1 );
  1117. return this.copy( v1 ).multiplyScalar( d );
  1118. };
  1119. }(),
  1120. projectOnPlane: function () {
  1121. var v1 = new THREE.Vector3();
  1122. return function( planeNormal ) {
  1123. v1.copy( this ).projectOnVector( planeNormal );
  1124. return this.sub( v1 );
  1125. }
  1126. }(),
  1127. reflect: function () {
  1128. var v1 = new THREE.Vector3();
  1129. return function ( vector ) {
  1130. v1.copy( this ).projectOnVector( vector ).multiplyScalar( 2 );
  1131. return this.subVectors( v1, this );
  1132. }
  1133. }(),
  1134. angleTo: function ( v ) {
  1135. return Math.acos( this.dot( v ) / this.length() / v.length() );
  1136. },
  1137. distanceTo: function ( v ) {
  1138. return Math.sqrt( this.distanceToSquared( v ) );
  1139. },
  1140. distanceToSquared: function ( v ) {
  1141. var dx = this.x - v.x;
  1142. var dy = this.y - v.y;
  1143. var dz = this.z - v.z;
  1144. return dx * dx + dy * dy + dz * dz;
  1145. },
  1146. getPositionFromMatrix: function ( m ) {
  1147. this.x = m.elements[12];
  1148. this.y = m.elements[13];
  1149. this.z = m.elements[14];
  1150. return this;
  1151. },
  1152. setEulerFromRotationMatrix: function ( m, order ) {
  1153. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1154. // clamp, to handle numerical problems
  1155. function clamp( x ) {
  1156. return Math.min( Math.max( x, -1 ), 1 );
  1157. }
  1158. var te = m.elements;
  1159. var m11 = te[0], m12 = te[4], m13 = te[8];
  1160. var m21 = te[1], m22 = te[5], m23 = te[9];
  1161. var m31 = te[2], m32 = te[6], m33 = te[10];
  1162. if ( order === undefined || order === 'XYZ' ) {
  1163. this.y = Math.asin( clamp( m13 ) );
  1164. if ( Math.abs( m13 ) < 0.99999 ) {
  1165. this.x = Math.atan2( - m23, m33 );
  1166. this.z = Math.atan2( - m12, m11 );
  1167. } else {
  1168. this.x = Math.atan2( m32, m22 );
  1169. this.z = 0;
  1170. }
  1171. } else if ( order === 'YXZ' ) {
  1172. this.x = Math.asin( - clamp( m23 ) );
  1173. if ( Math.abs( m23 ) < 0.99999 ) {
  1174. this.y = Math.atan2( m13, m33 );
  1175. this.z = Math.atan2( m21, m22 );
  1176. } else {
  1177. this.y = Math.atan2( - m31, m11 );
  1178. this.z = 0;
  1179. }
  1180. } else if ( order === 'ZXY' ) {
  1181. this.x = Math.asin( clamp( m32 ) );
  1182. if ( Math.abs( m32 ) < 0.99999 ) {
  1183. this.y = Math.atan2( - m31, m33 );
  1184. this.z = Math.atan2( - m12, m22 );
  1185. } else {
  1186. this.y = 0;
  1187. this.z = Math.atan2( m21, m11 );
  1188. }
  1189. } else if ( order === 'ZYX' ) {
  1190. this.y = Math.asin( - clamp( m31 ) );
  1191. if ( Math.abs( m31 ) < 0.99999 ) {
  1192. this.x = Math.atan2( m32, m33 );
  1193. this.z = Math.atan2( m21, m11 );
  1194. } else {
  1195. this.x = 0;
  1196. this.z = Math.atan2( - m12, m22 );
  1197. }
  1198. } else if ( order === 'YZX' ) {
  1199. this.z = Math.asin( clamp( m21 ) );
  1200. if ( Math.abs( m21 ) < 0.99999 ) {
  1201. this.x = Math.atan2( - m23, m22 );
  1202. this.y = Math.atan2( - m31, m11 );
  1203. } else {
  1204. this.x = 0;
  1205. this.y = Math.atan2( m13, m33 );
  1206. }
  1207. } else if ( order === 'XZY' ) {
  1208. this.z = Math.asin( - clamp( m12 ) );
  1209. if ( Math.abs( m12 ) < 0.99999 ) {
  1210. this.x = Math.atan2( m32, m22 );
  1211. this.y = Math.atan2( m13, m11 );
  1212. } else {
  1213. this.x = Math.atan2( - m23, m33 );
  1214. this.y = 0;
  1215. }
  1216. }
  1217. return this;
  1218. },
  1219. setEulerFromQuaternion: function ( q, order ) {
  1220. // q is assumed to be normalized
  1221. // clamp, to handle numerical problems
  1222. function clamp( x ) {
  1223. return Math.min( Math.max( x, -1 ), 1 );
  1224. }
  1225. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  1226. var sqx = q.x * q.x;
  1227. var sqy = q.y * q.y;
  1228. var sqz = q.z * q.z;
  1229. var sqw = q.w * q.w;
  1230. if ( order === undefined || order === 'XYZ' ) {
  1231. this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  1232. this.y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  1233. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  1234. } else if ( order === 'YXZ' ) {
  1235. this.x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  1236. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  1237. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  1238. } else if ( order === 'ZXY' ) {
  1239. this.x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  1240. this.y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  1241. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  1242. } else if ( order === 'ZYX' ) {
  1243. this.x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  1244. this.y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  1245. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  1246. } else if ( order === 'YZX' ) {
  1247. this.x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  1248. this.y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  1249. this.z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  1250. } else if ( order === 'XZY' ) {
  1251. this.x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  1252. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  1253. this.z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  1254. }
  1255. return this;
  1256. },
  1257. getScaleFromMatrix: function ( m ) {
  1258. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  1259. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  1260. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  1261. this.x = sx;
  1262. this.y = sy;
  1263. this.z = sz;
  1264. return this;
  1265. },
  1266. equals: function ( v ) {
  1267. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1268. },
  1269. toArray: function () {
  1270. return [ this.x, this.y, this.z ];
  1271. },
  1272. clone: function () {
  1273. return new THREE.Vector3( this.x, this.y, this.z );
  1274. }
  1275. } );
  1276. /**
  1277. * @author supereggbert / http://www.paulbrunt.co.uk/
  1278. * @author philogb / http://blog.thejit.org/
  1279. * @author mikael emtinger / http://gomo.se/
  1280. * @author egraether / http://egraether.com/
  1281. * @author WestLangley / http://github.com/WestLangley
  1282. */
  1283. THREE.Vector4 = function ( x, y, z, w ) {
  1284. this.x = x || 0;
  1285. this.y = y || 0;
  1286. this.z = z || 0;
  1287. this.w = ( w !== undefined ) ? w : 1;
  1288. };
  1289. THREE.extend( THREE.Vector4.prototype, {
  1290. set: function ( x, y, z, w ) {
  1291. this.x = x;
  1292. this.y = y;
  1293. this.z = z;
  1294. this.w = w;
  1295. return this;
  1296. },
  1297. setX: function ( x ) {
  1298. this.x = x;
  1299. return this;
  1300. },
  1301. setY: function ( y ) {
  1302. this.y = y;
  1303. return this;
  1304. },
  1305. setZ: function ( z ) {
  1306. this.z = z;
  1307. return this;
  1308. },
  1309. setW: function ( w ) {
  1310. this.w = w;
  1311. return this;
  1312. },
  1313. setComponent: function ( index, value ) {
  1314. switch ( index ) {
  1315. case 0: this.x = value; break;
  1316. case 1: this.y = value; break;
  1317. case 2: this.z = value; break;
  1318. case 3: this.w = value; break;
  1319. default: throw new Error( "index is out of range: " + index );
  1320. }
  1321. },
  1322. getComponent: function ( index ) {
  1323. switch ( index ) {
  1324. case 0: return this.x;
  1325. case 1: return this.y;
  1326. case 2: return this.z;
  1327. case 3: return this.w;
  1328. default: throw new Error( "index is out of range: " + index );
  1329. }
  1330. },
  1331. copy: function ( v ) {
  1332. this.x = v.x;
  1333. this.y = v.y;
  1334. this.z = v.z;
  1335. this.w = ( v.w !== undefined ) ? v.w : 1;
  1336. return this;
  1337. },
  1338. add: function ( v, w ) {
  1339. if ( w !== undefined ) {
  1340. console.warn( 'DEPRECATED: Vector4\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1341. return this.addVectors( v, w );
  1342. }
  1343. this.x += v.x;
  1344. this.y += v.y;
  1345. this.z += v.z;
  1346. this.w += v.w;
  1347. return this;
  1348. },
  1349. addScalar: function ( s ) {
  1350. this.x += s;
  1351. this.y += s;
  1352. this.z += s;
  1353. this.w += s;
  1354. return this;
  1355. },
  1356. addVectors: function ( a, b ) {
  1357. this.x = a.x + b.x;
  1358. this.y = a.y + b.y;
  1359. this.z = a.z + b.z;
  1360. this.w = a.w + b.w;
  1361. return this;
  1362. },
  1363. sub: function ( v, w ) {
  1364. if ( w !== undefined ) {
  1365. console.warn( 'DEPRECATED: Vector4\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1366. return this.subVectors( v, w );
  1367. }
  1368. this.x -= v.x;
  1369. this.y -= v.y;
  1370. this.z -= v.z;
  1371. this.w -= v.w;
  1372. return this;
  1373. },
  1374. subVectors: function ( a, b ) {
  1375. this.x = a.x - b.x;
  1376. this.y = a.y - b.y;
  1377. this.z = a.z - b.z;
  1378. this.w = a.w - b.w;
  1379. return this;
  1380. },
  1381. multiplyScalar: function ( s ) {
  1382. this.x *= s;
  1383. this.y *= s;
  1384. this.z *= s;
  1385. this.w *= s;
  1386. return this;
  1387. },
  1388. applyMatrix4: function ( m ) {
  1389. var x = this.x;
  1390. var y = this.y;
  1391. var z = this.z;
  1392. var w = this.w;
  1393. var e = m.elements;
  1394. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1395. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1396. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1397. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1398. return this;
  1399. },
  1400. divideScalar: function ( s ) {
  1401. if ( s !== 0 ) {
  1402. this.x /= s;
  1403. this.y /= s;
  1404. this.z /= s;
  1405. this.w /= s;
  1406. } else {
  1407. this.x = 0;
  1408. this.y = 0;
  1409. this.z = 0;
  1410. this.w = 1;
  1411. }
  1412. return this;
  1413. },
  1414. setAxisAngleFromQuaternion: function ( q ) {
  1415. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1416. // q is assumed to be normalized
  1417. this.w = 2 * Math.acos( q.w );
  1418. var s = Math.sqrt( 1 - q.w * q.w );
  1419. if ( s < 0.0001 ) {
  1420. this.x = 1;
  1421. this.y = 0;
  1422. this.z = 0;
  1423. } else {
  1424. this.x = q.x / s;
  1425. this.y = q.y / s;
  1426. this.z = q.z / s;
  1427. }
  1428. return this;
  1429. },
  1430. setAxisAngleFromRotationMatrix: function ( m ) {
  1431. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1432. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1433. var angle, x, y, z, // variables for result
  1434. epsilon = 0.01, // margin to allow for rounding errors
  1435. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1436. te = m.elements,
  1437. m11 = te[0], m12 = te[4], m13 = te[8],
  1438. m21 = te[1], m22 = te[5], m23 = te[9],
  1439. m31 = te[2], m32 = te[6], m33 = te[10];
  1440. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1441. && ( Math.abs( m13 - m31 ) < epsilon )
  1442. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1443. // singularity found
  1444. // first check for identity matrix which must have +1 for all terms
  1445. // in leading diagonal and zero in other terms
  1446. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1447. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1448. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1449. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1450. // this singularity is identity matrix so angle = 0
  1451. this.set( 1, 0, 0, 0 );
  1452. return this; // zero angle, arbitrary axis
  1453. }
  1454. // otherwise this singularity is angle = 180
  1455. angle = Math.PI;
  1456. var xx = ( m11 + 1 ) / 2;
  1457. var yy = ( m22 + 1 ) / 2;
  1458. var zz = ( m33 + 1 ) / 2;
  1459. var xy = ( m12 + m21 ) / 4;
  1460. var xz = ( m13 + m31 ) / 4;
  1461. var yz = ( m23 + m32 ) / 4;
  1462. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1463. if ( xx < epsilon ) {
  1464. x = 0;
  1465. y = 0.707106781;
  1466. z = 0.707106781;
  1467. } else {
  1468. x = Math.sqrt( xx );
  1469. y = xy / x;
  1470. z = xz / x;
  1471. }
  1472. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1473. if ( yy < epsilon ) {
  1474. x = 0.707106781;
  1475. y = 0;
  1476. z = 0.707106781;
  1477. } else {
  1478. y = Math.sqrt( yy );
  1479. x = xy / y;
  1480. z = yz / y;
  1481. }
  1482. } else { // m33 is the largest diagonal term so base result on this
  1483. if ( zz < epsilon ) {
  1484. x = 0.707106781;
  1485. y = 0.707106781;
  1486. z = 0;
  1487. } else {
  1488. z = Math.sqrt( zz );
  1489. x = xz / z;
  1490. y = yz / z;
  1491. }
  1492. }
  1493. this.set( x, y, z, angle );
  1494. return this; // return 180 deg rotation
  1495. }
  1496. // as we have reached here there are no singularities so we can handle normally
  1497. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1498. + ( m13 - m31 ) * ( m13 - m31 )
  1499. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1500. if ( Math.abs( s ) < 0.001 ) s = 1;
  1501. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1502. // caught by singularity test above, but I've left it in just in case
  1503. this.x = ( m32 - m23 ) / s;
  1504. this.y = ( m13 - m31 ) / s;
  1505. this.z = ( m21 - m12 ) / s;
  1506. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1507. return this;
  1508. },
  1509. min: function ( v ) {
  1510. if ( this.x > v.x ) {
  1511. this.x = v.x;
  1512. }
  1513. if ( this.y > v.y ) {
  1514. this.y = v.y;
  1515. }
  1516. if ( this.z > v.z ) {
  1517. this.z = v.z;
  1518. }
  1519. if ( this.w > v.w ) {
  1520. this.w = v.w;
  1521. }
  1522. return this;
  1523. },
  1524. max: function ( v ) {
  1525. if ( this.x < v.x ) {
  1526. this.x = v.x;
  1527. }
  1528. if ( this.y < v.y ) {
  1529. this.y = v.y;
  1530. }
  1531. if ( this.z < v.z ) {
  1532. this.z = v.z;
  1533. }
  1534. if ( this.w < v.w ) {
  1535. this.w = v.w;
  1536. }
  1537. return this;
  1538. },
  1539. clamp: function ( min, max ) {
  1540. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1541. if ( this.x < min.x ) {
  1542. this.x = min.x;
  1543. } else if ( this.x > max.x ) {
  1544. this.x = max.x;
  1545. }
  1546. if ( this.y < min.y ) {
  1547. this.y = min.y;
  1548. } else if ( this.y > max.y ) {
  1549. this.y = max.y;
  1550. }
  1551. if ( this.z < min.z ) {
  1552. this.z = min.z;
  1553. } else if ( this.z > max.z ) {
  1554. this.z = max.z;
  1555. }
  1556. if ( this.w < min.w ) {
  1557. this.w = min.w;
  1558. } else if ( this.w > max.w ) {
  1559. this.w = max.w;
  1560. }
  1561. return this;
  1562. },
  1563. negate: function() {
  1564. return this.multiplyScalar( -1 );
  1565. },
  1566. dot: function ( v ) {
  1567. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1568. },
  1569. lengthSq: function () {
  1570. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1571. },
  1572. length: function () {
  1573. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1574. },
  1575. lengthManhattan: function () {
  1576. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1577. },
  1578. normalize: function () {
  1579. return this.divideScalar( this.length() );
  1580. },
  1581. setLength: function ( l ) {
  1582. var oldLength = this.length();
  1583. if ( oldLength !== 0 && l !== oldLength ) {
  1584. this.multiplyScalar( l / oldLength );
  1585. }
  1586. return this;
  1587. },
  1588. lerp: function ( v, alpha ) {
  1589. this.x += ( v.x - this.x ) * alpha;
  1590. this.y += ( v.y - this.y ) * alpha;
  1591. this.z += ( v.z - this.z ) * alpha;
  1592. this.w += ( v.w - this.w ) * alpha;
  1593. return this;
  1594. },
  1595. equals: function ( v ) {
  1596. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1597. },
  1598. toArray: function () {
  1599. return [ this.x, this.y, this.z, this.w ];
  1600. },
  1601. clone: function () {
  1602. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1603. }
  1604. } );
  1605. /**
  1606. * @author bhouston / http://exocortex.com
  1607. */
  1608. THREE.Box2 = function ( min, max ) {
  1609. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  1610. this.max = ( max !== undefined ) ? max : new THREE.Vector2( -Infinity, -Infinity );
  1611. };
  1612. THREE.extend( THREE.Box2.prototype, {
  1613. set: function ( min, max ) {
  1614. this.min.copy( min );
  1615. this.max.copy( max );
  1616. return this;
  1617. },
  1618. setFromPoints: function ( points ) {
  1619. if ( points.length > 0 ) {
  1620. var point = points[ 0 ];
  1621. this.min.copy( point );
  1622. this.max.copy( point );
  1623. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1624. point = points[ i ];
  1625. if ( point.x < this.min.x ) {
  1626. this.min.x = point.x;
  1627. } else if ( point.x > this.max.x ) {
  1628. this.max.x = point.x;
  1629. }
  1630. if ( point.y < this.min.y ) {
  1631. this.min.y = point.y;
  1632. } else if ( point.y > this.max.y ) {
  1633. this.max.y = point.y;
  1634. }
  1635. }
  1636. } else {
  1637. this.makeEmpty();
  1638. }
  1639. return this;
  1640. },
  1641. setFromCenterAndSize: function() {
  1642. var v1 = new THREE.Vector2();
  1643. return function ( center, size ) {
  1644. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1645. this.min.copy( center ).sub( halfSize );
  1646. this.max.copy( center ).add( halfSize );
  1647. return this;
  1648. };
  1649. }(),
  1650. copy: function ( box ) {
  1651. this.min.copy( box.min );
  1652. this.max.copy( box.max );
  1653. return this;
  1654. },
  1655. makeEmpty: function () {
  1656. this.min.x = this.min.y = Infinity;
  1657. this.max.x = this.max.y = -Infinity;
  1658. return this;
  1659. },
  1660. empty: function () {
  1661. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1662. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  1663. },
  1664. center: function ( optionalTarget ) {
  1665. var result = optionalTarget || new THREE.Vector2();
  1666. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1667. },
  1668. size: function ( optionalTarget ) {
  1669. var result = optionalTarget || new THREE.Vector2();
  1670. return result.subVectors( this.max, this.min );
  1671. },
  1672. expandByPoint: function ( point ) {
  1673. this.min.min( point );
  1674. this.max.max( point );
  1675. return this;
  1676. },
  1677. expandByVector: function ( vector ) {
  1678. this.min.sub( vector );
  1679. this.max.add( vector );
  1680. return this;
  1681. },
  1682. expandByScalar: function ( scalar ) {
  1683. this.min.addScalar( -scalar );
  1684. this.max.addScalar( scalar );
  1685. return this;
  1686. },
  1687. containsPoint: function ( point ) {
  1688. if ( point.x < this.min.x || point.x > this.max.x ||
  1689. point.y < this.min.y || point.y > this.max.y ) {
  1690. return false;
  1691. }
  1692. return true;
  1693. },
  1694. containsBox: function ( box ) {
  1695. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1696. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  1697. return true;
  1698. }
  1699. return false;
  1700. },
  1701. getParameter: function ( point ) {
  1702. // This can potentially have a divide by zero if the box
  1703. // has a size dimension of 0.
  1704. return new THREE.Vector2(
  1705. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1706. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  1707. );
  1708. },
  1709. isIntersectionBox: function ( box ) {
  1710. // using 6 splitting planes to rule out intersections.
  1711. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  1712. box.max.y < this.min.y || box.min.y > this.max.y ) {
  1713. return false;
  1714. }
  1715. return true;
  1716. },
  1717. clampPoint: function ( point, optionalTarget ) {
  1718. var result = optionalTarget || new THREE.Vector2();
  1719. return result.copy( point ).clamp( this.min, this.max );
  1720. },
  1721. distanceToPoint: function() {
  1722. var v1 = new THREE.Vector2();
  1723. return function ( point ) {
  1724. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  1725. return clampedPoint.sub( point ).length();
  1726. };
  1727. }(),
  1728. intersect: function ( box ) {
  1729. this.min.max( box.min );
  1730. this.max.min( box.max );
  1731. return this;
  1732. },
  1733. union: function ( box ) {
  1734. this.min.min( box.min );
  1735. this.max.max( box.max );
  1736. return this;
  1737. },
  1738. translate: function ( offset ) {
  1739. this.min.add( offset );
  1740. this.max.add( offset );
  1741. return this;
  1742. },
  1743. equals: function ( box ) {
  1744. return box.min.equals( this.min ) && box.max.equals( this.max );
  1745. },
  1746. clone: function () {
  1747. return new THREE.Box2().copy( this );
  1748. }
  1749. } );
  1750. /**
  1751. * @author bhouston / http://exocortex.com
  1752. */
  1753. THREE.Box3 = function ( min, max ) {
  1754. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  1755. this.max = ( max !== undefined ) ? max : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  1756. };
  1757. THREE.extend( THREE.Box3.prototype, {
  1758. set: function ( min, max ) {
  1759. this.min.copy( min );
  1760. this.max.copy( max );
  1761. return this;
  1762. },
  1763. setFromPoints: function ( points ) {
  1764. if ( points.length > 0 ) {
  1765. var point = points[ 0 ];
  1766. this.min.copy( point );
  1767. this.max.copy( point );
  1768. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1769. point = points[ i ];
  1770. if ( point.x < this.min.x ) {
  1771. this.min.x = point.x;
  1772. } else if ( point.x > this.max.x ) {
  1773. this.max.x = point.x;
  1774. }
  1775. if ( point.y < this.min.y ) {
  1776. this.min.y = point.y;
  1777. } else if ( point.y > this.max.y ) {
  1778. this.max.y = point.y;
  1779. }
  1780. if ( point.z < this.min.z ) {
  1781. this.min.z = point.z;
  1782. } else if ( point.z > this.max.z ) {
  1783. this.max.z = point.z;
  1784. }
  1785. }
  1786. } else {
  1787. this.makeEmpty();
  1788. }
  1789. return this;
  1790. },
  1791. setFromCenterAndSize: function() {
  1792. var v1 = new THREE.Vector3();
  1793. return function ( center, size ) {
  1794. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1795. this.min.copy( center ).sub( halfSize );
  1796. this.max.copy( center ).add( halfSize );
  1797. return this;
  1798. };
  1799. }(),
  1800. copy: function ( box ) {
  1801. this.min.copy( box.min );
  1802. this.max.copy( box.max );
  1803. return this;
  1804. },
  1805. makeEmpty: function () {
  1806. this.min.x = this.min.y = this.min.z = Infinity;
  1807. this.max.x = this.max.y = this.max.z = -Infinity;
  1808. return this;
  1809. },
  1810. empty: function () {
  1811. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1812. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  1813. },
  1814. center: function ( optionalTarget ) {
  1815. var result = optionalTarget || new THREE.Vector3();
  1816. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1817. },
  1818. size: function ( optionalTarget ) {
  1819. var result = optionalTarget || new THREE.Vector3();
  1820. return result.subVectors( this.max, this.min );
  1821. },
  1822. expandByPoint: function ( point ) {
  1823. this.min.min( point );
  1824. this.max.max( point );
  1825. return this;
  1826. },
  1827. expandByVector: function ( vector ) {
  1828. this.min.sub( vector );
  1829. this.max.add( vector );
  1830. return this;
  1831. },
  1832. expandByScalar: function ( scalar ) {
  1833. this.min.addScalar( -scalar );
  1834. this.max.addScalar( scalar );
  1835. return this;
  1836. },
  1837. containsPoint: function ( point ) {
  1838. if ( point.x < this.min.x || point.x > this.max.x ||
  1839. point.y < this.min.y || point.y > this.max.y ||
  1840. point.z < this.min.z || point.z > this.max.z ) {
  1841. return false;
  1842. }
  1843. return true;
  1844. },
  1845. containsBox: function ( box ) {
  1846. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1847. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  1848. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  1849. return true;
  1850. }
  1851. return false;
  1852. },
  1853. getParameter: function ( point ) {
  1854. // This can potentially have a divide by zero if the box
  1855. // has a size dimension of 0.
  1856. return new THREE.Vector3(
  1857. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1858. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  1859. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  1860. );
  1861. },
  1862. isIntersectionBox: function ( box ) {
  1863. // using 6 splitting planes to rule out intersections.
  1864. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  1865. box.max.y < this.min.y || box.min.y > this.max.y ||
  1866. box.max.z < this.min.z || box.min.z > this.max.z ) {
  1867. return false;
  1868. }
  1869. return true;
  1870. },
  1871. clampPoint: function ( point, optionalTarget ) {
  1872. var result = optionalTarget || new THREE.Vector3();
  1873. return result.copy( point ).clamp( this.min, this.max );
  1874. },
  1875. distanceToPoint: function() {
  1876. var v1 = new THREE.Vector3();
  1877. return function ( point ) {
  1878. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  1879. return clampedPoint.sub( point ).length();
  1880. };
  1881. }(),
  1882. getBoundingSphere: function() {
  1883. var v1 = new THREE.Vector3();
  1884. return function ( optionalTarget ) {
  1885. var result = optionalTarget || new THREE.Sphere();
  1886. result.center = this.center();
  1887. result.radius = this.size( v1 ).length() * 0.5;
  1888. return result;
  1889. };
  1890. }(),
  1891. intersect: function ( box ) {
  1892. this.min.max( box.min );
  1893. this.max.min( box.max );
  1894. return this;
  1895. },
  1896. union: function ( box ) {
  1897. this.min.min( box.min );
  1898. this.max.max( box.max );
  1899. return this;
  1900. },
  1901. transform: function() {
  1902. var points = [
  1903. new THREE.Vector3(),
  1904. new THREE.Vector3(),
  1905. new THREE.Vector3(),
  1906. new THREE.Vector3(),
  1907. new THREE.Vector3(),
  1908. new THREE.Vector3(),
  1909. new THREE.Vector3(),
  1910. new THREE.Vector3()
  1911. ];
  1912. return function ( matrix ) {
  1913. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  1914. points[0].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  1915. points[1].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  1916. points[2].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  1917. points[3].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  1918. points[4].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  1919. points[5].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  1920. points[6].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  1921. points[7].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  1922. this.makeEmpty();
  1923. this.setFromPoints( points );
  1924. return this;
  1925. };
  1926. }(),
  1927. translate: function ( offset ) {
  1928. this.min.add( offset );
  1929. this.max.add( offset );
  1930. return this;
  1931. },
  1932. equals: function ( box ) {
  1933. return box.min.equals( this.min ) && box.max.equals( this.max );
  1934. },
  1935. clone: function () {
  1936. return new THREE.Box3().copy( this );
  1937. }
  1938. } );
  1939. /**
  1940. * @author alteredq / http://alteredqualia.com/
  1941. * @author WestLangley / http://github.com/WestLangley
  1942. * @author bhouston / http://exocortex.com
  1943. */
  1944. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  1945. this.elements = new Float32Array(9);
  1946. this.set(
  1947. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0,
  1948. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0,
  1949. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1
  1950. );
  1951. };
  1952. THREE.extend( THREE.Matrix3.prototype, {
  1953. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  1954. var te = this.elements;
  1955. te[0] = n11; te[3] = n12; te[6] = n13;
  1956. te[1] = n21; te[4] = n22; te[7] = n23;
  1957. te[2] = n31; te[5] = n32; te[8] = n33;
  1958. return this;
  1959. },
  1960. identity: function () {
  1961. this.set(
  1962. 1, 0, 0,
  1963. 0, 1, 0,
  1964. 0, 0, 1
  1965. );
  1966. return this;
  1967. },
  1968. copy: function ( m ) {
  1969. var me = m.elements;
  1970. this.set(
  1971. me[0], me[3], me[6],
  1972. me[1], me[4], me[7],
  1973. me[2], me[5], me[8]
  1974. );
  1975. return this;
  1976. },
  1977. multiplyVector3: function ( vector ) {
  1978. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  1979. return vector.applyMatrix3( this );
  1980. },
  1981. multiplyVector3Array: function() {
  1982. var v1 = new THREE.Vector3();
  1983. return function ( a ) {
  1984. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  1985. v1.x = a[ i ];
  1986. v1.y = a[ i + 1 ];
  1987. v1.z = a[ i + 2 ];
  1988. v1.applyMatrix3(this);
  1989. a[ i ] = v1.x;
  1990. a[ i + 1 ] = v1.y;
  1991. a[ i + 2 ] = v1.z;
  1992. }
  1993. return a;
  1994. };
  1995. }(),
  1996. multiplyScalar: function ( s ) {
  1997. var te = this.elements;
  1998. te[0] *= s; te[3] *= s; te[6] *= s;
  1999. te[1] *= s; te[4] *= s; te[7] *= s;
  2000. te[2] *= s; te[5] *= s; te[8] *= s;
  2001. return this;
  2002. },
  2003. determinant: function () {
  2004. var te = this.elements;
  2005. var a = te[0], b = te[1], c = te[2],
  2006. d = te[3], e = te[4], f = te[5],
  2007. g = te[6], h = te[7], i = te[8];
  2008. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  2009. },
  2010. getInverse: function ( matrix, throwOnInvertible ) {
  2011. // input: THREE.Matrix4
  2012. // ( based on http://code.google.com/p/webgl-mjs/ )
  2013. var me = matrix.elements;
  2014. var te = this.elements;
  2015. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  2016. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  2017. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  2018. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  2019. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  2020. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  2021. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  2022. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  2023. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  2024. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2025. // no inverse
  2026. if ( det === 0 ) {
  2027. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2028. if ( throwOnInvertible || false ) {
  2029. throw new Error( msg );
  2030. } else {
  2031. console.warn( msg );
  2032. }
  2033. this.identity();
  2034. return this;
  2035. }
  2036. this.multiplyScalar( 1.0 / det );
  2037. return this;
  2038. },
  2039. transpose: function () {
  2040. var tmp, m = this.elements;
  2041. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  2042. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  2043. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  2044. return this;
  2045. },
  2046. getNormalMatrix: function ( m ) {
  2047. // input: THREE.Matrix4
  2048. this.getInverse( m ).transpose();
  2049. return this;
  2050. },
  2051. transposeIntoArray: function ( r ) {
  2052. var m = this.elements;
  2053. r[ 0 ] = m[ 0 ];
  2054. r[ 1 ] = m[ 3 ];
  2055. r[ 2 ] = m[ 6 ];
  2056. r[ 3 ] = m[ 1 ];
  2057. r[ 4 ] = m[ 4 ];
  2058. r[ 5 ] = m[ 7 ];
  2059. r[ 6 ] = m[ 2 ];
  2060. r[ 7 ] = m[ 5 ];
  2061. r[ 8 ] = m[ 8 ];
  2062. return this;
  2063. },
  2064. clone: function () {
  2065. var te = this.elements;
  2066. return new THREE.Matrix3(
  2067. te[0], te[3], te[6],
  2068. te[1], te[4], te[7],
  2069. te[2], te[5], te[8]
  2070. );
  2071. }
  2072. } );
  2073. /**
  2074. * @author mrdoob / http://mrdoob.com/
  2075. * @author supereggbert / http://www.paulbrunt.co.uk/
  2076. * @author philogb / http://blog.thejit.org/
  2077. * @author jordi_ros / http://plattsoft.com
  2078. * @author D1plo1d / http://github.com/D1plo1d
  2079. * @author alteredq / http://alteredqualia.com/
  2080. * @author mikael emtinger / http://gomo.se/
  2081. * @author timknip / http://www.floorplanner.com/
  2082. * @author bhouston / http://exocortex.com
  2083. */
  2084. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2085. var te = this.elements = new Float32Array( 16 );
  2086. // TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix
  2087. // we should not support semi specification of Matrix4, it is just weird.
  2088. te[0] = ( n11 !== undefined ) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  2089. te[1] = n21 || 0; te[5] = ( n22 !== undefined ) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  2090. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = ( n33 !== undefined ) ? n33 : 1; te[14] = n34 || 0;
  2091. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = ( n44 !== undefined ) ? n44 : 1;
  2092. };
  2093. THREE.extend( THREE.Matrix4.prototype, {
  2094. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2095. var te = this.elements;
  2096. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  2097. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  2098. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  2099. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  2100. return this;
  2101. },
  2102. identity: function () {
  2103. this.set(
  2104. 1, 0, 0, 0,
  2105. 0, 1, 0, 0,
  2106. 0, 0, 1, 0,
  2107. 0, 0, 0, 1
  2108. );
  2109. return this;
  2110. },
  2111. copy: function ( m ) {
  2112. var me = m.elements;
  2113. this.set(
  2114. me[0], me[4], me[8], me[12],
  2115. me[1], me[5], me[9], me[13],
  2116. me[2], me[6], me[10], me[14],
  2117. me[3], me[7], me[11], me[15]
  2118. );
  2119. return this;
  2120. },
  2121. setRotationFromEuler: function ( v, order ) {
  2122. var te = this.elements;
  2123. var x = v.x, y = v.y, z = v.z;
  2124. var a = Math.cos( x ), b = Math.sin( x );
  2125. var c = Math.cos( y ), d = Math.sin( y );
  2126. var e = Math.cos( z ), f = Math.sin( z );
  2127. if ( order === undefined || order === 'XYZ' ) {
  2128. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2129. te[0] = c * e;
  2130. te[4] = - c * f;
  2131. te[8] = d;
  2132. te[1] = af + be * d;
  2133. te[5] = ae - bf * d;
  2134. te[9] = - b * c;
  2135. te[2] = bf - ae * d;
  2136. te[6] = be + af * d;
  2137. te[10] = a * c;
  2138. } else if ( order === 'YXZ' ) {
  2139. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2140. te[0] = ce + df * b;
  2141. te[4] = de * b - cf;
  2142. te[8] = a * d;
  2143. te[1] = a * f;
  2144. te[5] = a * e;
  2145. te[9] = - b;
  2146. te[2] = cf * b - de;
  2147. te[6] = df + ce * b;
  2148. te[10] = a * c;
  2149. } else if ( order === 'ZXY' ) {
  2150. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2151. te[0] = ce - df * b;
  2152. te[4] = - a * f;
  2153. te[8] = de + cf * b;
  2154. te[1] = cf + de * b;
  2155. te[5] = a * e;
  2156. te[9] = df - ce * b;
  2157. te[2] = - a * d;
  2158. te[6] = b;
  2159. te[10] = a * c;
  2160. } else if ( order === 'ZYX' ) {
  2161. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2162. te[0] = c * e;
  2163. te[4] = be * d - af;
  2164. te[8] = ae * d + bf;
  2165. te[1] = c * f;
  2166. te[5] = bf * d + ae;
  2167. te[9] = af * d - be;
  2168. te[2] = - d;
  2169. te[6] = b * c;
  2170. te[10] = a * c;
  2171. } else if ( order === 'YZX' ) {
  2172. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2173. te[0] = c * e;
  2174. te[4] = bd - ac * f;
  2175. te[8] = bc * f + ad;
  2176. te[1] = f;
  2177. te[5] = a * e;
  2178. te[9] = - b * e;
  2179. te[2] = - d * e;
  2180. te[6] = ad * f + bc;
  2181. te[10] = ac - bd * f;
  2182. } else if ( order === 'XZY' ) {
  2183. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2184. te[0] = c * e;
  2185. te[4] = - f;
  2186. te[8] = d * e;
  2187. te[1] = ac * f + bd;
  2188. te[5] = a * e;
  2189. te[9] = ad * f - bc;
  2190. te[2] = bc * f - ad;
  2191. te[6] = b * e;
  2192. te[10] = bd * f + ac;
  2193. }
  2194. return this;
  2195. },
  2196. setRotationFromQuaternion: function ( q ) {
  2197. var te = this.elements;
  2198. var x = q.x, y = q.y, z = q.z, w = q.w;
  2199. var x2 = x + x, y2 = y + y, z2 = z + z;
  2200. var xx = x * x2, xy = x * y2, xz = x * z2;
  2201. var yy = y * y2, yz = y * z2, zz = z * z2;
  2202. var wx = w * x2, wy = w * y2, wz = w * z2;
  2203. te[0] = 1 - ( yy + zz );
  2204. te[4] = xy - wz;
  2205. te[8] = xz + wy;
  2206. te[1] = xy + wz;
  2207. te[5] = 1 - ( xx + zz );
  2208. te[9] = yz - wx;
  2209. te[2] = xz - wy;
  2210. te[6] = yz + wx;
  2211. te[10] = 1 - ( xx + yy );
  2212. return this;
  2213. },
  2214. lookAt: function() {
  2215. var x = new THREE.Vector3();
  2216. var y = new THREE.Vector3();
  2217. var z = new THREE.Vector3();
  2218. return function ( eye, target, up ) {
  2219. var te = this.elements;
  2220. z.subVectors( eye, target ).normalize();
  2221. if ( z.length() === 0 ) {
  2222. z.z = 1;
  2223. }
  2224. x.crossVectors( up, z ).normalize();
  2225. if ( x.length() === 0 ) {
  2226. z.x += 0.0001;
  2227. x.crossVectors( up, z ).normalize();
  2228. }
  2229. y.crossVectors( z, x );
  2230. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  2231. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  2232. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  2233. return this;
  2234. };
  2235. }(),
  2236. multiply: function ( m, n ) {
  2237. if ( n !== undefined ) {
  2238. console.warn( 'DEPRECATED: Matrix4\'s .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2239. return this.multiplyMatrices( m, n );
  2240. }
  2241. return this.multiplyMatrices( this, m );
  2242. },
  2243. multiplyMatrices: function ( a, b ) {
  2244. var ae = a.elements;
  2245. var be = b.elements;
  2246. var te = this.elements;
  2247. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  2248. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  2249. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  2250. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  2251. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  2252. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  2253. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  2254. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  2255. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2256. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2257. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2258. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2259. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2260. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2261. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2262. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2263. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2264. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2265. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2266. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2267. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2268. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2269. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2270. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2271. return this;
  2272. },
  2273. multiplyToArray: function ( a, b, r ) {
  2274. var te = this.elements;
  2275. this.multiplyMatrices( a, b );
  2276. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  2277. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  2278. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  2279. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  2280. return this;
  2281. },
  2282. multiplyScalar: function ( s ) {
  2283. var te = this.elements;
  2284. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  2285. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  2286. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  2287. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  2288. return this;
  2289. },
  2290. multiplyVector3: function ( vector ) {
  2291. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2292. return vector.applyProjection( this );
  2293. },
  2294. multiplyVector4: function ( vector ) {
  2295. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2296. return vector.applyMatrix4( this );
  2297. },
  2298. multiplyVector3Array: function() {
  2299. var v1 = new THREE.Vector3();
  2300. return function ( a ) {
  2301. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2302. v1.x = a[ i ];
  2303. v1.y = a[ i + 1 ];
  2304. v1.z = a[ i + 2 ];
  2305. v1.applyProjection( this );
  2306. a[ i ] = v1.x;
  2307. a[ i + 1 ] = v1.y;
  2308. a[ i + 2 ] = v1.z;
  2309. }
  2310. return a;
  2311. };
  2312. }(),
  2313. rotateAxis: function ( v ) {
  2314. var te = this.elements;
  2315. var vx = v.x, vy = v.y, vz = v.z;
  2316. v.x = vx * te[0] + vy * te[4] + vz * te[8];
  2317. v.y = vx * te[1] + vy * te[5] + vz * te[9];
  2318. v.z = vx * te[2] + vy * te[6] + vz * te[10];
  2319. v.normalize();
  2320. return v;
  2321. },
  2322. crossVector: function ( a ) {
  2323. var te = this.elements;
  2324. var v = new THREE.Vector4();
  2325. v.x = te[0] * a.x + te[4] * a.y + te[8] * a.z + te[12] * a.w;
  2326. v.y = te[1] * a.x + te[5] * a.y + te[9] * a.z + te[13] * a.w;
  2327. v.z = te[2] * a.x + te[6] * a.y + te[10] * a.z + te[14] * a.w;
  2328. v.w = ( a.w ) ? te[3] * a.x + te[7] * a.y + te[11] * a.z + te[15] * a.w : 1;
  2329. return v;
  2330. },
  2331. determinant: function () {
  2332. var te = this.elements;
  2333. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  2334. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  2335. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  2336. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  2337. //TODO: make this more efficient
  2338. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2339. return (
  2340. n41 * (
  2341. +n14 * n23 * n32
  2342. -n13 * n24 * n32
  2343. -n14 * n22 * n33
  2344. +n12 * n24 * n33
  2345. +n13 * n22 * n34
  2346. -n12 * n23 * n34
  2347. ) +
  2348. n42 * (
  2349. +n11 * n23 * n34
  2350. -n11 * n24 * n33
  2351. +n14 * n21 * n33
  2352. -n13 * n21 * n34
  2353. +n13 * n24 * n31
  2354. -n14 * n23 * n31
  2355. ) +
  2356. n43 * (
  2357. +n11 * n24 * n32
  2358. -n11 * n22 * n34
  2359. -n14 * n21 * n32
  2360. +n12 * n21 * n34
  2361. +n14 * n22 * n31
  2362. -n12 * n24 * n31
  2363. ) +
  2364. n44 * (
  2365. -n13 * n22 * n31
  2366. -n11 * n23 * n32
  2367. +n11 * n22 * n33
  2368. +n13 * n21 * n32
  2369. -n12 * n21 * n33
  2370. +n12 * n23 * n31
  2371. )
  2372. );
  2373. },
  2374. transpose: function () {
  2375. var te = this.elements;
  2376. var tmp;
  2377. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  2378. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  2379. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  2380. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  2381. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  2382. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  2383. return this;
  2384. },
  2385. flattenToArray: function ( flat ) {
  2386. var te = this.elements;
  2387. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  2388. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  2389. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  2390. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  2391. return flat;
  2392. },
  2393. flattenToArrayOffset: function( flat, offset ) {
  2394. var te = this.elements;
  2395. flat[ offset ] = te[0];
  2396. flat[ offset + 1 ] = te[1];
  2397. flat[ offset + 2 ] = te[2];
  2398. flat[ offset + 3 ] = te[3];
  2399. flat[ offset + 4 ] = te[4];
  2400. flat[ offset + 5 ] = te[5];
  2401. flat[ offset + 6 ] = te[6];
  2402. flat[ offset + 7 ] = te[7];
  2403. flat[ offset + 8 ] = te[8];
  2404. flat[ offset + 9 ] = te[9];
  2405. flat[ offset + 10 ] = te[10];
  2406. flat[ offset + 11 ] = te[11];
  2407. flat[ offset + 12 ] = te[12];
  2408. flat[ offset + 13 ] = te[13];
  2409. flat[ offset + 14 ] = te[14];
  2410. flat[ offset + 15 ] = te[15];
  2411. return flat;
  2412. },
  2413. getPosition: function() {
  2414. var v1 = new THREE.Vector3();
  2415. return function () {
  2416. var te = this.elements;
  2417. return v1.set( te[12], te[13], te[14] );
  2418. };
  2419. }(),
  2420. setPosition: function ( v ) {
  2421. var te = this.elements;
  2422. te[12] = v.x;
  2423. te[13] = v.y;
  2424. te[14] = v.z;
  2425. return this;
  2426. },
  2427. getInverse: function ( m, throwOnInvertible ) {
  2428. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2429. var te = this.elements;
  2430. var me = m.elements;
  2431. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2432. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2433. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2434. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2435. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2436. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2437. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2438. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2439. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2440. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2441. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2442. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2443. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2444. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2445. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2446. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2447. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2448. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2449. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2450. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2451. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 4 ] + me[ 2 ] * te[ 8 ] + me[ 3 ] * te[ 12 ];
  2452. if ( det == 0 ) {
  2453. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2454. if ( throwOnInvertible || false ) {
  2455. throw new Error( msg );
  2456. } else {
  2457. console.warn( msg );
  2458. }
  2459. this.identity();
  2460. return this;
  2461. }
  2462. this.multiplyScalar( 1 / det );
  2463. return this;
  2464. },
  2465. compose: function() {
  2466. var mRotation = new THREE.Matrix4(),
  2467. mScale = new THREE.Matrix4();
  2468. return function ( translation, rotation, scale ) {
  2469. var te = this.elements;
  2470. mRotation.identity();
  2471. mRotation.setRotationFromQuaternion( rotation );
  2472. mScale.makeScale( scale.x, scale.y, scale.z );
  2473. this.multiplyMatrices( mRotation, mScale );
  2474. te[12] = translation.x;
  2475. te[13] = translation.y;
  2476. te[14] = translation.z;
  2477. return this;
  2478. };
  2479. }(),
  2480. decompose: function() {
  2481. var x = new THREE.Vector3(),
  2482. y = new THREE.Vector3(),
  2483. z = new THREE.Vector3(),
  2484. matrix = new THREE.Matrix4();
  2485. return function ( translation, rotation, scale ) {
  2486. var te = this.elements;
  2487. // grab the axis vectors
  2488. x.set( te[0], te[1], te[2] );
  2489. y.set( te[4], te[5], te[6] );
  2490. z.set( te[8], te[9], te[10] );
  2491. translation = ( translation instanceof THREE.Vector3 ) ? translation : new THREE.Vector3();
  2492. rotation = ( rotation instanceof THREE.Quaternion ) ? rotation : new THREE.Quaternion();
  2493. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  2494. scale.x = x.length();
  2495. scale.y = y.length();
  2496. scale.z = z.length();
  2497. translation.x = te[12];
  2498. translation.y = te[13];
  2499. translation.z = te[14];
  2500. // scale the rotation part
  2501. matrix.copy( this );
  2502. matrix.elements[0] /= scale.x;
  2503. matrix.elements[1] /= scale.x;
  2504. matrix.elements[2] /= scale.x;
  2505. matrix.elements[4] /= scale.y;
  2506. matrix.elements[5] /= scale.y;
  2507. matrix.elements[6] /= scale.y;
  2508. matrix.elements[8] /= scale.z;
  2509. matrix.elements[9] /= scale.z;
  2510. matrix.elements[10] /= scale.z;
  2511. rotation.setFromRotationMatrix( matrix );
  2512. return [ translation, rotation, scale ];
  2513. };
  2514. }(),
  2515. extractPosition: function ( m ) {
  2516. var te = this.elements;
  2517. var me = m.elements;
  2518. te[12] = me[12];
  2519. te[13] = me[13];
  2520. te[14] = me[14];
  2521. return this;
  2522. },
  2523. extractRotation: function() {
  2524. var v1 = new THREE.Vector3();
  2525. return function ( m ) {
  2526. var te = this.elements;
  2527. var me = m.elements;
  2528. var scaleX = 1 / v1.set( me[0], me[1], me[2] ).length();
  2529. var scaleY = 1 / v1.set( me[4], me[5], me[6] ).length();
  2530. var scaleZ = 1 / v1.set( me[8], me[9], me[10] ).length();
  2531. te[0] = me[0] * scaleX;
  2532. te[1] = me[1] * scaleX;
  2533. te[2] = me[2] * scaleX;
  2534. te[4] = me[4] * scaleY;
  2535. te[5] = me[5] * scaleY;
  2536. te[6] = me[6] * scaleY;
  2537. te[8] = me[8] * scaleZ;
  2538. te[9] = me[9] * scaleZ;
  2539. te[10] = me[10] * scaleZ;
  2540. return this;
  2541. };
  2542. }(),
  2543. translate: function ( v ) {
  2544. var te = this.elements;
  2545. var x = v.x, y = v.y, z = v.z;
  2546. te[12] = te[0] * x + te[4] * y + te[8] * z + te[12];
  2547. te[13] = te[1] * x + te[5] * y + te[9] * z + te[13];
  2548. te[14] = te[2] * x + te[6] * y + te[10] * z + te[14];
  2549. te[15] = te[3] * x + te[7] * y + te[11] * z + te[15];
  2550. return this;
  2551. },
  2552. rotateX: function ( angle ) {
  2553. var te = this.elements;
  2554. var m12 = te[4];
  2555. var m22 = te[5];
  2556. var m32 = te[6];
  2557. var m42 = te[7];
  2558. var m13 = te[8];
  2559. var m23 = te[9];
  2560. var m33 = te[10];
  2561. var m43 = te[11];
  2562. var c = Math.cos( angle );
  2563. var s = Math.sin( angle );
  2564. te[4] = c * m12 + s * m13;
  2565. te[5] = c * m22 + s * m23;
  2566. te[6] = c * m32 + s * m33;
  2567. te[7] = c * m42 + s * m43;
  2568. te[8] = c * m13 - s * m12;
  2569. te[9] = c * m23 - s * m22;
  2570. te[10] = c * m33 - s * m32;
  2571. te[11] = c * m43 - s * m42;
  2572. return this;
  2573. },
  2574. rotateY: function ( angle ) {
  2575. var te = this.elements;
  2576. var m11 = te[0];
  2577. var m21 = te[1];
  2578. var m31 = te[2];
  2579. var m41 = te[3];
  2580. var m13 = te[8];
  2581. var m23 = te[9];
  2582. var m33 = te[10];
  2583. var m43 = te[11];
  2584. var c = Math.cos( angle );
  2585. var s = Math.sin( angle );
  2586. te[0] = c * m11 - s * m13;
  2587. te[1] = c * m21 - s * m23;
  2588. te[2] = c * m31 - s * m33;
  2589. te[3] = c * m41 - s * m43;
  2590. te[8] = c * m13 + s * m11;
  2591. te[9] = c * m23 + s * m21;
  2592. te[10] = c * m33 + s * m31;
  2593. te[11] = c * m43 + s * m41;
  2594. return this;
  2595. },
  2596. rotateZ: function ( angle ) {
  2597. var te = this.elements;
  2598. var m11 = te[0];
  2599. var m21 = te[1];
  2600. var m31 = te[2];
  2601. var m41 = te[3];
  2602. var m12 = te[4];
  2603. var m22 = te[5];
  2604. var m32 = te[6];
  2605. var m42 = te[7];
  2606. var c = Math.cos( angle );
  2607. var s = Math.sin( angle );
  2608. te[0] = c * m11 + s * m12;
  2609. te[1] = c * m21 + s * m22;
  2610. te[2] = c * m31 + s * m32;
  2611. te[3] = c * m41 + s * m42;
  2612. te[4] = c * m12 - s * m11;
  2613. te[5] = c * m22 - s * m21;
  2614. te[6] = c * m32 - s * m31;
  2615. te[7] = c * m42 - s * m41;
  2616. return this;
  2617. },
  2618. rotateByAxis: function ( axis, angle ) {
  2619. var te = this.elements;
  2620. // optimize by checking axis
  2621. if ( axis.x === 1 && axis.y === 0 && axis.z === 0 ) {
  2622. return this.rotateX( angle );
  2623. } else if ( axis.x === 0 && axis.y === 1 && axis.z === 0 ) {
  2624. return this.rotateY( angle );
  2625. } else if ( axis.x === 0 && axis.y === 0 && axis.z === 1 ) {
  2626. return this.rotateZ( angle );
  2627. }
  2628. var x = axis.x, y = axis.y, z = axis.z;
  2629. var n = Math.sqrt(x * x + y * y + z * z);
  2630. x /= n;
  2631. y /= n;
  2632. z /= n;
  2633. var xx = x * x, yy = y * y, zz = z * z;
  2634. var c = Math.cos( angle );
  2635. var s = Math.sin( angle );
  2636. var oneMinusCosine = 1 - c;
  2637. var xy = x * y * oneMinusCosine;
  2638. var xz = x * z * oneMinusCosine;
  2639. var yz = y * z * oneMinusCosine;
  2640. var xs = x * s;
  2641. var ys = y * s;
  2642. var zs = z * s;
  2643. var r11 = xx + (1 - xx) * c;
  2644. var r21 = xy + zs;
  2645. var r31 = xz - ys;
  2646. var r12 = xy - zs;
  2647. var r22 = yy + (1 - yy) * c;
  2648. var r32 = yz + xs;
  2649. var r13 = xz + ys;
  2650. var r23 = yz - xs;
  2651. var r33 = zz + (1 - zz) * c;
  2652. var m11 = te[0], m21 = te[1], m31 = te[2], m41 = te[3];
  2653. var m12 = te[4], m22 = te[5], m32 = te[6], m42 = te[7];
  2654. var m13 = te[8], m23 = te[9], m33 = te[10], m43 = te[11];
  2655. var m14 = te[12], m24 = te[13], m34 = te[14], m44 = te[15];
  2656. te[0] = r11 * m11 + r21 * m12 + r31 * m13;
  2657. te[1] = r11 * m21 + r21 * m22 + r31 * m23;
  2658. te[2] = r11 * m31 + r21 * m32 + r31 * m33;
  2659. te[3] = r11 * m41 + r21 * m42 + r31 * m43;
  2660. te[4] = r12 * m11 + r22 * m12 + r32 * m13;
  2661. te[5] = r12 * m21 + r22 * m22 + r32 * m23;
  2662. te[6] = r12 * m31 + r22 * m32 + r32 * m33;
  2663. te[7] = r12 * m41 + r22 * m42 + r32 * m43;
  2664. te[8] = r13 * m11 + r23 * m12 + r33 * m13;
  2665. te[9] = r13 * m21 + r23 * m22 + r33 * m23;
  2666. te[10] = r13 * m31 + r23 * m32 + r33 * m33;
  2667. te[11] = r13 * m41 + r23 * m42 + r33 * m43;
  2668. return this;
  2669. },
  2670. scale: function ( v ) {
  2671. var te = this.elements;
  2672. var x = v.x, y = v.y, z = v.z;
  2673. te[0] *= x; te[4] *= y; te[8] *= z;
  2674. te[1] *= x; te[5] *= y; te[9] *= z;
  2675. te[2] *= x; te[6] *= y; te[10] *= z;
  2676. te[3] *= x; te[7] *= y; te[11] *= z;
  2677. return this;
  2678. },
  2679. getMaxScaleOnAxis: function () {
  2680. var te = this.elements;
  2681. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2682. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2683. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2684. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2685. },
  2686. makeTranslation: function ( x, y, z ) {
  2687. this.set(
  2688. 1, 0, 0, x,
  2689. 0, 1, 0, y,
  2690. 0, 0, 1, z,
  2691. 0, 0, 0, 1
  2692. );
  2693. return this;
  2694. },
  2695. makeRotationX: function ( theta ) {
  2696. var c = Math.cos( theta ), s = Math.sin( theta );
  2697. this.set(
  2698. 1, 0, 0, 0,
  2699. 0, c, -s, 0,
  2700. 0, s, c, 0,
  2701. 0, 0, 0, 1
  2702. );
  2703. return this;
  2704. },
  2705. makeRotationY: function ( theta ) {
  2706. var c = Math.cos( theta ), s = Math.sin( theta );
  2707. this.set(
  2708. c, 0, s, 0,
  2709. 0, 1, 0, 0,
  2710. -s, 0, c, 0,
  2711. 0, 0, 0, 1
  2712. );
  2713. return this;
  2714. },
  2715. makeRotationZ: function ( theta ) {
  2716. var c = Math.cos( theta ), s = Math.sin( theta );
  2717. this.set(
  2718. c, -s, 0, 0,
  2719. s, c, 0, 0,
  2720. 0, 0, 1, 0,
  2721. 0, 0, 0, 1
  2722. );
  2723. return this;
  2724. },
  2725. makeRotationAxis: function ( axis, angle ) {
  2726. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2727. var c = Math.cos( angle );
  2728. var s = Math.sin( angle );
  2729. var t = 1 - c;
  2730. var x = axis.x, y = axis.y, z = axis.z;
  2731. var tx = t * x, ty = t * y;
  2732. this.set(
  2733. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2734. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2735. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2736. 0, 0, 0, 1
  2737. );
  2738. return this;
  2739. },
  2740. makeScale: function ( x, y, z ) {
  2741. this.set(
  2742. x, 0, 0, 0,
  2743. 0, y, 0, 0,
  2744. 0, 0, z, 0,
  2745. 0, 0, 0, 1
  2746. );
  2747. return this;
  2748. },
  2749. makeFrustum: function ( left, right, bottom, top, near, far ) {
  2750. var te = this.elements;
  2751. var x = 2 * near / ( right - left );
  2752. var y = 2 * near / ( top - bottom );
  2753. var a = ( right + left ) / ( right - left );
  2754. var b = ( top + bottom ) / ( top - bottom );
  2755. var c = - ( far + near ) / ( far - near );
  2756. var d = - 2 * far * near / ( far - near );
  2757. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  2758. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  2759. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  2760. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  2761. return this;
  2762. },
  2763. makePerspective: function ( fov, aspect, near, far ) {
  2764. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  2765. var ymin = - ymax;
  2766. var xmin = ymin * aspect;
  2767. var xmax = ymax * aspect;
  2768. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  2769. },
  2770. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2771. var te = this.elements;
  2772. var w = right - left;
  2773. var h = top - bottom;
  2774. var p = far - near;
  2775. var x = ( right + left ) / w;
  2776. var y = ( top + bottom ) / h;
  2777. var z = ( far + near ) / p;
  2778. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  2779. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  2780. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  2781. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  2782. return this;
  2783. },
  2784. clone: function () {
  2785. var te = this.elements;
  2786. return new THREE.Matrix4(
  2787. te[0], te[4], te[8], te[12],
  2788. te[1], te[5], te[9], te[13],
  2789. te[2], te[6], te[10], te[14],
  2790. te[3], te[7], te[11], te[15]
  2791. );
  2792. }
  2793. } );
  2794. /**
  2795. * @author bhouston / http://exocortex.com
  2796. */
  2797. THREE.Ray = function ( origin, direction ) {
  2798. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  2799. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  2800. };
  2801. THREE.extend( THREE.Ray.prototype, {
  2802. set: function ( origin, direction ) {
  2803. this.origin.copy( origin );
  2804. this.direction.copy( direction );
  2805. return this;
  2806. },
  2807. copy: function ( ray ) {
  2808. this.origin.copy( ray.origin );
  2809. this.direction.copy( ray.direction );
  2810. return this;
  2811. },
  2812. at: function( t, optionalTarget ) {
  2813. var result = optionalTarget || new THREE.Vector3();
  2814. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  2815. },
  2816. recast: function() {
  2817. var v1 = new THREE.Vector3();
  2818. return function ( t ) {
  2819. this.origin.copy( this.at( t, v1 ) );
  2820. return this;
  2821. };
  2822. }(),
  2823. closestPointToPoint: function ( point, optionalTarget ) {
  2824. var result = optionalTarget || new THREE.Vector3();
  2825. result.subVectors( point, this.origin );
  2826. var directionDistance = result.dot( this.direction );
  2827. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2828. },
  2829. distanceToPoint: function() {
  2830. var v1 = new THREE.Vector3();
  2831. return function ( point ) {
  2832. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  2833. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2834. return v1.distanceTo( point );
  2835. };
  2836. }(),
  2837. isIntersectionSphere: function( sphere ) {
  2838. return ( this.distanceToPoint( sphere.center ) <= sphere.radius );
  2839. },
  2840. isIntersectionPlane: function ( plane ) {
  2841. // check if the line and plane are non-perpendicular, if they
  2842. // eventually they will intersect.
  2843. var denominator = plane.normal.dot( this.direction );
  2844. if ( denominator != 0 ) {
  2845. return true;
  2846. }
  2847. // line is coplanar, return origin
  2848. if( plane.distanceToPoint( this.origin ) == 0 ) {
  2849. return true;
  2850. }
  2851. return false;
  2852. },
  2853. distanceToPlane: function ( plane ) {
  2854. var denominator = plane.normal.dot( this.direction );
  2855. if ( denominator == 0 ) {
  2856. // line is coplanar, return origin
  2857. if( plane.distanceToPoint( this.origin ) == 0 ) {
  2858. return 0;
  2859. }
  2860. // Unsure if this is the correct method to handle this case.
  2861. return undefined;
  2862. }
  2863. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  2864. return t;
  2865. },
  2866. intersectPlane: function ( plane, optionalTarget ) {
  2867. var t = this.distanceToPlane( plane );
  2868. if ( t === undefined ) {
  2869. return undefined;
  2870. }
  2871. return this.at( t, optionalTarget );
  2872. },
  2873. transform: function ( matrix4 ) {
  2874. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  2875. this.origin.applyMatrix4( matrix4 );
  2876. this.direction.sub( this.origin );
  2877. return this;
  2878. },
  2879. equals: function ( ray ) {
  2880. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  2881. },
  2882. clone: function () {
  2883. return new THREE.Ray().copy( this );
  2884. }
  2885. } );
  2886. /**
  2887. * @author bhouston / http://exocortex.com
  2888. * @author mrdoob / http://mrdoob.com/
  2889. */
  2890. THREE.Sphere = function ( center, radius ) {
  2891. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  2892. this.radius = ( radius !== undefined ) ? radius : 0;
  2893. };
  2894. THREE.extend( THREE.Sphere.prototype, {
  2895. set: function ( center, radius ) {
  2896. this.center.copy( center );
  2897. this.radius = radius;
  2898. return this;
  2899. },
  2900. setFromCenterAndPoints: function ( center, points ) {
  2901. var maxRadiusSq = 0;
  2902. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2903. var radiusSq = center.distanceToSquared( points[ i ] );
  2904. maxRadiusSq = Math.max( maxRadiusSq, radiusSq );
  2905. }
  2906. this.center = center;
  2907. this.radius = Math.sqrt( maxRadiusSq );
  2908. return this;
  2909. },
  2910. copy: function ( sphere ) {
  2911. this.center.copy( sphere.center );
  2912. this.radius = sphere.radius;
  2913. return this;
  2914. },
  2915. empty: function () {
  2916. return ( this.radius <= 0 );
  2917. },
  2918. containsPoint: function ( point ) {
  2919. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  2920. },
  2921. distanceToPoint: function ( point ) {
  2922. return ( point.distanceTo( this.center ) - this.radius );
  2923. },
  2924. intersectsSphere: function ( sphere ) {
  2925. var radiusSum = this.radius + sphere.radius;
  2926. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  2927. },
  2928. clampPoint: function ( point, optionalTarget ) {
  2929. var deltaLengthSq = this.center.distanceToSquared( point );
  2930. var result = optionalTarget || new THREE.Vector3();
  2931. result.copy( point );
  2932. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  2933. result.sub( this.center ).normalize();
  2934. result.multiplyScalar( this.radius ).add( this.center );
  2935. }
  2936. return result;
  2937. },
  2938. getBoundingBox: function ( optionalTarget ) {
  2939. var box = optionalTarget || new THREE.Box3();
  2940. box.set( this.center, this.center );
  2941. box.expandByScalar( this.radius );
  2942. return box;
  2943. },
  2944. transform: function ( matrix ) {
  2945. this.center.applyMatrix4( matrix );
  2946. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2947. return this;
  2948. },
  2949. translate: function ( offset ) {
  2950. this.center.add( offset );
  2951. return this;
  2952. },
  2953. equals: function ( sphere ) {
  2954. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  2955. },
  2956. clone: function () {
  2957. return new THREE.Sphere().copy( this );
  2958. }
  2959. } );
  2960. /**
  2961. * @author mrdoob / http://mrdoob.com/
  2962. * @author alteredq / http://alteredqualia.com/
  2963. * @author bhouston / http://exocortex.com
  2964. */
  2965. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  2966. this.planes = [
  2967. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  2968. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  2969. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  2970. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  2971. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  2972. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  2973. ];
  2974. };
  2975. THREE.extend( THREE.Frustum.prototype, {
  2976. set: function ( p0, p1, p2, p3, p4, p5 ) {
  2977. var planes = this.planes;
  2978. planes[0].copy( p0 );
  2979. planes[1].copy( p1 );
  2980. planes[2].copy( p2 );
  2981. planes[3].copy( p3 );
  2982. planes[4].copy( p4 );
  2983. planes[5].copy( p5 );
  2984. return this;
  2985. },
  2986. copy: function ( frustum ) {
  2987. var planes = this.planes;
  2988. for( var i = 0; i < 6; i ++ ) {
  2989. planes[i].copy( frustum.planes[i] );
  2990. }
  2991. return this;
  2992. },
  2993. setFromMatrix: function ( m ) {
  2994. var planes = this.planes;
  2995. var me = m.elements;
  2996. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  2997. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  2998. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  2999. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  3000. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3001. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3002. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3003. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3004. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3005. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3006. return this;
  3007. },
  3008. intersectsObject: function () {
  3009. var center = new THREE.Vector3();
  3010. return function ( object ) {
  3011. // this method is expanded inlined for performance reasons.
  3012. var matrix = object.matrixWorld;
  3013. var planes = this.planes;
  3014. var negRadius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  3015. center.getPositionFromMatrix( matrix );
  3016. for ( var i = 0; i < 6; i ++ ) {
  3017. var distance = planes[ i ].distanceToPoint( center );
  3018. if ( distance < negRadius ) {
  3019. return false;
  3020. }
  3021. }
  3022. return true;
  3023. };
  3024. }(),
  3025. intersectsSphere: function ( sphere ) {
  3026. var planes = this.planes;
  3027. var center = sphere.center;
  3028. var negRadius = -sphere.radius;
  3029. for ( var i = 0; i < 6; i ++ ) {
  3030. var distance = planes[ i ].distanceToPoint( center );
  3031. if ( distance < negRadius ) {
  3032. return false;
  3033. }
  3034. }
  3035. return true;
  3036. },
  3037. containsPoint: function ( point ) {
  3038. var planes = this.planes;
  3039. for ( var i = 0; i < 6; i ++ ) {
  3040. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3041. return false;
  3042. }
  3043. }
  3044. return true;
  3045. },
  3046. clone: function () {
  3047. return new THREE.Frustum().copy( this );
  3048. }
  3049. } );
  3050. /**
  3051. * @author bhouston / http://exocortex.com
  3052. */
  3053. THREE.Plane = function ( normal, constant ) {
  3054. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3055. this.constant = ( constant !== undefined ) ? constant : 0;
  3056. };
  3057. THREE.extend( THREE.Plane.prototype, {
  3058. set: function ( normal, constant ) {
  3059. this.normal.copy( normal );
  3060. this.constant = constant;
  3061. return this;
  3062. },
  3063. setComponents: function ( x, y, z, w ) {
  3064. this.normal.set( x, y, z );
  3065. this.constant = w;
  3066. return this;
  3067. },
  3068. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3069. this.normal.copy( normal );
  3070. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3071. return this;
  3072. },
  3073. setFromCoplanarPoints: function() {
  3074. var v1 = new THREE.Vector3();
  3075. var v2 = new THREE.Vector3();
  3076. return function ( a, b, c ) {
  3077. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3078. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3079. this.setFromNormalAndCoplanarPoint( normal, a );
  3080. return this;
  3081. };
  3082. }(),
  3083. copy: function ( plane ) {
  3084. this.normal.copy( plane.normal );
  3085. this.constant = plane.constant;
  3086. return this;
  3087. },
  3088. normalize: function () {
  3089. // Note: will lead to a divide by zero if the plane is invalid.
  3090. var inverseNormalLength = 1.0 / this.normal.length();
  3091. this.normal.multiplyScalar( inverseNormalLength );
  3092. this.constant *= inverseNormalLength;
  3093. return this;
  3094. },
  3095. negate: function () {
  3096. this.constant *= -1;
  3097. this.normal.negate();
  3098. return this;
  3099. },
  3100. distanceToPoint: function ( point ) {
  3101. return this.normal.dot( point ) + this.constant;
  3102. },
  3103. distanceToSphere: function ( sphere ) {
  3104. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3105. },
  3106. projectPoint: function ( point, optionalTarget ) {
  3107. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3108. },
  3109. orthoPoint: function ( point, optionalTarget ) {
  3110. var perpendicularMagnitude = this.distanceToPoint( point );
  3111. var result = optionalTarget || new THREE.Vector3();
  3112. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3113. },
  3114. isIntersectionLine: function ( startPoint, endPoint ) {
  3115. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3116. var startSign = this.distanceToPoint( startPoint );
  3117. var endSign = this.distanceToPoint( endPoint );
  3118. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3119. },
  3120. intersectLine: function() {
  3121. var v1 = new THREE.Vector3();
  3122. return function ( startPoint, endPoint, optionalTarget ) {
  3123. var result = optionalTarget || new THREE.Vector3();
  3124. var direction = v1.subVectors( endPoint, startPoint );
  3125. var denominator = this.normal.dot( direction );
  3126. if ( denominator == 0 ) {
  3127. // line is coplanar, return origin
  3128. if( this.distanceToPoint( startPoint ) == 0 ) {
  3129. return result.copy( startPoint );
  3130. }
  3131. // Unsure if this is the correct method to handle this case.
  3132. return undefined;
  3133. }
  3134. var t = - ( startPoint.dot( this.normal ) + this.constant ) / denominator;
  3135. if( t < 0 || t > 1 ) {
  3136. return undefined;
  3137. }
  3138. return result.copy( direction ).multiplyScalar( t ).add( startPoint );
  3139. };
  3140. }(),
  3141. coplanarPoint: function ( optionalTarget ) {
  3142. var result = optionalTarget || new THREE.Vector3();
  3143. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3144. },
  3145. transform: function() {
  3146. var v1 = new THREE.Vector3();
  3147. var v2 = new THREE.Vector3();
  3148. return function ( matrix, optionalNormalMatrix ) {
  3149. // compute new normal based on theory here:
  3150. // http://www.songho.ca/opengl/gl_normaltransform.html
  3151. optionalNormalMatrix = optionalNormalMatrix || new THREE.Matrix3().getInverse( matrix ).transpose();
  3152. var newNormal = v1.copy( this.normal ).applyMatrix3( optionalNormalMatrix );
  3153. var newCoplanarPoint = this.coplanarPoint( v2 );
  3154. newCoplanarPoint.applyMatrix4( matrix );
  3155. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3156. return this;
  3157. };
  3158. }(),
  3159. translate: function ( offset ) {
  3160. this.constant = this.constant - offset.dot( this.normal );
  3161. return this;
  3162. },
  3163. equals: function ( plane ) {
  3164. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3165. },
  3166. clone: function () {
  3167. return new THREE.Plane().copy( this );
  3168. }
  3169. } );
  3170. /**
  3171. * @author alteredq / http://alteredqualia.com/
  3172. */
  3173. THREE.Math = {
  3174. // Clamp value to range <a, b>
  3175. clamp: function ( x, a, b ) {
  3176. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3177. },
  3178. // Clamp value to range <a, inf)
  3179. clampBottom: function ( x, a ) {
  3180. return x < a ? a : x;
  3181. },
  3182. // Linear mapping from range <a1, a2> to range <b1, b2>
  3183. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3184. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3185. },
  3186. // Random float from <0, 1> with 16 bits of randomness
  3187. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3188. random16: function () {
  3189. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3190. },
  3191. // Random integer from <low, high> interval
  3192. randInt: function ( low, high ) {
  3193. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  3194. },
  3195. // Random float from <low, high> interval
  3196. randFloat: function ( low, high ) {
  3197. return low + Math.random() * ( high - low );
  3198. },
  3199. // Random float from <-range/2, range/2> interval
  3200. randFloatSpread: function ( range ) {
  3201. return range * ( 0.5 - Math.random() );
  3202. },
  3203. sign: function ( x ) {
  3204. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  3205. },
  3206. degToRad: function() {
  3207. var degreeToRadiansFactor = Math.PI / 180;
  3208. return function ( degrees ) {
  3209. return degrees * degreeToRadiansFactor;
  3210. };
  3211. }(),
  3212. radToDeg: function() {
  3213. var radianToDegreesFactor = 180 / Math.PI;
  3214. return function ( radians ) {
  3215. return radians * radianToDegreesFactor;
  3216. };
  3217. }()
  3218. };
  3219. /**
  3220. * Spline from Tween.js, slightly optimized (and trashed)
  3221. * http://sole.github.com/tween.js/examples/05_spline.html
  3222. *
  3223. * @author mrdoob / http://mrdoob.com/
  3224. * @author alteredq / http://alteredqualia.com/
  3225. */
  3226. THREE.Spline = function ( points ) {
  3227. this.points = points;
  3228. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3229. point, intPoint, weight, w2, w3,
  3230. pa, pb, pc, pd;
  3231. this.initFromArray = function( a ) {
  3232. this.points = [];
  3233. for ( var i = 0; i < a.length; i++ ) {
  3234. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3235. }
  3236. };
  3237. this.getPoint = function ( k ) {
  3238. point = ( this.points.length - 1 ) * k;
  3239. intPoint = Math.floor( point );
  3240. weight = point - intPoint;
  3241. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3242. c[ 1 ] = intPoint;
  3243. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3244. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3245. pa = this.points[ c[ 0 ] ];
  3246. pb = this.points[ c[ 1 ] ];
  3247. pc = this.points[ c[ 2 ] ];
  3248. pd = this.points[ c[ 3 ] ];
  3249. w2 = weight * weight;
  3250. w3 = weight * w2;
  3251. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3252. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3253. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3254. return v3;
  3255. };
  3256. this.getControlPointsArray = function () {
  3257. var i, p, l = this.points.length,
  3258. coords = [];
  3259. for ( i = 0; i < l; i ++ ) {
  3260. p = this.points[ i ];
  3261. coords[ i ] = [ p.x, p.y, p.z ];
  3262. }
  3263. return coords;
  3264. };
  3265. // approximate length by summing linear segments
  3266. this.getLength = function ( nSubDivisions ) {
  3267. var i, index, nSamples, position,
  3268. point = 0, intPoint = 0, oldIntPoint = 0,
  3269. oldPosition = new THREE.Vector3(),
  3270. tmpVec = new THREE.Vector3(),
  3271. chunkLengths = [],
  3272. totalLength = 0;
  3273. // first point has 0 length
  3274. chunkLengths[ 0 ] = 0;
  3275. if ( !nSubDivisions ) nSubDivisions = 100;
  3276. nSamples = this.points.length * nSubDivisions;
  3277. oldPosition.copy( this.points[ 0 ] );
  3278. for ( i = 1; i < nSamples; i ++ ) {
  3279. index = i / nSamples;
  3280. position = this.getPoint( index );
  3281. tmpVec.copy( position );
  3282. totalLength += tmpVec.distanceTo( oldPosition );
  3283. oldPosition.copy( position );
  3284. point = ( this.points.length - 1 ) * index;
  3285. intPoint = Math.floor( point );
  3286. if ( intPoint != oldIntPoint ) {
  3287. chunkLengths[ intPoint ] = totalLength;
  3288. oldIntPoint = intPoint;
  3289. }
  3290. }
  3291. // last point ends with total length
  3292. chunkLengths[ chunkLengths.length ] = totalLength;
  3293. return { chunks: chunkLengths, total: totalLength };
  3294. };
  3295. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3296. var i, j,
  3297. index, indexCurrent, indexNext,
  3298. linearDistance, realDistance,
  3299. sampling, position,
  3300. newpoints = [],
  3301. tmpVec = new THREE.Vector3(),
  3302. sl = this.getLength();
  3303. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3304. for ( i = 1; i < this.points.length; i++ ) {
  3305. //tmpVec.copy( this.points[ i - 1 ] );
  3306. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3307. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3308. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3309. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3310. indexNext = i / ( this.points.length - 1 );
  3311. for ( j = 1; j < sampling - 1; j++ ) {
  3312. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3313. position = this.getPoint( index );
  3314. newpoints.push( tmpVec.copy( position ).clone() );
  3315. }
  3316. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3317. }
  3318. this.points = newpoints;
  3319. };
  3320. // Catmull-Rom
  3321. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3322. var v0 = ( p2 - p0 ) * 0.5,
  3323. v1 = ( p3 - p1 ) * 0.5;
  3324. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3325. };
  3326. };
  3327. /**
  3328. * @author bhouston / http://exocortex.com
  3329. * @author mrdoob / http://mrdoob.com/
  3330. */
  3331. THREE.Triangle = function ( a, b, c ) {
  3332. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3333. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3334. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3335. };
  3336. THREE.Triangle.normal = function() {
  3337. var v0 = new THREE.Vector3();
  3338. return function( a, b, c, optionalTarget ) {
  3339. var result = optionalTarget || new THREE.Vector3();
  3340. result.subVectors( c, b );
  3341. v0.subVectors( a, b );
  3342. result.cross( v0 );
  3343. var resultLengthSq = result.lengthSq();
  3344. if( resultLengthSq > 0 ) {
  3345. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3346. }
  3347. return result.set( 0, 0, 0 );
  3348. };
  3349. }();
  3350. // static/instance method to calculate barycoordinates
  3351. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3352. THREE.Triangle.barycoordFromPoint = function() {
  3353. var v0 = new THREE.Vector3(),
  3354. v1 = new THREE.Vector3(),
  3355. v2 = new THREE.Vector3();
  3356. return function ( point, a, b, c, optionalTarget ) {
  3357. v0.subVectors( c, a );
  3358. v1.subVectors( b, a );
  3359. v2.subVectors( point, a );
  3360. var dot00 = v0.dot( v0 );
  3361. var dot01 = v0.dot( v1 );
  3362. var dot02 = v0.dot( v2 );
  3363. var dot11 = v1.dot( v1 );
  3364. var dot12 = v1.dot( v2 );
  3365. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3366. var result = optionalTarget || new THREE.Vector3();
  3367. // colinear or singular triangle
  3368. if( denom == 0 ) {
  3369. // arbitrary location outside of triangle?
  3370. // not sure if this is the best idea, maybe should be returning undefined
  3371. return result.set( -2, -1, -1 );
  3372. }
  3373. var invDenom = 1 / denom;
  3374. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3375. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3376. // barycoordinates must always sum to 1
  3377. return result.set( 1 - u - v, v, u );
  3378. };
  3379. }();
  3380. THREE.Triangle.containsPoint = function() {
  3381. var v1 = new THREE.Vector3();
  3382. return function ( point, a, b, c ) {
  3383. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  3384. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3385. };
  3386. }();
  3387. THREE.extend( THREE.Triangle.prototype, {
  3388. constructor: THREE.Triangle,
  3389. set: function ( a, b, c ) {
  3390. this.a.copy( a );
  3391. this.b.copy( b );
  3392. this.c.copy( c );
  3393. return this;
  3394. },
  3395. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3396. this.a.copy( points[i0] );
  3397. this.b.copy( points[i1] );
  3398. this.c.copy( points[i2] );
  3399. return this;
  3400. },
  3401. copy: function ( triangle ) {
  3402. this.a.copy( triangle.a );
  3403. this.b.copy( triangle.b );
  3404. this.c.copy( triangle.c );
  3405. return this;
  3406. },
  3407. area: function() {
  3408. var v0 = new THREE.Vector3();
  3409. var v1 = new THREE.Vector3();
  3410. return function () {
  3411. v0.subVectors( this.c, this.b );
  3412. v1.subVectors( this.a, this.b );
  3413. return v0.cross( v1 ).length() * 0.5;
  3414. };
  3415. }(),
  3416. midpoint: function ( optionalTarget ) {
  3417. var result = optionalTarget || new THREE.Vector3();
  3418. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  3419. },
  3420. normal: function ( optionalTarget ) {
  3421. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3422. },
  3423. plane: function ( optionalTarget ) {
  3424. var result = optionalTarget || new THREE.Plane();
  3425. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  3426. },
  3427. barycoordFromPoint: function ( point, optionalTarget ) {
  3428. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  3429. },
  3430. containsPoint: function ( point ) {
  3431. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  3432. },
  3433. equals: function ( triangle ) {
  3434. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  3435. },
  3436. clone: function () {
  3437. return new THREE.Triangle().copy( this );
  3438. }
  3439. } );
  3440. /**
  3441. * @author mrdoob / http://mrdoob.com/
  3442. */
  3443. THREE.Vertex = function ( v ) {
  3444. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  3445. return v;
  3446. };
  3447. /**
  3448. * @author mrdoob / http://mrdoob.com/
  3449. */
  3450. THREE.UV = function ( u, v ) {
  3451. console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
  3452. return new THREE.Vector2( u, v );
  3453. };
  3454. /**
  3455. * @author alteredq / http://alteredqualia.com/
  3456. */
  3457. THREE.Clock = function ( autoStart ) {
  3458. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  3459. this.startTime = 0;
  3460. this.oldTime = 0;
  3461. this.elapsedTime = 0;
  3462. this.running = false;
  3463. };
  3464. THREE.extend( THREE.Clock.prototype, {
  3465. start: function () {
  3466. this.startTime = window.performance !== undefined && window.performance.now !== undefined
  3467. ? window.performance.now()
  3468. : Date.now();
  3469. this.oldTime = this.startTime;
  3470. this.running = true;
  3471. },
  3472. stop: function () {
  3473. this.getElapsedTime();
  3474. this.running = false;
  3475. },
  3476. getElapsedTime: function () {
  3477. this.getDelta();
  3478. return this.elapsedTime;
  3479. },
  3480. getDelta: function () {
  3481. var diff = 0;
  3482. if ( this.autoStart && ! this.running ) {
  3483. this.start();
  3484. }
  3485. if ( this.running ) {
  3486. var newTime = window.performance !== undefined && window.performance.now !== undefined
  3487. ? window.performance.now()
  3488. : Date.now();
  3489. diff = 0.001 * ( newTime - this.oldTime );
  3490. this.oldTime = newTime;
  3491. this.elapsedTime += diff;
  3492. }
  3493. return diff;
  3494. }
  3495. } );
  3496. /**
  3497. * https://github.com/mrdoob/eventdispatcher.js/
  3498. */
  3499. THREE.EventDispatcher = function () {
  3500. var listeners = {};
  3501. this.addEventListener = function ( type, listener ) {
  3502. if ( listeners[ type ] === undefined ) {
  3503. listeners[ type ] = [];
  3504. }
  3505. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  3506. listeners[ type ].push( listener );
  3507. }
  3508. };
  3509. this.removeEventListener = function ( type, listener ) {
  3510. var index = listeners[ type ].indexOf( listener );
  3511. if ( index !== - 1 ) {
  3512. listeners[ type ].splice( index, 1 );
  3513. }
  3514. };
  3515. this.dispatchEvent = function ( event ) {
  3516. var listenerArray = listeners[ event.type ];
  3517. if ( listenerArray !== undefined ) {
  3518. event.target = this;
  3519. for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
  3520. listenerArray[ i ].call( this, event );
  3521. }
  3522. }
  3523. };
  3524. };
  3525. /**
  3526. * @author mrdoob / http://mrdoob.com/
  3527. * @author bhouston / http://exocortex.com/
  3528. */
  3529. ( function ( THREE ) {
  3530. THREE.Raycaster = function ( origin, direction, near, far ) {
  3531. this.ray = new THREE.Ray( origin, direction );
  3532. // normalized ray.direction required for accurate distance calculations
  3533. if( this.ray.direction.lengthSq() > 0 ) {
  3534. this.ray.direction.normalize();
  3535. }
  3536. this.near = near || 0;
  3537. this.far = far || Infinity;
  3538. };
  3539. var sphere = new THREE.Sphere();
  3540. var localRay = new THREE.Ray();
  3541. var facePlane = new THREE.Plane();
  3542. var intersectPoint = new THREE.Vector3();
  3543. var inverseMatrix = new THREE.Matrix4();
  3544. var descSort = function ( a, b ) {
  3545. return a.distance - b.distance;
  3546. };
  3547. var intersectObject = function ( object, raycaster, intersects ) {
  3548. if ( object instanceof THREE.Particle ) {
  3549. var distance = raycaster.ray.distanceToPoint( object.matrixWorld.getPosition() );
  3550. if ( distance > object.scale.x ) {
  3551. return intersects;
  3552. }
  3553. intersects.push( {
  3554. distance: distance,
  3555. point: object.position,
  3556. face: null,
  3557. object: object
  3558. } );
  3559. } else if ( object instanceof THREE.Mesh ) {
  3560. // Checking boundingSphere distance to ray
  3561. sphere.set(
  3562. object.matrixWorld.getPosition(),
  3563. object.geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis() );
  3564. if ( ! raycaster.ray.isIntersectionSphere( sphere ) ) {
  3565. return intersects;
  3566. }
  3567. // Checking faces
  3568. var geometry = object.geometry;
  3569. var vertices = geometry.vertices;
  3570. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3571. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  3572. var side = object.material.side;
  3573. var a, b, c, d;
  3574. var precision = raycaster.precision;
  3575. object.matrixRotationWorld.extractRotation( object.matrixWorld );
  3576. inverseMatrix.getInverse( object.matrixWorld );
  3577. localRay.copy( raycaster.ray ).transform( inverseMatrix );
  3578. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  3579. var face = geometry.faces[ f ];
  3580. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  3581. if ( material === undefined ) continue;
  3582. facePlane.setFromNormalAndCoplanarPoint( face.normal, vertices[face.a] );
  3583. var planeDistance = localRay.distanceToPlane( facePlane );
  3584. // bail if raycaster and plane are parallel
  3585. if ( Math.abs( planeDistance ) < precision ) continue;
  3586. // if negative distance, then plane is behind raycaster
  3587. if ( planeDistance < 0 ) continue;
  3588. // check if we hit the wrong side of a single sided face
  3589. side = material.side;
  3590. if( side !== THREE.DoubleSide ) {
  3591. var planeSign = localRay.direction.dot( facePlane.normal );
  3592. if( ! ( side === THREE.FrontSide ? planeSign < 0 : planeSign > 0 ) ) continue;
  3593. }
  3594. // this can be done using the planeDistance from localRay because localRay wasn't normalized, but ray was
  3595. if ( planeDistance < raycaster.near || planeDistance > raycaster.far ) continue;
  3596. intersectPoint = localRay.at( planeDistance, intersectPoint ); // passing in intersectPoint avoids a copy
  3597. if ( face instanceof THREE.Face3 ) {
  3598. a = vertices[ face.a ];
  3599. b = vertices[ face.b ];
  3600. c = vertices[ face.c ];
  3601. if ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, c ) ) continue;
  3602. } else if ( face instanceof THREE.Face4 ) {
  3603. a = vertices[ face.a ];
  3604. b = vertices[ face.b ];
  3605. c = vertices[ face.c ];
  3606. d = vertices[ face.d ];
  3607. if ( ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, d ) ) &&
  3608. ( ! THREE.Triangle.containsPoint( intersectPoint, b, c, d ) ) ) continue;
  3609. } else {
  3610. // This is added because if we call out of this if/else group when none of the cases
  3611. // match it will add a point to the intersection list erroneously.
  3612. throw Error( "face type not supported" );
  3613. }
  3614. intersects.push( {
  3615. distance: planeDistance, // this works because the original ray was normalized, and the transformed localRay wasn't
  3616. point: raycaster.ray.at( planeDistance ),
  3617. face: face,
  3618. faceIndex: f,
  3619. object: object
  3620. } );
  3621. }
  3622. }
  3623. };
  3624. var intersectDescendants = function ( object, raycaster, intersects ) {
  3625. var descendants = object.getDescendants();
  3626. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  3627. intersectObject( descendants[ i ], raycaster, intersects );
  3628. }
  3629. };
  3630. //
  3631. THREE.Raycaster.prototype.precision = 0.0001;
  3632. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  3633. this.ray.set( origin, direction );
  3634. // normalized ray.direction required for accurate distance calculations
  3635. if( this.ray.direction.length() > 0 ) {
  3636. this.ray.direction.normalize();
  3637. }
  3638. };
  3639. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  3640. var intersects = [];
  3641. if ( recursive === true ) {
  3642. intersectDescendants( object, this, intersects );
  3643. }
  3644. intersectObject( object, this, intersects );
  3645. intersects.sort( descSort );
  3646. return intersects;
  3647. };
  3648. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  3649. var intersects = [];
  3650. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  3651. intersectObject( objects[ i ], this, intersects );
  3652. if ( recursive === true ) {
  3653. intersectDescendants( objects[ i ], this, intersects );
  3654. }
  3655. }
  3656. intersects.sort( descSort );
  3657. return intersects;
  3658. };
  3659. }( THREE ) );
  3660. /**
  3661. * @author mrdoob / http://mrdoob.com/
  3662. * @author mikael emtinger / http://gomo.se/
  3663. * @author alteredq / http://alteredqualia.com/
  3664. */
  3665. THREE.Object3D = function () {
  3666. this.id = THREE.Object3DIdCount ++;
  3667. this.name = '';
  3668. this.properties = {};
  3669. this.parent = undefined;
  3670. this.children = [];
  3671. this.up = new THREE.Vector3( 0, 1, 0 );
  3672. this.position = new THREE.Vector3();
  3673. this.rotation = new THREE.Vector3();
  3674. this.eulerOrder = THREE.Object3D.defaultEulerOrder;
  3675. this.scale = new THREE.Vector3( 1, 1, 1 );
  3676. this.renderDepth = null;
  3677. this.rotationAutoUpdate = true;
  3678. this.matrix = new THREE.Matrix4();
  3679. this.matrixWorld = new THREE.Matrix4();
  3680. this.matrixRotationWorld = new THREE.Matrix4();
  3681. this.matrixAutoUpdate = true;
  3682. this.matrixWorldNeedsUpdate = true;
  3683. this.quaternion = new THREE.Quaternion();
  3684. this.useQuaternion = false;
  3685. this.visible = true;
  3686. this.castShadow = false;
  3687. this.receiveShadow = false;
  3688. this.frustumCulled = true;
  3689. this._vector = new THREE.Vector3();
  3690. };
  3691. THREE.Object3D.prototype = {
  3692. constructor: THREE.Object3D,
  3693. applyMatrix: function ( matrix ) {
  3694. this.matrix.multiplyMatrices( matrix, this.matrix );
  3695. this.scale.getScaleFromMatrix( this.matrix );
  3696. var mat = new THREE.Matrix4().extractRotation( this.matrix );
  3697. this.rotation.setEulerFromRotationMatrix( mat, this.eulerOrder );
  3698. this.position.getPositionFromMatrix( this.matrix );
  3699. },
  3700. translate: function ( distance, axis ) {
  3701. this.matrix.rotateAxis( axis );
  3702. this.position.add( axis.multiplyScalar( distance ) );
  3703. },
  3704. translateX: function ( distance ) {
  3705. this.translate( distance, this._vector.set( 1, 0, 0 ) );
  3706. },
  3707. translateY: function ( distance ) {
  3708. this.translate( distance, this._vector.set( 0, 1, 0 ) );
  3709. },
  3710. translateZ: function ( distance ) {
  3711. this.translate( distance, this._vector.set( 0, 0, 1 ) );
  3712. },
  3713. localToWorld: function ( vector ) {
  3714. return vector.applyMatrix4( this.matrixWorld );
  3715. },
  3716. worldToLocal: function ( vector ) {
  3717. return vector.applyMatrix4( THREE.Object3D.__m1.getInverse( this.matrixWorld ) );
  3718. },
  3719. lookAt: function ( vector ) {
  3720. // TODO: Add hierarchy support.
  3721. this.matrix.lookAt( vector, this.position, this.up );
  3722. if ( this.rotationAutoUpdate ) {
  3723. if ( this.useQuaternion === false ) {
  3724. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  3725. } else {
  3726. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  3727. }
  3728. }
  3729. },
  3730. add: function ( object ) {
  3731. if ( object === this ) {
  3732. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  3733. return;
  3734. }
  3735. if ( object instanceof THREE.Object3D ) {
  3736. if ( object.parent !== undefined ) {
  3737. object.parent.remove( object );
  3738. }
  3739. object.parent = this;
  3740. this.children.push( object );
  3741. // add to scene
  3742. var scene = this;
  3743. while ( scene.parent !== undefined ) {
  3744. scene = scene.parent;
  3745. }
  3746. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  3747. scene.__addObject( object );
  3748. }
  3749. }
  3750. },
  3751. remove: function ( object ) {
  3752. var index = this.children.indexOf( object );
  3753. if ( index !== - 1 ) {
  3754. object.parent = undefined;
  3755. this.children.splice( index, 1 );
  3756. // remove from scene
  3757. var scene = this;
  3758. while ( scene.parent !== undefined ) {
  3759. scene = scene.parent;
  3760. }
  3761. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  3762. scene.__removeObject( object );
  3763. }
  3764. }
  3765. },
  3766. traverse: function ( callback ) {
  3767. callback( this );
  3768. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3769. this.children[ i ].traverse( callback );
  3770. }
  3771. },
  3772. getChildByName: function ( name, recursive ) {
  3773. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3774. var child = this.children[ i ];
  3775. if ( child.name === name ) {
  3776. return child;
  3777. }
  3778. if ( recursive === true ) {
  3779. child = child.getChildByName( name, recursive );
  3780. if ( child !== undefined ) {
  3781. return child;
  3782. }
  3783. }
  3784. }
  3785. return undefined;
  3786. },
  3787. getDescendants: function ( array ) {
  3788. if ( array === undefined ) array = [];
  3789. Array.prototype.push.apply( array, this.children );
  3790. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3791. this.children[ i ].getDescendants( array );
  3792. }
  3793. return array;
  3794. },
  3795. updateMatrix: function () {
  3796. this.matrix.setPosition( this.position );
  3797. if ( this.useQuaternion === false ) {
  3798. this.matrix.setRotationFromEuler( this.rotation, this.eulerOrder );
  3799. } else {
  3800. this.matrix.setRotationFromQuaternion( this.quaternion );
  3801. }
  3802. if ( this.scale.x !== 1 || this.scale.y !== 1 || this.scale.z !== 1 ) {
  3803. this.matrix.scale( this.scale );
  3804. }
  3805. this.matrixWorldNeedsUpdate = true;
  3806. },
  3807. updateMatrixWorld: function ( force ) {
  3808. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  3809. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  3810. if ( this.parent === undefined ) {
  3811. this.matrixWorld.copy( this.matrix );
  3812. } else {
  3813. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  3814. }
  3815. this.matrixWorldNeedsUpdate = false;
  3816. force = true;
  3817. }
  3818. // update children
  3819. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3820. this.children[ i ].updateMatrixWorld( force );
  3821. }
  3822. },
  3823. clone: function ( object ) {
  3824. if ( object === undefined ) object = new THREE.Object3D();
  3825. object.name = this.name;
  3826. object.up.copy( this.up );
  3827. object.position.copy( this.position );
  3828. if ( object.rotation instanceof THREE.Vector3 ) object.rotation.copy( this.rotation ); // because of Sprite madness
  3829. object.eulerOrder = this.eulerOrder;
  3830. object.scale.copy( this.scale );
  3831. object.renderDepth = this.renderDepth;
  3832. object.rotationAutoUpdate = this.rotationAutoUpdate;
  3833. object.matrix.copy( this.matrix );
  3834. object.matrixWorld.copy( this.matrixWorld );
  3835. object.matrixRotationWorld.copy( this.matrixRotationWorld );
  3836. object.matrixAutoUpdate = this.matrixAutoUpdate;
  3837. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  3838. object.quaternion.copy( this.quaternion );
  3839. object.useQuaternion = this.useQuaternion;
  3840. object.visible = this.visible;
  3841. object.castShadow = this.castShadow;
  3842. object.receiveShadow = this.receiveShadow;
  3843. object.frustumCulled = this.frustumCulled;
  3844. for ( var i = 0; i < this.children.length; i ++ ) {
  3845. var child = this.children[ i ];
  3846. object.add( child.clone() );
  3847. }
  3848. return object;
  3849. }
  3850. };
  3851. THREE.Object3D.__m1 = new THREE.Matrix4();
  3852. THREE.Object3D.defaultEulerOrder = 'XYZ',
  3853. THREE.Object3DIdCount = 0;
  3854. /**
  3855. * @author mrdoob / http://mrdoob.com/
  3856. * @author supereggbert / http://www.paulbrunt.co.uk/
  3857. * @author julianwa / https://github.com/julianwa
  3858. */
  3859. THREE.Projector = function () {
  3860. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  3861. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  3862. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  3863. _face4Count, _face4Pool = [], _face4PoolLength = 0,
  3864. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  3865. _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
  3866. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  3867. _vector3 = new THREE.Vector3(),
  3868. _vector4 = new THREE.Vector4(),
  3869. _clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ),
  3870. _boundingBox = new THREE.Box3(),
  3871. _points3 = new Array( 3 ),
  3872. _points4 = new Array( 4 ),
  3873. _viewMatrix = new THREE.Matrix4(),
  3874. _viewProjectionMatrix = new THREE.Matrix4(),
  3875. _modelMatrix,
  3876. _modelViewProjectionMatrix = new THREE.Matrix4(),
  3877. _normalMatrix = new THREE.Matrix3(),
  3878. _normalViewMatrix = new THREE.Matrix3(),
  3879. _centroid = new THREE.Vector3(),
  3880. _frustum = new THREE.Frustum(),
  3881. _clippedVertex1PositionScreen = new THREE.Vector4(),
  3882. _clippedVertex2PositionScreen = new THREE.Vector4(),
  3883. _face3VertexNormals;
  3884. this.projectVector = function ( vector, camera ) {
  3885. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  3886. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  3887. return vector.applyProjection( _viewProjectionMatrix );
  3888. };
  3889. this.unprojectVector = function ( vector, camera ) {
  3890. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  3891. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, camera.projectionMatrixInverse );
  3892. return vector.applyProjection( _viewProjectionMatrix );
  3893. };
  3894. this.pickingRay = function ( vector, camera ) {
  3895. // set two vectors with opposing z values
  3896. vector.z = -1.0;
  3897. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  3898. this.unprojectVector( vector, camera );
  3899. this.unprojectVector( end, camera );
  3900. // find direction from vector to end
  3901. end.sub( vector ).normalize();
  3902. return new THREE.Raycaster( vector, end );
  3903. };
  3904. var projectGraph = function ( root, sortObjects ) {
  3905. _objectCount = 0;
  3906. _renderData.objects.length = 0;
  3907. _renderData.sprites.length = 0;
  3908. _renderData.lights.length = 0;
  3909. var projectObject = function ( parent ) {
  3910. for ( var c = 0, cl = parent.children.length; c < cl; c ++ ) {
  3911. var object = parent.children[ c ];
  3912. if ( object.visible === false ) continue;
  3913. if ( object instanceof THREE.Light ) {
  3914. _renderData.lights.push( object );
  3915. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  3916. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  3917. _object = getNextObjectInPool();
  3918. _object.object = object;
  3919. if ( object.renderDepth !== null ) {
  3920. _object.z = object.renderDepth;
  3921. } else {
  3922. _vector3.getPositionFromMatrix( object.matrixWorld );
  3923. _vector3.applyProjection( _viewProjectionMatrix );
  3924. _object.z = _vector3.z;
  3925. }
  3926. _renderData.objects.push( _object );
  3927. }
  3928. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  3929. _object = getNextObjectInPool();
  3930. _object.object = object;
  3931. // TODO: Find an elegant and performant solution and remove this dupe code.
  3932. if ( object.renderDepth !== null ) {
  3933. _object.z = object.renderDepth;
  3934. } else {
  3935. _vector3.getPositionFromMatrix( object.matrixWorld );
  3936. _vector3.applyProjection( _viewProjectionMatrix );
  3937. _object.z = _vector3.z;
  3938. }
  3939. _renderData.sprites.push( _object );
  3940. } else {
  3941. _object = getNextObjectInPool();
  3942. _object.object = object;
  3943. if ( object.renderDepth !== null ) {
  3944. _object.z = object.renderDepth;
  3945. } else {
  3946. _vector3.getPositionFromMatrix( object.matrixWorld );
  3947. _vector3.applyProjection( _viewProjectionMatrix );
  3948. _object.z = _vector3.z;
  3949. }
  3950. _renderData.objects.push( _object );
  3951. }
  3952. projectObject( object );
  3953. }
  3954. };
  3955. projectObject( root );
  3956. if ( sortObjects === true ) _renderData.objects.sort( painterSort );
  3957. return _renderData;
  3958. };
  3959. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  3960. var visible = false,
  3961. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  3962. geometry, vertices, vertex, vertexPositionScreen,
  3963. faces, face, faceVertexNormals, faceVertexUvs, uvs,
  3964. v1, v2, v3, v4, isFaceMaterial, objectMaterials;
  3965. _face3Count = 0;
  3966. _face4Count = 0;
  3967. _lineCount = 0;
  3968. _particleCount = 0;
  3969. _renderData.elements.length = 0;
  3970. scene.updateMatrixWorld();
  3971. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  3972. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  3973. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  3974. _normalViewMatrix.getInverse( _viewMatrix );
  3975. _normalViewMatrix.transpose();
  3976. _frustum.setFromMatrix( _viewProjectionMatrix );
  3977. _renderData = projectGraph( scene, sortObjects );
  3978. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  3979. object = _renderData.objects[ o ].object;
  3980. _modelMatrix = object.matrixWorld;
  3981. _vertexCount = 0;
  3982. if ( object instanceof THREE.Mesh ) {
  3983. geometry = object.geometry;
  3984. vertices = geometry.vertices;
  3985. faces = geometry.faces;
  3986. faceVertexUvs = geometry.faceVertexUvs;
  3987. _normalMatrix.getInverse( _modelMatrix );
  3988. _normalMatrix.transpose();
  3989. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3990. objectMaterials = isFaceMaterial === true ? object.material : null;
  3991. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  3992. _vertex = getNextVertexInPool();
  3993. _vertex.positionWorld.copy( vertices[ v ] ).applyMatrix4( _modelMatrix );
  3994. _vertex.positionScreen.copy( _vertex.positionWorld ).applyMatrix4( _viewProjectionMatrix );
  3995. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  3996. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  3997. _vertex.positionScreen.z /= _vertex.positionScreen.w;
  3998. _vertex.visible = ! ( _vertex.positionScreen.x < -1 || _vertex.positionScreen.x > 1 ||
  3999. _vertex.positionScreen.y < -1 || _vertex.positionScreen.y > 1 ||
  4000. _vertex.positionScreen.z < -1 || _vertex.positionScreen.z > 1 );
  4001. }
  4002. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  4003. face = faces[ f ];
  4004. var material = isFaceMaterial === true
  4005. ? objectMaterials.materials[ face.materialIndex ]
  4006. : object.material;
  4007. if ( material === undefined ) continue;
  4008. var side = material.side;
  4009. if ( face instanceof THREE.Face3 ) {
  4010. v1 = _vertexPool[ face.a ];
  4011. v2 = _vertexPool[ face.b ];
  4012. v3 = _vertexPool[ face.c ];
  4013. _points3[ 0 ] = v1.positionScreen;
  4014. _points3[ 1 ] = v2.positionScreen;
  4015. _points3[ 2 ] = v3.positionScreen;
  4016. if ( v1.visible === true || v2.visible === true || v3.visible === true ||
  4017. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) ) ) {
  4018. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  4019. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  4020. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  4021. _face = getNextFace3InPool();
  4022. _face.v1.copy( v1 );
  4023. _face.v2.copy( v2 );
  4024. _face.v3.copy( v3 );
  4025. } else {
  4026. continue;
  4027. }
  4028. } else {
  4029. continue;
  4030. }
  4031. } else if ( face instanceof THREE.Face4 ) {
  4032. v1 = _vertexPool[ face.a ];
  4033. v2 = _vertexPool[ face.b ];
  4034. v3 = _vertexPool[ face.c ];
  4035. v4 = _vertexPool[ face.d ];
  4036. _points4[ 0 ] = v1.positionScreen;
  4037. _points4[ 1 ] = v2.positionScreen;
  4038. _points4[ 2 ] = v3.positionScreen;
  4039. _points4[ 3 ] = v4.positionScreen;
  4040. if ( v1.visible === true || v2.visible === true || v3.visible === true || v4.visible === true ||
  4041. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points4 ) ) ) {
  4042. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  4043. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  4044. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  4045. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  4046. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  4047. _face = getNextFace4InPool();
  4048. _face.v1.copy( v1 );
  4049. _face.v2.copy( v2 );
  4050. _face.v3.copy( v3 );
  4051. _face.v4.copy( v4 );
  4052. } else {
  4053. continue;
  4054. }
  4055. } else {
  4056. continue;
  4057. }
  4058. }
  4059. _face.normalModel.copy( face.normal );
  4060. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4061. _face.normalModel.negate();
  4062. }
  4063. _face.normalModel.applyMatrix3( _normalMatrix ).normalize();
  4064. _face.normalModelView.copy( _face.normalModel ).applyMatrix3( _normalViewMatrix );
  4065. _face.centroidModel.copy( face.centroid ).applyMatrix4( _modelMatrix );
  4066. faceVertexNormals = face.vertexNormals;
  4067. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  4068. var normalModel = _face.vertexNormalsModel[ n ];
  4069. normalModel.copy( faceVertexNormals[ n ] );
  4070. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4071. normalModel.negate();
  4072. }
  4073. normalModel.applyMatrix3( _normalMatrix ).normalize();
  4074. var normalModelView = _face.vertexNormalsModelView[ n ];
  4075. normalModelView.copy( normalModel ).applyMatrix3( _normalViewMatrix );
  4076. }
  4077. _face.vertexNormalsLength = faceVertexNormals.length;
  4078. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  4079. uvs = faceVertexUvs[ c ][ f ];
  4080. if ( uvs === undefined ) continue;
  4081. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  4082. _face.uvs[ c ][ u ] = uvs[ u ];
  4083. }
  4084. }
  4085. _face.color = face.color;
  4086. _face.material = material;
  4087. _centroid.copy( _face.centroidModel ).applyProjection( _viewProjectionMatrix );
  4088. _face.z = _centroid.z;
  4089. _renderData.elements.push( _face );
  4090. }
  4091. } else if ( object instanceof THREE.Line ) {
  4092. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  4093. vertices = object.geometry.vertices;
  4094. v1 = getNextVertexInPool();
  4095. v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
  4096. // Handle LineStrip and LinePieces
  4097. var step = object.type === THREE.LinePieces ? 2 : 1;
  4098. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  4099. v1 = getNextVertexInPool();
  4100. v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
  4101. if ( ( v + 1 ) % step > 0 ) continue;
  4102. v2 = _vertexPool[ _vertexCount - 2 ];
  4103. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  4104. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  4105. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  4106. // Perform the perspective divide
  4107. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  4108. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  4109. _line = getNextLineInPool();
  4110. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  4111. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  4112. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  4113. _line.material = object.material;
  4114. _renderData.elements.push( _line );
  4115. }
  4116. }
  4117. }
  4118. }
  4119. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  4120. object = _renderData.sprites[ o ].object;
  4121. _modelMatrix = object.matrixWorld;
  4122. if ( object instanceof THREE.Particle ) {
  4123. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  4124. _vector4.applyMatrix4( _viewProjectionMatrix );
  4125. _vector4.z /= _vector4.w;
  4126. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  4127. _particle = getNextParticleInPool();
  4128. _particle.object = object;
  4129. _particle.x = _vector4.x / _vector4.w;
  4130. _particle.y = _vector4.y / _vector4.w;
  4131. _particle.z = _vector4.z;
  4132. _particle.rotation = object.rotation.z;
  4133. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  4134. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  4135. _particle.material = object.material;
  4136. _renderData.elements.push( _particle );
  4137. }
  4138. }
  4139. }
  4140. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  4141. return _renderData;
  4142. };
  4143. // Pools
  4144. function getNextObjectInPool() {
  4145. if ( _objectCount === _objectPoolLength ) {
  4146. var object = new THREE.RenderableObject();
  4147. _objectPool.push( object );
  4148. _objectPoolLength ++;
  4149. _objectCount ++;
  4150. return object;
  4151. }
  4152. return _objectPool[ _objectCount ++ ];
  4153. }
  4154. function getNextVertexInPool() {
  4155. if ( _vertexCount === _vertexPoolLength ) {
  4156. var vertex = new THREE.RenderableVertex();
  4157. _vertexPool.push( vertex );
  4158. _vertexPoolLength ++;
  4159. _vertexCount ++;
  4160. return vertex;
  4161. }
  4162. return _vertexPool[ _vertexCount ++ ];
  4163. }
  4164. function getNextFace3InPool() {
  4165. if ( _face3Count === _face3PoolLength ) {
  4166. var face = new THREE.RenderableFace3();
  4167. _face3Pool.push( face );
  4168. _face3PoolLength ++;
  4169. _face3Count ++;
  4170. return face;
  4171. }
  4172. return _face3Pool[ _face3Count ++ ];
  4173. }
  4174. function getNextFace4InPool() {
  4175. if ( _face4Count === _face4PoolLength ) {
  4176. var face = new THREE.RenderableFace4();
  4177. _face4Pool.push( face );
  4178. _face4PoolLength ++;
  4179. _face4Count ++;
  4180. return face;
  4181. }
  4182. return _face4Pool[ _face4Count ++ ];
  4183. }
  4184. function getNextLineInPool() {
  4185. if ( _lineCount === _linePoolLength ) {
  4186. var line = new THREE.RenderableLine();
  4187. _linePool.push( line );
  4188. _linePoolLength ++;
  4189. _lineCount ++
  4190. return line;
  4191. }
  4192. return _linePool[ _lineCount ++ ];
  4193. }
  4194. function getNextParticleInPool() {
  4195. if ( _particleCount === _particlePoolLength ) {
  4196. var particle = new THREE.RenderableParticle();
  4197. _particlePool.push( particle );
  4198. _particlePoolLength ++;
  4199. _particleCount ++
  4200. return particle;
  4201. }
  4202. return _particlePool[ _particleCount ++ ];
  4203. }
  4204. //
  4205. function painterSort( a, b ) {
  4206. return b.z - a.z;
  4207. }
  4208. function clipLine( s1, s2 ) {
  4209. var alpha1 = 0, alpha2 = 1,
  4210. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  4211. // Z = -1 and Z = +1, respectively.
  4212. bc1near = s1.z + s1.w,
  4213. bc2near = s2.z + s2.w,
  4214. bc1far = - s1.z + s1.w,
  4215. bc2far = - s2.z + s2.w;
  4216. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  4217. // Both vertices lie entirely within all clip planes.
  4218. return true;
  4219. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  4220. // Both vertices lie entirely outside one of the clip planes.
  4221. return false;
  4222. } else {
  4223. // The line segment spans at least one clip plane.
  4224. if ( bc1near < 0 ) {
  4225. // v1 lies outside the near plane, v2 inside
  4226. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  4227. } else if ( bc2near < 0 ) {
  4228. // v2 lies outside the near plane, v1 inside
  4229. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  4230. }
  4231. if ( bc1far < 0 ) {
  4232. // v1 lies outside the far plane, v2 inside
  4233. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  4234. } else if ( bc2far < 0 ) {
  4235. // v2 lies outside the far plane, v2 inside
  4236. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  4237. }
  4238. if ( alpha2 < alpha1 ) {
  4239. // The line segment spans two boundaries, but is outside both of them.
  4240. // (This can't happen when we're only clipping against just near/far but good
  4241. // to leave the check here for future usage if other clip planes are added.)
  4242. return false;
  4243. } else {
  4244. // Update the s1 and s2 vertices to match the clipped line segment.
  4245. s1.lerp( s2, alpha1 );
  4246. s2.lerp( s1, 1 - alpha2 );
  4247. return true;
  4248. }
  4249. }
  4250. }
  4251. };
  4252. /**
  4253. * @author mrdoob / http://mrdoob.com/
  4254. * @author alteredq / http://alteredqualia.com/
  4255. */
  4256. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  4257. this.a = a;
  4258. this.b = b;
  4259. this.c = c;
  4260. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4261. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4262. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4263. this.vertexColors = color instanceof Array ? color : [];
  4264. this.vertexTangents = [];
  4265. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4266. this.centroid = new THREE.Vector3();
  4267. };
  4268. THREE.Face3.prototype = {
  4269. constructor: THREE.Face3,
  4270. clone: function () {
  4271. var face = new THREE.Face3( this.a, this.b, this.c );
  4272. face.normal.copy( this.normal );
  4273. face.color.copy( this.color );
  4274. face.centroid.copy( this.centroid );
  4275. face.materialIndex = this.materialIndex;
  4276. var i, il;
  4277. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4278. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4279. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4280. return face;
  4281. }
  4282. };
  4283. /**
  4284. * @author mrdoob / http://mrdoob.com/
  4285. * @author alteredq / http://alteredqualia.com/
  4286. */
  4287. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  4288. this.a = a;
  4289. this.b = b;
  4290. this.c = c;
  4291. this.d = d;
  4292. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4293. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4294. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4295. this.vertexColors = color instanceof Array ? color : [];
  4296. this.vertexTangents = [];
  4297. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4298. this.centroid = new THREE.Vector3();
  4299. };
  4300. THREE.Face4.prototype = {
  4301. constructor: THREE.Face4,
  4302. clone: function () {
  4303. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  4304. face.normal.copy( this.normal );
  4305. face.color.copy( this.color );
  4306. face.centroid.copy( this.centroid );
  4307. face.materialIndex = this.materialIndex;
  4308. var i, il;
  4309. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4310. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4311. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4312. return face;
  4313. }
  4314. };
  4315. /**
  4316. * @author mrdoob / http://mrdoob.com/
  4317. * @author kile / http://kile.stravaganza.org/
  4318. * @author alteredq / http://alteredqualia.com/
  4319. * @author mikael emtinger / http://gomo.se/
  4320. * @author zz85 / http://www.lab4games.net/zz85/blog
  4321. * @author bhouston / http://exocortex.com
  4322. */
  4323. THREE.Geometry = function () {
  4324. THREE.EventDispatcher.call( this );
  4325. this.id = THREE.GeometryIdCount ++;
  4326. this.name = '';
  4327. this.vertices = [];
  4328. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  4329. this.normals = []; // one-to-one vertex normals, used in Ribbon
  4330. this.faces = [];
  4331. this.faceUvs = [[]];
  4332. this.faceVertexUvs = [[]];
  4333. this.morphTargets = [];
  4334. this.morphColors = [];
  4335. this.morphNormals = [];
  4336. this.skinWeights = [];
  4337. this.skinIndices = [];
  4338. this.lineDistances = [];
  4339. this.boundingBox = null;
  4340. this.boundingSphere = null;
  4341. this.hasTangents = false;
  4342. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  4343. // update flags
  4344. this.verticesNeedUpdate = false;
  4345. this.elementsNeedUpdate = false;
  4346. this.uvsNeedUpdate = false;
  4347. this.normalsNeedUpdate = false;
  4348. this.tangentsNeedUpdate = false;
  4349. this.colorsNeedUpdate = false;
  4350. this.lineDistancesNeedUpdate = false;
  4351. this.buffersNeedUpdate = false;
  4352. };
  4353. THREE.Geometry.prototype = {
  4354. constructor: THREE.Geometry,
  4355. applyMatrix: function ( matrix ) {
  4356. var normalMatrix = new THREE.Matrix3().getInverse( matrix ).transpose();
  4357. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  4358. var vertex = this.vertices[ i ];
  4359. vertex.applyMatrix4( matrix );
  4360. }
  4361. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  4362. var face = this.faces[ i ];
  4363. face.normal.applyMatrix3( normalMatrix ).normalize();
  4364. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  4365. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  4366. }
  4367. face.centroid.applyMatrix4( matrix );
  4368. }
  4369. },
  4370. computeCentroids: function () {
  4371. var f, fl, face;
  4372. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4373. face = this.faces[ f ];
  4374. face.centroid.set( 0, 0, 0 );
  4375. if ( face instanceof THREE.Face3 ) {
  4376. face.centroid.add( this.vertices[ face.a ] );
  4377. face.centroid.add( this.vertices[ face.b ] );
  4378. face.centroid.add( this.vertices[ face.c ] );
  4379. face.centroid.divideScalar( 3 );
  4380. } else if ( face instanceof THREE.Face4 ) {
  4381. face.centroid.add( this.vertices[ face.a ] );
  4382. face.centroid.add( this.vertices[ face.b ] );
  4383. face.centroid.add( this.vertices[ face.c ] );
  4384. face.centroid.add( this.vertices[ face.d ] );
  4385. face.centroid.divideScalar( 4 );
  4386. }
  4387. }
  4388. },
  4389. computeFaceNormals: function () {
  4390. var n, nl, v, vl, vertex, f, fl, face, vA, vB, vC,
  4391. cb = new THREE.Vector3(), ab = new THREE.Vector3();
  4392. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4393. face = this.faces[ f ];
  4394. vA = this.vertices[ face.a ];
  4395. vB = this.vertices[ face.b ];
  4396. vC = this.vertices[ face.c ];
  4397. cb.subVectors( vC, vB );
  4398. ab.subVectors( vA, vB );
  4399. cb.cross( ab );
  4400. cb.normalize();
  4401. face.normal.copy( cb );
  4402. }
  4403. },
  4404. computeVertexNormals: function ( areaWeighted ) {
  4405. var v, vl, f, fl, face, vertices;
  4406. // create internal buffers for reuse when calling this method repeatedly
  4407. // (otherwise memory allocation / deallocation every frame is big resource hog)
  4408. if ( this.__tmpVertices === undefined ) {
  4409. this.__tmpVertices = new Array( this.vertices.length );
  4410. vertices = this.__tmpVertices;
  4411. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4412. vertices[ v ] = new THREE.Vector3();
  4413. }
  4414. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4415. face = this.faces[ f ];
  4416. if ( face instanceof THREE.Face3 ) {
  4417. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4418. } else if ( face instanceof THREE.Face4 ) {
  4419. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4420. }
  4421. }
  4422. } else {
  4423. vertices = this.__tmpVertices;
  4424. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4425. vertices[ v ].set( 0, 0, 0 );
  4426. }
  4427. }
  4428. if ( areaWeighted ) {
  4429. // vertex normals weighted by triangle areas
  4430. // http://www.iquilezles.org/www/articles/normals/normals.htm
  4431. var vA, vB, vC, vD;
  4432. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  4433. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  4434. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4435. face = this.faces[ f ];
  4436. if ( face instanceof THREE.Face3 ) {
  4437. vA = this.vertices[ face.a ];
  4438. vB = this.vertices[ face.b ];
  4439. vC = this.vertices[ face.c ];
  4440. cb.subVectors( vC, vB );
  4441. ab.subVectors( vA, vB );
  4442. cb.cross( ab );
  4443. vertices[ face.a ].add( cb );
  4444. vertices[ face.b ].add( cb );
  4445. vertices[ face.c ].add( cb );
  4446. } else if ( face instanceof THREE.Face4 ) {
  4447. vA = this.vertices[ face.a ];
  4448. vB = this.vertices[ face.b ];
  4449. vC = this.vertices[ face.c ];
  4450. vD = this.vertices[ face.d ];
  4451. // abd
  4452. db.subVectors( vD, vB );
  4453. ab.subVectors( vA, vB );
  4454. db.cross( ab );
  4455. vertices[ face.a ].add( db );
  4456. vertices[ face.b ].add( db );
  4457. vertices[ face.d ].add( db );
  4458. // bcd
  4459. dc.subVectors( vD, vC );
  4460. bc.subVectors( vB, vC );
  4461. dc.cross( bc );
  4462. vertices[ face.b ].add( dc );
  4463. vertices[ face.c ].add( dc );
  4464. vertices[ face.d ].add( dc );
  4465. }
  4466. }
  4467. } else {
  4468. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4469. face = this.faces[ f ];
  4470. if ( face instanceof THREE.Face3 ) {
  4471. vertices[ face.a ].add( face.normal );
  4472. vertices[ face.b ].add( face.normal );
  4473. vertices[ face.c ].add( face.normal );
  4474. } else if ( face instanceof THREE.Face4 ) {
  4475. vertices[ face.a ].add( face.normal );
  4476. vertices[ face.b ].add( face.normal );
  4477. vertices[ face.c ].add( face.normal );
  4478. vertices[ face.d ].add( face.normal );
  4479. }
  4480. }
  4481. }
  4482. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4483. vertices[ v ].normalize();
  4484. }
  4485. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4486. face = this.faces[ f ];
  4487. if ( face instanceof THREE.Face3 ) {
  4488. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4489. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4490. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4491. } else if ( face instanceof THREE.Face4 ) {
  4492. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4493. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4494. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4495. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  4496. }
  4497. }
  4498. },
  4499. computeMorphNormals: function () {
  4500. var i, il, f, fl, face;
  4501. // save original normals
  4502. // - create temp variables on first access
  4503. // otherwise just copy (for faster repeated calls)
  4504. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4505. face = this.faces[ f ];
  4506. if ( ! face.__originalFaceNormal ) {
  4507. face.__originalFaceNormal = face.normal.clone();
  4508. } else {
  4509. face.__originalFaceNormal.copy( face.normal );
  4510. }
  4511. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  4512. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  4513. if ( ! face.__originalVertexNormals[ i ] ) {
  4514. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  4515. } else {
  4516. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  4517. }
  4518. }
  4519. }
  4520. // use temp geometry to compute face and vertex normals for each morph
  4521. var tmpGeo = new THREE.Geometry();
  4522. tmpGeo.faces = this.faces;
  4523. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  4524. // create on first access
  4525. if ( ! this.morphNormals[ i ] ) {
  4526. this.morphNormals[ i ] = {};
  4527. this.morphNormals[ i ].faceNormals = [];
  4528. this.morphNormals[ i ].vertexNormals = [];
  4529. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  4530. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  4531. var faceNormal, vertexNormals;
  4532. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4533. face = this.faces[ f ];
  4534. faceNormal = new THREE.Vector3();
  4535. if ( face instanceof THREE.Face3 ) {
  4536. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  4537. } else {
  4538. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  4539. }
  4540. dstNormalsFace.push( faceNormal );
  4541. dstNormalsVertex.push( vertexNormals );
  4542. }
  4543. }
  4544. var morphNormals = this.morphNormals[ i ];
  4545. // set vertices to morph target
  4546. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  4547. // compute morph normals
  4548. tmpGeo.computeFaceNormals();
  4549. tmpGeo.computeVertexNormals();
  4550. // store morph normals
  4551. var faceNormal, vertexNormals;
  4552. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4553. face = this.faces[ f ];
  4554. faceNormal = morphNormals.faceNormals[ f ];
  4555. vertexNormals = morphNormals.vertexNormals[ f ];
  4556. faceNormal.copy( face.normal );
  4557. if ( face instanceof THREE.Face3 ) {
  4558. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4559. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4560. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4561. } else {
  4562. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4563. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4564. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4565. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  4566. }
  4567. }
  4568. }
  4569. // restore original normals
  4570. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4571. face = this.faces[ f ];
  4572. face.normal = face.__originalFaceNormal;
  4573. face.vertexNormals = face.__originalVertexNormals;
  4574. }
  4575. },
  4576. computeTangents: function () {
  4577. // based on http://www.terathon.com/code/tangent.html
  4578. // tangents go to vertices
  4579. var f, fl, v, vl, i, il, vertexIndex,
  4580. face, uv, vA, vB, vC, uvA, uvB, uvC,
  4581. x1, x2, y1, y2, z1, z2,
  4582. s1, s2, t1, t2, r, t, test,
  4583. tan1 = [], tan2 = [],
  4584. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  4585. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  4586. n = new THREE.Vector3(), w;
  4587. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4588. tan1[ v ] = new THREE.Vector3();
  4589. tan2[ v ] = new THREE.Vector3();
  4590. }
  4591. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  4592. vA = context.vertices[ a ];
  4593. vB = context.vertices[ b ];
  4594. vC = context.vertices[ c ];
  4595. uvA = uv[ ua ];
  4596. uvB = uv[ ub ];
  4597. uvC = uv[ uc ];
  4598. x1 = vB.x - vA.x;
  4599. x2 = vC.x - vA.x;
  4600. y1 = vB.y - vA.y;
  4601. y2 = vC.y - vA.y;
  4602. z1 = vB.z - vA.z;
  4603. z2 = vC.z - vA.z;
  4604. s1 = uvB.x - uvA.x;
  4605. s2 = uvC.x - uvA.x;
  4606. t1 = uvB.y - uvA.y;
  4607. t2 = uvC.y - uvA.y;
  4608. r = 1.0 / ( s1 * t2 - s2 * t1 );
  4609. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  4610. ( t2 * y1 - t1 * y2 ) * r,
  4611. ( t2 * z1 - t1 * z2 ) * r );
  4612. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  4613. ( s1 * y2 - s2 * y1 ) * r,
  4614. ( s1 * z2 - s2 * z1 ) * r );
  4615. tan1[ a ].add( sdir );
  4616. tan1[ b ].add( sdir );
  4617. tan1[ c ].add( sdir );
  4618. tan2[ a ].add( tdir );
  4619. tan2[ b ].add( tdir );
  4620. tan2[ c ].add( tdir );
  4621. }
  4622. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4623. face = this.faces[ f ];
  4624. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  4625. if ( face instanceof THREE.Face3 ) {
  4626. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  4627. } else if ( face instanceof THREE.Face4 ) {
  4628. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  4629. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  4630. }
  4631. }
  4632. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  4633. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4634. face = this.faces[ f ];
  4635. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  4636. n.copy( face.vertexNormals[ i ] );
  4637. vertexIndex = face[ faceIndex[ i ] ];
  4638. t = tan1[ vertexIndex ];
  4639. // Gram-Schmidt orthogonalize
  4640. tmp.copy( t );
  4641. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  4642. // Calculate handedness
  4643. tmp2.crossVectors( face.vertexNormals[ i ], t );
  4644. test = tmp2.dot( tan2[ vertexIndex ] );
  4645. w = (test < 0.0) ? -1.0 : 1.0;
  4646. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  4647. }
  4648. }
  4649. this.hasTangents = true;
  4650. },
  4651. computeLineDistances: function ( ) {
  4652. var d = 0;
  4653. var vertices = this.vertices;
  4654. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4655. if ( i > 0 ) {
  4656. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  4657. }
  4658. this.lineDistances[ i ] = d;
  4659. }
  4660. },
  4661. computeBoundingBox: function () {
  4662. if ( this.boundingBox === null ) {
  4663. this.boundingBox = new THREE.Box3();
  4664. }
  4665. this.boundingBox.setFromPoints( this.vertices );
  4666. },
  4667. computeBoundingSphere: function () {
  4668. if ( this.boundingSphere === null ) {
  4669. this.boundingSphere = new THREE.Sphere();
  4670. }
  4671. this.boundingSphere.setFromCenterAndPoints( this.boundingSphere.center, this.vertices );
  4672. },
  4673. /*
  4674. * Checks for duplicate vertices with hashmap.
  4675. * Duplicated vertices are removed
  4676. * and faces' vertices are updated.
  4677. */
  4678. mergeVertices: function () {
  4679. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  4680. var unique = [], changes = [];
  4681. var v, key;
  4682. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  4683. var precision = Math.pow( 10, precisionPoints );
  4684. var i,il, face;
  4685. var indices, k, j, jl, u;
  4686. // reset cache of vertices as it now will be changing.
  4687. this.__tmpVertices = undefined;
  4688. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  4689. v = this.vertices[ i ];
  4690. key = [ Math.round( v.x * precision ), Math.round( v.y * precision ), Math.round( v.z * precision ) ].join( '_' );
  4691. if ( verticesMap[ key ] === undefined ) {
  4692. verticesMap[ key ] = i;
  4693. unique.push( this.vertices[ i ] );
  4694. changes[ i ] = unique.length - 1;
  4695. } else {
  4696. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  4697. changes[ i ] = changes[ verticesMap[ key ] ];
  4698. }
  4699. };
  4700. // if faces are completely degenerate after merging vertices, we
  4701. // have to remove them from the geometry.
  4702. var faceIndicesToRemove = [];
  4703. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  4704. face = this.faces[ i ];
  4705. if ( face instanceof THREE.Face3 ) {
  4706. face.a = changes[ face.a ];
  4707. face.b = changes[ face.b ];
  4708. face.c = changes[ face.c ];
  4709. indices = [ face.a, face.b, face.c ];
  4710. var dupIndex = -1;
  4711. // if any duplicate vertices are found in a Face3
  4712. // we have to remove the face as nothing can be saved
  4713. for ( var n = 0; n < 3; n ++ ) {
  4714. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  4715. dupIndex = n;
  4716. faceIndicesToRemove.push( i );
  4717. break;
  4718. }
  4719. }
  4720. } else if ( face instanceof THREE.Face4 ) {
  4721. face.a = changes[ face.a ];
  4722. face.b = changes[ face.b ];
  4723. face.c = changes[ face.c ];
  4724. face.d = changes[ face.d ];
  4725. // check dups in (a, b, c, d) and convert to -> face3
  4726. indices = [ face.a, face.b, face.c, face.d ];
  4727. var dupIndex = -1;
  4728. for ( var n = 0; n < 4; n ++ ) {
  4729. if ( indices[ n ] == indices[ ( n + 1 ) % 4 ] ) {
  4730. // if more than one duplicated vertex is found
  4731. // we can't generate any valid Face3's, thus
  4732. // we need to remove this face complete.
  4733. if ( dupIndex >= 0 ) {
  4734. faceIndicesToRemove.push( i );
  4735. }
  4736. dupIndex = n;
  4737. }
  4738. }
  4739. if ( dupIndex >= 0 ) {
  4740. indices.splice( dupIndex, 1 );
  4741. var newFace = new THREE.Face3( indices[0], indices[1], indices[2], face.normal, face.color, face.materialIndex );
  4742. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  4743. u = this.faceVertexUvs[ j ][ i ];
  4744. if ( u ) {
  4745. u.splice( dupIndex, 1 );
  4746. }
  4747. }
  4748. if( face.vertexNormals && face.vertexNormals.length > 0) {
  4749. newFace.vertexNormals = face.vertexNormals;
  4750. newFace.vertexNormals.splice( dupIndex, 1 );
  4751. }
  4752. if( face.vertexColors && face.vertexColors.length > 0 ) {
  4753. newFace.vertexColors = face.vertexColors;
  4754. newFace.vertexColors.splice( dupIndex, 1 );
  4755. }
  4756. this.faces[ i ] = newFace;
  4757. }
  4758. }
  4759. }
  4760. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  4761. this.faces.splice( i, 1 );
  4762. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  4763. this.faceVertexUvs[ j ].splice( i, 1 );
  4764. }
  4765. }
  4766. // Use unique set of vertices
  4767. var diff = this.vertices.length - unique.length;
  4768. this.vertices = unique;
  4769. return diff;
  4770. },
  4771. clone: function () {
  4772. var geometry = new THREE.Geometry();
  4773. var vertices = this.vertices;
  4774. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4775. geometry.vertices.push( vertices[ i ].clone() );
  4776. }
  4777. var faces = this.faces;
  4778. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  4779. geometry.faces.push( faces[ i ].clone() );
  4780. }
  4781. var uvs = this.faceVertexUvs[ 0 ];
  4782. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  4783. var uv = uvs[ i ], uvCopy = [];
  4784. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  4785. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  4786. }
  4787. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  4788. }
  4789. return geometry;
  4790. },
  4791. dispose: function () {
  4792. this.dispatchEvent( { type: 'dispose' } );
  4793. }
  4794. };
  4795. THREE.GeometryIdCount = 0;
  4796. /**
  4797. * @author alteredq / http://alteredqualia.com/
  4798. */
  4799. THREE.BufferGeometry = function () {
  4800. THREE.EventDispatcher.call( this );
  4801. this.id = THREE.GeometryIdCount ++;
  4802. // attributes
  4803. this.attributes = {};
  4804. // attributes typed arrays are kept only if dynamic flag is set
  4805. this.dynamic = false;
  4806. // offsets for chunks when using indexed elements
  4807. this.offsets = [];
  4808. // boundings
  4809. this.boundingBox = null;
  4810. this.boundingSphere = null;
  4811. this.hasTangents = false;
  4812. // for compatibility
  4813. this.morphTargets = [];
  4814. };
  4815. THREE.BufferGeometry.prototype = {
  4816. constructor : THREE.BufferGeometry,
  4817. applyMatrix: function ( matrix ) {
  4818. var positionArray;
  4819. var normalArray;
  4820. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  4821. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  4822. if ( positionArray !== undefined ) {
  4823. matrix.multiplyVector3Array( positionArray );
  4824. this.verticesNeedUpdate = true;
  4825. }
  4826. if ( normalArray !== undefined ) {
  4827. var normalMatrix = new THREE.Matrix3();
  4828. normalMatrix.getInverse( matrix ).transpose();
  4829. normalMatrix.multiplyVector3Array( normalArray );
  4830. this.normalizeNormals();
  4831. this.normalsNeedUpdate = true;
  4832. }
  4833. },
  4834. computeBoundingBox: function () {
  4835. if ( this.boundingBox === null ) {
  4836. this.boundingBox = new THREE.Box3();
  4837. }
  4838. var positions = this.attributes[ "position" ].array;
  4839. if ( positions ) {
  4840. var bb = this.boundingBox;
  4841. var x, y, z;
  4842. if( positions.length >= 3 ) {
  4843. bb.min.x = bb.max.x = positions[ 0 ];
  4844. bb.min.y = bb.max.y = positions[ 1 ];
  4845. bb.min.z = bb.max.z = positions[ 2 ];
  4846. }
  4847. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  4848. x = positions[ i ];
  4849. y = positions[ i + 1 ];
  4850. z = positions[ i + 2 ];
  4851. // bounding box
  4852. if ( x < bb.min.x ) {
  4853. bb.min.x = x;
  4854. } else if ( x > bb.max.x ) {
  4855. bb.max.x = x;
  4856. }
  4857. if ( y < bb.min.y ) {
  4858. bb.min.y = y;
  4859. } else if ( y > bb.max.y ) {
  4860. bb.max.y = y;
  4861. }
  4862. if ( z < bb.min.z ) {
  4863. bb.min.z = z;
  4864. } else if ( z > bb.max.z ) {
  4865. bb.max.z = z;
  4866. }
  4867. }
  4868. }
  4869. if ( positions === undefined || positions.length === 0 ) {
  4870. this.boundingBox.min.set( 0, 0, 0 );
  4871. this.boundingBox.max.set( 0, 0, 0 );
  4872. }
  4873. },
  4874. computeBoundingSphere: function () {
  4875. if ( this.boundingSphere === null ) {
  4876. this.boundingSphere = new THREE.Sphere();
  4877. }
  4878. var positions = this.attributes[ "position" ].array;
  4879. if ( positions ) {
  4880. var radiusSq, maxRadiusSq = 0;
  4881. var x, y, z;
  4882. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  4883. x = positions[ i ];
  4884. y = positions[ i + 1 ];
  4885. z = positions[ i + 2 ];
  4886. radiusSq = x * x + y * y + z * z;
  4887. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  4888. }
  4889. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  4890. }
  4891. },
  4892. computeVertexNormals: function () {
  4893. if ( this.attributes[ "position" ] ) {
  4894. var i, il;
  4895. var j, jl;
  4896. var nVertexElements = this.attributes[ "position" ].array.length;
  4897. if ( this.attributes[ "normal" ] === undefined ) {
  4898. this.attributes[ "normal" ] = {
  4899. itemSize: 3,
  4900. array: new Float32Array( nVertexElements ),
  4901. numItems: nVertexElements
  4902. };
  4903. } else {
  4904. // reset existing normals to zero
  4905. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  4906. this.attributes[ "normal" ].array[ i ] = 0;
  4907. }
  4908. }
  4909. var positions = this.attributes[ "position" ].array;
  4910. var normals = this.attributes[ "normal" ].array;
  4911. var vA, vB, vC, x, y, z,
  4912. pA = new THREE.Vector3(),
  4913. pB = new THREE.Vector3(),
  4914. pC = new THREE.Vector3(),
  4915. cb = new THREE.Vector3(),
  4916. ab = new THREE.Vector3();
  4917. // indexed elements
  4918. if ( this.attributes[ "index" ] ) {
  4919. var indices = this.attributes[ "index" ].array;
  4920. var offsets = this.offsets;
  4921. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  4922. var start = offsets[ j ].start;
  4923. var count = offsets[ j ].count;
  4924. var index = offsets[ j ].index;
  4925. for ( i = start, il = start + count; i < il; i += 3 ) {
  4926. vA = index + indices[ i ];
  4927. vB = index + indices[ i + 1 ];
  4928. vC = index + indices[ i + 2 ];
  4929. x = positions[ vA * 3 ];
  4930. y = positions[ vA * 3 + 1 ];
  4931. z = positions[ vA * 3 + 2 ];
  4932. pA.set( x, y, z );
  4933. x = positions[ vB * 3 ];
  4934. y = positions[ vB * 3 + 1 ];
  4935. z = positions[ vB * 3 + 2 ];
  4936. pB.set( x, y, z );
  4937. x = positions[ vC * 3 ];
  4938. y = positions[ vC * 3 + 1 ];
  4939. z = positions[ vC * 3 + 2 ];
  4940. pC.set( x, y, z );
  4941. cb.subVectors( pC, pB );
  4942. ab.subVectors( pA, pB );
  4943. cb.cross( ab );
  4944. normals[ vA * 3 ] += cb.x;
  4945. normals[ vA * 3 + 1 ] += cb.y;
  4946. normals[ vA * 3 + 2 ] += cb.z;
  4947. normals[ vB * 3 ] += cb.x;
  4948. normals[ vB * 3 + 1 ] += cb.y;
  4949. normals[ vB * 3 + 2 ] += cb.z;
  4950. normals[ vC * 3 ] += cb.x;
  4951. normals[ vC * 3 + 1 ] += cb.y;
  4952. normals[ vC * 3 + 2 ] += cb.z;
  4953. }
  4954. }
  4955. // non-indexed elements (unconnected triangle soup)
  4956. } else {
  4957. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  4958. x = positions[ i ];
  4959. y = positions[ i + 1 ];
  4960. z = positions[ i + 2 ];
  4961. pA.set( x, y, z );
  4962. x = positions[ i + 3 ];
  4963. y = positions[ i + 4 ];
  4964. z = positions[ i + 5 ];
  4965. pB.set( x, y, z );
  4966. x = positions[ i + 6 ];
  4967. y = positions[ i + 7 ];
  4968. z = positions[ i + 8 ];
  4969. pC.set( x, y, z );
  4970. cb.subVectors( pC, pB );
  4971. ab.subVectors( pA, pB );
  4972. cb.cross( ab );
  4973. normals[ i ] = cb.x;
  4974. normals[ i + 1 ] = cb.y;
  4975. normals[ i + 2 ] = cb.z;
  4976. normals[ i + 3 ] = cb.x;
  4977. normals[ i + 4 ] = cb.y;
  4978. normals[ i + 5 ] = cb.z;
  4979. normals[ i + 6 ] = cb.x;
  4980. normals[ i + 7 ] = cb.y;
  4981. normals[ i + 8 ] = cb.z;
  4982. }
  4983. }
  4984. this.normalizeNormals();
  4985. this.normalsNeedUpdate = true;
  4986. }
  4987. },
  4988. normalizeNormals: function () {
  4989. var normals = this.attributes[ "normal" ].array;
  4990. var x, y, z, n;
  4991. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  4992. x = normals[ i ];
  4993. y = normals[ i + 1 ];
  4994. z = normals[ i + 2 ];
  4995. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  4996. normals[ i ] *= n;
  4997. normals[ i + 1 ] *= n;
  4998. normals[ i + 2 ] *= n;
  4999. }
  5000. },
  5001. computeTangents: function () {
  5002. // based on http://www.terathon.com/code/tangent.html
  5003. // (per vertex tangents)
  5004. if ( this.attributes[ "index" ] === undefined ||
  5005. this.attributes[ "position" ] === undefined ||
  5006. this.attributes[ "normal" ] === undefined ||
  5007. this.attributes[ "uv" ] === undefined ) {
  5008. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  5009. return;
  5010. }
  5011. var indices = this.attributes[ "index" ].array;
  5012. var positions = this.attributes[ "position" ].array;
  5013. var normals = this.attributes[ "normal" ].array;
  5014. var uvs = this.attributes[ "uv" ].array;
  5015. var nVertices = positions.length / 3;
  5016. if ( this.attributes[ "tangent" ] === undefined ) {
  5017. var nTangentElements = 4 * nVertices;
  5018. this.attributes[ "tangent" ] = {
  5019. itemSize: 4,
  5020. array: new Float32Array( nTangentElements ),
  5021. numItems: nTangentElements
  5022. };
  5023. }
  5024. var tangents = this.attributes[ "tangent" ].array;
  5025. var tan1 = [], tan2 = [];
  5026. for ( var k = 0; k < nVertices; k ++ ) {
  5027. tan1[ k ] = new THREE.Vector3();
  5028. tan2[ k ] = new THREE.Vector3();
  5029. }
  5030. var xA, yA, zA,
  5031. xB, yB, zB,
  5032. xC, yC, zC,
  5033. uA, vA,
  5034. uB, vB,
  5035. uC, vC,
  5036. x1, x2, y1, y2, z1, z2,
  5037. s1, s2, t1, t2, r;
  5038. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5039. function handleTriangle( a, b, c ) {
  5040. xA = positions[ a * 3 ];
  5041. yA = positions[ a * 3 + 1 ];
  5042. zA = positions[ a * 3 + 2 ];
  5043. xB = positions[ b * 3 ];
  5044. yB = positions[ b * 3 + 1 ];
  5045. zB = positions[ b * 3 + 2 ];
  5046. xC = positions[ c * 3 ];
  5047. yC = positions[ c * 3 + 1 ];
  5048. zC = positions[ c * 3 + 2 ];
  5049. uA = uvs[ a * 2 ];
  5050. vA = uvs[ a * 2 + 1 ];
  5051. uB = uvs[ b * 2 ];
  5052. vB = uvs[ b * 2 + 1 ];
  5053. uC = uvs[ c * 2 ];
  5054. vC = uvs[ c * 2 + 1 ];
  5055. x1 = xB - xA;
  5056. x2 = xC - xA;
  5057. y1 = yB - yA;
  5058. y2 = yC - yA;
  5059. z1 = zB - zA;
  5060. z2 = zC - zA;
  5061. s1 = uB - uA;
  5062. s2 = uC - uA;
  5063. t1 = vB - vA;
  5064. t2 = vC - vA;
  5065. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5066. sdir.set(
  5067. ( t2 * x1 - t1 * x2 ) * r,
  5068. ( t2 * y1 - t1 * y2 ) * r,
  5069. ( t2 * z1 - t1 * z2 ) * r
  5070. );
  5071. tdir.set(
  5072. ( s1 * x2 - s2 * x1 ) * r,
  5073. ( s1 * y2 - s2 * y1 ) * r,
  5074. ( s1 * z2 - s2 * z1 ) * r
  5075. );
  5076. tan1[ a ].add( sdir );
  5077. tan1[ b ].add( sdir );
  5078. tan1[ c ].add( sdir );
  5079. tan2[ a ].add( tdir );
  5080. tan2[ b ].add( tdir );
  5081. tan2[ c ].add( tdir );
  5082. }
  5083. var i, il;
  5084. var j, jl;
  5085. var iA, iB, iC;
  5086. var offsets = this.offsets;
  5087. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5088. var start = offsets[ j ].start;
  5089. var count = offsets[ j ].count;
  5090. var index = offsets[ j ].index;
  5091. for ( i = start, il = start + count; i < il; i += 3 ) {
  5092. iA = index + indices[ i ];
  5093. iB = index + indices[ i + 1 ];
  5094. iC = index + indices[ i + 2 ];
  5095. handleTriangle( iA, iB, iC );
  5096. }
  5097. }
  5098. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5099. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5100. var w, t, test;
  5101. var nx, ny, nz;
  5102. function handleVertex( v ) {
  5103. n.x = normals[ v * 3 ];
  5104. n.y = normals[ v * 3 + 1 ];
  5105. n.z = normals[ v * 3 + 2 ];
  5106. n2.copy( n );
  5107. t = tan1[ v ];
  5108. // Gram-Schmidt orthogonalize
  5109. tmp.copy( t );
  5110. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5111. // Calculate handedness
  5112. tmp2.crossVectors( n2, t );
  5113. test = tmp2.dot( tan2[ v ] );
  5114. w = ( test < 0.0 ) ? -1.0 : 1.0;
  5115. tangents[ v * 4 ] = tmp.x;
  5116. tangents[ v * 4 + 1 ] = tmp.y;
  5117. tangents[ v * 4 + 2 ] = tmp.z;
  5118. tangents[ v * 4 + 3 ] = w;
  5119. }
  5120. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5121. var start = offsets[ j ].start;
  5122. var count = offsets[ j ].count;
  5123. var index = offsets[ j ].index;
  5124. for ( i = start, il = start + count; i < il; i += 3 ) {
  5125. iA = index + indices[ i ];
  5126. iB = index + indices[ i + 1 ];
  5127. iC = index + indices[ i + 2 ];
  5128. handleVertex( iA );
  5129. handleVertex( iB );
  5130. handleVertex( iC );
  5131. }
  5132. }
  5133. this.hasTangents = true;
  5134. this.tangentsNeedUpdate = true;
  5135. },
  5136. dispose: function () {
  5137. this.dispatchEvent( { type: 'dispose' } );
  5138. }
  5139. };
  5140. /**
  5141. * @author mrdoob / http://mrdoob.com/
  5142. * @author mikael emtinger / http://gomo.se/
  5143. */
  5144. THREE.Camera = function () {
  5145. THREE.Object3D.call( this );
  5146. this.matrixWorldInverse = new THREE.Matrix4();
  5147. this.projectionMatrix = new THREE.Matrix4();
  5148. this.projectionMatrixInverse = new THREE.Matrix4();
  5149. };
  5150. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  5151. THREE.Camera.prototype.lookAt = function ( vector ) {
  5152. // TODO: Add hierarchy support.
  5153. this.matrix.lookAt( this.position, vector, this.up );
  5154. if ( this.rotationAutoUpdate === true ) {
  5155. if ( this.useQuaternion === false ) {
  5156. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  5157. } else {
  5158. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  5159. }
  5160. }
  5161. };
  5162. /**
  5163. * @author alteredq / http://alteredqualia.com/
  5164. */
  5165. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  5166. THREE.Camera.call( this );
  5167. this.left = left;
  5168. this.right = right;
  5169. this.top = top;
  5170. this.bottom = bottom;
  5171. this.near = ( near !== undefined ) ? near : 0.1;
  5172. this.far = ( far !== undefined ) ? far : 2000;
  5173. this.updateProjectionMatrix();
  5174. };
  5175. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  5176. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  5177. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  5178. };
  5179. /**
  5180. * @author mrdoob / http://mrdoob.com/
  5181. * @author greggman / http://games.greggman.com/
  5182. * @author zz85 / http://www.lab4games.net/zz85/blog
  5183. */
  5184. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  5185. THREE.Camera.call( this );
  5186. this.fov = fov !== undefined ? fov : 50;
  5187. this.aspect = aspect !== undefined ? aspect : 1;
  5188. this.near = near !== undefined ? near : 0.1;
  5189. this.far = far !== undefined ? far : 2000;
  5190. this.updateProjectionMatrix();
  5191. };
  5192. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  5193. /**
  5194. * Uses Focal Length (in mm) to estimate and set FOV
  5195. * 35mm (fullframe) camera is used if frame size is not specified;
  5196. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  5197. */
  5198. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  5199. if ( frameHeight === undefined ) frameHeight = 24;
  5200. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  5201. this.updateProjectionMatrix();
  5202. }
  5203. /**
  5204. * Sets an offset in a larger frustum. This is useful for multi-window or
  5205. * multi-monitor/multi-machine setups.
  5206. *
  5207. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  5208. * the monitors are in grid like this
  5209. *
  5210. * +---+---+---+
  5211. * | A | B | C |
  5212. * +---+---+---+
  5213. * | D | E | F |
  5214. * +---+---+---+
  5215. *
  5216. * then for each monitor you would call it like this
  5217. *
  5218. * var w = 1920;
  5219. * var h = 1080;
  5220. * var fullWidth = w * 3;
  5221. * var fullHeight = h * 2;
  5222. *
  5223. * --A--
  5224. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  5225. * --B--
  5226. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  5227. * --C--
  5228. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  5229. * --D--
  5230. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  5231. * --E--
  5232. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  5233. * --F--
  5234. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  5235. *
  5236. * Note there is no reason monitors have to be the same size or in a grid.
  5237. */
  5238. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  5239. this.fullWidth = fullWidth;
  5240. this.fullHeight = fullHeight;
  5241. this.x = x;
  5242. this.y = y;
  5243. this.width = width;
  5244. this.height = height;
  5245. this.updateProjectionMatrix();
  5246. };
  5247. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  5248. if ( this.fullWidth ) {
  5249. var aspect = this.fullWidth / this.fullHeight;
  5250. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  5251. var bottom = -top;
  5252. var left = aspect * bottom;
  5253. var right = aspect * top;
  5254. var width = Math.abs( right - left );
  5255. var height = Math.abs( top - bottom );
  5256. this.projectionMatrix.makeFrustum(
  5257. left + this.x * width / this.fullWidth,
  5258. left + ( this.x + this.width ) * width / this.fullWidth,
  5259. top - ( this.y + this.height ) * height / this.fullHeight,
  5260. top - this.y * height / this.fullHeight,
  5261. this.near,
  5262. this.far
  5263. );
  5264. } else {
  5265. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  5266. }
  5267. };
  5268. /**
  5269. * @author mrdoob / http://mrdoob.com/
  5270. * @author alteredq / http://alteredqualia.com/
  5271. */
  5272. THREE.Light = function ( hex ) {
  5273. THREE.Object3D.call( this );
  5274. this.color = new THREE.Color( hex );
  5275. };
  5276. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  5277. /**
  5278. * @author mrdoob / http://mrdoob.com/
  5279. */
  5280. THREE.AmbientLight = function ( hex ) {
  5281. THREE.Light.call( this, hex );
  5282. };
  5283. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  5284. /**
  5285. * @author MPanknin / http://www.redplant.de/
  5286. * @author alteredq / http://alteredqualia.com/
  5287. */
  5288. THREE.AreaLight = function ( hex, intensity ) {
  5289. THREE.Light.call( this, hex );
  5290. this.normal = new THREE.Vector3( 0, -1, 0 );
  5291. this.right = new THREE.Vector3( 1, 0, 0 );
  5292. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5293. this.width = 1.0;
  5294. this.height = 1.0;
  5295. this.constantAttenuation = 1.5;
  5296. this.linearAttenuation = 0.5;
  5297. this.quadraticAttenuation = 0.1;
  5298. };
  5299. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  5300. /**
  5301. * @author mrdoob / http://mrdoob.com/
  5302. * @author alteredq / http://alteredqualia.com/
  5303. */
  5304. THREE.DirectionalLight = function ( hex, intensity ) {
  5305. THREE.Light.call( this, hex );
  5306. this.position = new THREE.Vector3( 0, 1, 0 );
  5307. this.target = new THREE.Object3D();
  5308. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5309. this.castShadow = false;
  5310. this.onlyShadow = false;
  5311. //
  5312. this.shadowCameraNear = 50;
  5313. this.shadowCameraFar = 5000;
  5314. this.shadowCameraLeft = -500;
  5315. this.shadowCameraRight = 500;
  5316. this.shadowCameraTop = 500;
  5317. this.shadowCameraBottom = -500;
  5318. this.shadowCameraVisible = false;
  5319. this.shadowBias = 0;
  5320. this.shadowDarkness = 0.5;
  5321. this.shadowMapWidth = 512;
  5322. this.shadowMapHeight = 512;
  5323. //
  5324. this.shadowCascade = false;
  5325. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  5326. this.shadowCascadeCount = 2;
  5327. this.shadowCascadeBias = [ 0, 0, 0 ];
  5328. this.shadowCascadeWidth = [ 512, 512, 512 ];
  5329. this.shadowCascadeHeight = [ 512, 512, 512 ];
  5330. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  5331. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  5332. this.shadowCascadeArray = [];
  5333. //
  5334. this.shadowMap = null;
  5335. this.shadowMapSize = null;
  5336. this.shadowCamera = null;
  5337. this.shadowMatrix = null;
  5338. };
  5339. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  5340. /**
  5341. * @author alteredq / http://alteredqualia.com/
  5342. */
  5343. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  5344. THREE.Light.call( this, skyColorHex );
  5345. this.groundColor = new THREE.Color( groundColorHex );
  5346. this.position = new THREE.Vector3( 0, 100, 0 );
  5347. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5348. };
  5349. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  5350. /**
  5351. * @author mrdoob / http://mrdoob.com/
  5352. */
  5353. THREE.PointLight = function ( hex, intensity, distance ) {
  5354. THREE.Light.call( this, hex );
  5355. this.position = new THREE.Vector3( 0, 0, 0 );
  5356. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5357. this.distance = ( distance !== undefined ) ? distance : 0;
  5358. };
  5359. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  5360. /**
  5361. * @author alteredq / http://alteredqualia.com/
  5362. */
  5363. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  5364. THREE.Light.call( this, hex );
  5365. this.position = new THREE.Vector3( 0, 1, 0 );
  5366. this.target = new THREE.Object3D();
  5367. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5368. this.distance = ( distance !== undefined ) ? distance : 0;
  5369. this.angle = ( angle !== undefined ) ? angle : Math.PI / 2;
  5370. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  5371. this.castShadow = false;
  5372. this.onlyShadow = false;
  5373. //
  5374. this.shadowCameraNear = 50;
  5375. this.shadowCameraFar = 5000;
  5376. this.shadowCameraFov = 50;
  5377. this.shadowCameraVisible = false;
  5378. this.shadowBias = 0;
  5379. this.shadowDarkness = 0.5;
  5380. this.shadowMapWidth = 512;
  5381. this.shadowMapHeight = 512;
  5382. //
  5383. this.shadowMap = null;
  5384. this.shadowMapSize = null;
  5385. this.shadowCamera = null;
  5386. this.shadowMatrix = null;
  5387. };
  5388. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  5389. /**
  5390. * @author alteredq / http://alteredqualia.com/
  5391. */
  5392. THREE.Loader = function ( showStatus ) {
  5393. this.showStatus = showStatus;
  5394. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  5395. this.onLoadStart = function () {};
  5396. this.onLoadProgress = function () {};
  5397. this.onLoadComplete = function () {};
  5398. };
  5399. THREE.Loader.prototype = {
  5400. constructor: THREE.Loader,
  5401. crossOrigin: 'anonymous',
  5402. addStatusElement: function () {
  5403. var e = document.createElement( "div" );
  5404. e.style.position = "absolute";
  5405. e.style.right = "0px";
  5406. e.style.top = "0px";
  5407. e.style.fontSize = "0.8em";
  5408. e.style.textAlign = "left";
  5409. e.style.background = "rgba(0,0,0,0.25)";
  5410. e.style.color = "#fff";
  5411. e.style.width = "120px";
  5412. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  5413. e.style.zIndex = 1000;
  5414. e.innerHTML = "Loading ...";
  5415. return e;
  5416. },
  5417. updateProgress: function ( progress ) {
  5418. var message = "Loaded ";
  5419. if ( progress.total ) {
  5420. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  5421. } else {
  5422. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  5423. }
  5424. this.statusDomElement.innerHTML = message;
  5425. },
  5426. extractUrlBase: function ( url ) {
  5427. var parts = url.split( '/' );
  5428. parts.pop();
  5429. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  5430. },
  5431. initMaterials: function ( materials, texturePath ) {
  5432. var array = [];
  5433. for ( var i = 0; i < materials.length; ++ i ) {
  5434. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  5435. }
  5436. return array;
  5437. },
  5438. needsTangents: function ( materials ) {
  5439. for( var i = 0, il = materials.length; i < il; i ++ ) {
  5440. var m = materials[ i ];
  5441. if ( m instanceof THREE.ShaderMaterial ) return true;
  5442. }
  5443. return false;
  5444. },
  5445. createMaterial: function ( m, texturePath ) {
  5446. var _this = this;
  5447. function is_pow2( n ) {
  5448. var l = Math.log( n ) / Math.LN2;
  5449. return Math.floor( l ) == l;
  5450. }
  5451. function nearest_pow2( n ) {
  5452. var l = Math.log( n ) / Math.LN2;
  5453. return Math.pow( 2, Math.round( l ) );
  5454. }
  5455. function load_image( where, url ) {
  5456. var image = new Image();
  5457. image.onload = function () {
  5458. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  5459. var width = nearest_pow2( this.width );
  5460. var height = nearest_pow2( this.height );
  5461. where.image.width = width;
  5462. where.image.height = height;
  5463. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  5464. } else {
  5465. where.image = this;
  5466. }
  5467. where.needsUpdate = true;
  5468. };
  5469. image.crossOrigin = _this.crossOrigin;
  5470. image.src = url;
  5471. }
  5472. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  5473. var isCompressed = sourceFile.toLowerCase().endsWith( ".dds" );
  5474. var fullPath = texturePath + "/" + sourceFile;
  5475. if ( isCompressed ) {
  5476. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  5477. where[ name ] = texture;
  5478. } else {
  5479. var texture = document.createElement( 'canvas' );
  5480. where[ name ] = new THREE.Texture( texture );
  5481. }
  5482. where[ name ].sourceFile = sourceFile;
  5483. if( repeat ) {
  5484. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  5485. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  5486. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  5487. }
  5488. if ( offset ) {
  5489. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  5490. }
  5491. if ( wrap ) {
  5492. var wrapMap = {
  5493. "repeat": THREE.RepeatWrapping,
  5494. "mirror": THREE.MirroredRepeatWrapping
  5495. }
  5496. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  5497. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  5498. }
  5499. if ( anisotropy ) {
  5500. where[ name ].anisotropy = anisotropy;
  5501. }
  5502. if ( ! isCompressed ) {
  5503. load_image( where[ name ], fullPath );
  5504. }
  5505. }
  5506. function rgb2hex( rgb ) {
  5507. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  5508. }
  5509. // defaults
  5510. var mtype = "MeshLambertMaterial";
  5511. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  5512. // parameters from model file
  5513. if ( m.shading ) {
  5514. var shading = m.shading.toLowerCase();
  5515. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  5516. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  5517. }
  5518. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  5519. mpars.blending = THREE[ m.blending ];
  5520. }
  5521. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  5522. mpars.transparent = m.transparent;
  5523. }
  5524. if ( m.depthTest !== undefined ) {
  5525. mpars.depthTest = m.depthTest;
  5526. }
  5527. if ( m.depthWrite !== undefined ) {
  5528. mpars.depthWrite = m.depthWrite;
  5529. }
  5530. if ( m.visible !== undefined ) {
  5531. mpars.visible = m.visible;
  5532. }
  5533. if ( m.flipSided !== undefined ) {
  5534. mpars.side = THREE.BackSide;
  5535. }
  5536. if ( m.doubleSided !== undefined ) {
  5537. mpars.side = THREE.DoubleSide;
  5538. }
  5539. if ( m.wireframe !== undefined ) {
  5540. mpars.wireframe = m.wireframe;
  5541. }
  5542. if ( m.vertexColors !== undefined ) {
  5543. if ( m.vertexColors === "face" ) {
  5544. mpars.vertexColors = THREE.FaceColors;
  5545. } else if ( m.vertexColors ) {
  5546. mpars.vertexColors = THREE.VertexColors;
  5547. }
  5548. }
  5549. // colors
  5550. if ( m.colorDiffuse ) {
  5551. mpars.color = rgb2hex( m.colorDiffuse );
  5552. } else if ( m.DbgColor ) {
  5553. mpars.color = m.DbgColor;
  5554. }
  5555. if ( m.colorSpecular ) {
  5556. mpars.specular = rgb2hex( m.colorSpecular );
  5557. }
  5558. if ( m.colorAmbient ) {
  5559. mpars.ambient = rgb2hex( m.colorAmbient );
  5560. }
  5561. // modifiers
  5562. if ( m.transparency ) {
  5563. mpars.opacity = m.transparency;
  5564. }
  5565. if ( m.specularCoef ) {
  5566. mpars.shininess = m.specularCoef;
  5567. }
  5568. // textures
  5569. if ( m.mapDiffuse && texturePath ) {
  5570. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  5571. }
  5572. if ( m.mapLight && texturePath ) {
  5573. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  5574. }
  5575. if ( m.mapBump && texturePath ) {
  5576. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  5577. }
  5578. if ( m.mapNormal && texturePath ) {
  5579. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  5580. }
  5581. if ( m.mapSpecular && texturePath ) {
  5582. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  5583. }
  5584. //
  5585. if ( m.mapBumpScale ) {
  5586. mpars.bumpScale = m.mapBumpScale;
  5587. }
  5588. // special case for normal mapped material
  5589. if ( m.mapNormal ) {
  5590. var shader = THREE.ShaderLib[ "normalmap" ];
  5591. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5592. uniforms[ "tNormal" ].value = mpars.normalMap;
  5593. if ( m.mapNormalFactor ) {
  5594. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  5595. }
  5596. if ( mpars.map ) {
  5597. uniforms[ "tDiffuse" ].value = mpars.map;
  5598. uniforms[ "enableDiffuse" ].value = true;
  5599. }
  5600. if ( mpars.specularMap ) {
  5601. uniforms[ "tSpecular" ].value = mpars.specularMap;
  5602. uniforms[ "enableSpecular" ].value = true;
  5603. }
  5604. if ( mpars.lightMap ) {
  5605. uniforms[ "tAO" ].value = mpars.lightMap;
  5606. uniforms[ "enableAO" ].value = true;
  5607. }
  5608. // for the moment don't handle displacement texture
  5609. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  5610. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  5611. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  5612. uniforms[ "uShininess" ].value = mpars.shininess;
  5613. if ( mpars.opacity !== undefined ) {
  5614. uniforms[ "uOpacity" ].value = mpars.opacity;
  5615. }
  5616. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5617. var material = new THREE.ShaderMaterial( parameters );
  5618. if ( mpars.transparent ) {
  5619. material.transparent = true;
  5620. }
  5621. } else {
  5622. var material = new THREE[ mtype ]( mpars );
  5623. }
  5624. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  5625. return material;
  5626. }
  5627. };
  5628. /**
  5629. * @author mrdoob / http://mrdoob.com/
  5630. */
  5631. THREE.ImageLoader = function () {
  5632. THREE.EventDispatcher.call( this );
  5633. this.crossOrigin = null;
  5634. };
  5635. THREE.ImageLoader.prototype = {
  5636. constructor: THREE.ImageLoader,
  5637. load: function ( url, image ) {
  5638. var scope = this;
  5639. if ( image === undefined ) image = new Image();
  5640. image.addEventListener( 'load', function () {
  5641. scope.dispatchEvent( { type: 'load', content: image } );
  5642. }, false );
  5643. image.addEventListener( 'error', function () {
  5644. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  5645. }, false );
  5646. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  5647. image.src = url;
  5648. }
  5649. }
  5650. /**
  5651. * @author mrdoob / http://mrdoob.com/
  5652. * @author alteredq / http://alteredqualia.com/
  5653. */
  5654. THREE.JSONLoader = function ( showStatus ) {
  5655. THREE.Loader.call( this, showStatus );
  5656. this.withCredentials = false;
  5657. };
  5658. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  5659. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  5660. var scope = this;
  5661. // todo: unify load API to for easier SceneLoader use
  5662. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  5663. this.onLoadStart();
  5664. this.loadAjaxJSON( this, url, callback, texturePath );
  5665. };
  5666. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  5667. var xhr = new XMLHttpRequest();
  5668. var length = 0;
  5669. xhr.onreadystatechange = function () {
  5670. if ( xhr.readyState === xhr.DONE ) {
  5671. if ( xhr.status === 200 || xhr.status === 0 ) {
  5672. if ( xhr.responseText ) {
  5673. var json = JSON.parse( xhr.responseText );
  5674. context.createModel( json, callback, texturePath );
  5675. } else {
  5676. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  5677. }
  5678. // in context of more complex asset initialization
  5679. // do not block on single failed file
  5680. // maybe should go even one more level up
  5681. context.onLoadComplete();
  5682. } else {
  5683. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5684. }
  5685. } else if ( xhr.readyState === xhr.LOADING ) {
  5686. if ( callbackProgress ) {
  5687. if ( length === 0 ) {
  5688. length = xhr.getResponseHeader( "Content-Length" );
  5689. }
  5690. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  5691. }
  5692. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  5693. length = xhr.getResponseHeader( "Content-Length" );
  5694. }
  5695. };
  5696. xhr.open( "GET", url, true );
  5697. xhr.withCredentials = this.withCredentials;
  5698. xhr.send( null );
  5699. };
  5700. THREE.JSONLoader.prototype.createModel = function ( json, callback, texturePath ) {
  5701. var scope = this,
  5702. geometry = new THREE.Geometry(),
  5703. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  5704. parseModel( scale );
  5705. parseSkin();
  5706. parseMorphing( scale );
  5707. geometry.computeCentroids();
  5708. geometry.computeFaceNormals();
  5709. function parseModel( scale ) {
  5710. function isBitSet( value, position ) {
  5711. return value & ( 1 << position );
  5712. }
  5713. var i, j, fi,
  5714. offset, zLength, nVertices,
  5715. colorIndex, normalIndex, uvIndex, materialIndex,
  5716. type,
  5717. isQuad,
  5718. hasMaterial,
  5719. hasFaceUv, hasFaceVertexUv,
  5720. hasFaceNormal, hasFaceVertexNormal,
  5721. hasFaceColor, hasFaceVertexColor,
  5722. vertex, face, color, normal,
  5723. uvLayer, uvs, u, v,
  5724. faces = json.faces,
  5725. vertices = json.vertices,
  5726. normals = json.normals,
  5727. colors = json.colors,
  5728. nUvLayers = 0;
  5729. // disregard empty arrays
  5730. for ( i = 0; i < json.uvs.length; i++ ) {
  5731. if ( json.uvs[ i ].length ) nUvLayers ++;
  5732. }
  5733. for ( i = 0; i < nUvLayers; i++ ) {
  5734. geometry.faceUvs[ i ] = [];
  5735. geometry.faceVertexUvs[ i ] = [];
  5736. }
  5737. offset = 0;
  5738. zLength = vertices.length;
  5739. while ( offset < zLength ) {
  5740. vertex = new THREE.Vector3();
  5741. vertex.x = vertices[ offset ++ ] * scale;
  5742. vertex.y = vertices[ offset ++ ] * scale;
  5743. vertex.z = vertices[ offset ++ ] * scale;
  5744. geometry.vertices.push( vertex );
  5745. }
  5746. offset = 0;
  5747. zLength = faces.length;
  5748. while ( offset < zLength ) {
  5749. type = faces[ offset ++ ];
  5750. isQuad = isBitSet( type, 0 );
  5751. hasMaterial = isBitSet( type, 1 );
  5752. hasFaceUv = isBitSet( type, 2 );
  5753. hasFaceVertexUv = isBitSet( type, 3 );
  5754. hasFaceNormal = isBitSet( type, 4 );
  5755. hasFaceVertexNormal = isBitSet( type, 5 );
  5756. hasFaceColor = isBitSet( type, 6 );
  5757. hasFaceVertexColor = isBitSet( type, 7 );
  5758. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  5759. if ( isQuad ) {
  5760. face = new THREE.Face4();
  5761. face.a = faces[ offset ++ ];
  5762. face.b = faces[ offset ++ ];
  5763. face.c = faces[ offset ++ ];
  5764. face.d = faces[ offset ++ ];
  5765. nVertices = 4;
  5766. } else {
  5767. face = new THREE.Face3();
  5768. face.a = faces[ offset ++ ];
  5769. face.b = faces[ offset ++ ];
  5770. face.c = faces[ offset ++ ];
  5771. nVertices = 3;
  5772. }
  5773. if ( hasMaterial ) {
  5774. materialIndex = faces[ offset ++ ];
  5775. face.materialIndex = materialIndex;
  5776. }
  5777. // to get face <=> uv index correspondence
  5778. fi = geometry.faces.length;
  5779. if ( hasFaceUv ) {
  5780. for ( i = 0; i < nUvLayers; i++ ) {
  5781. uvLayer = json.uvs[ i ];
  5782. uvIndex = faces[ offset ++ ];
  5783. u = uvLayer[ uvIndex * 2 ];
  5784. v = uvLayer[ uvIndex * 2 + 1 ];
  5785. geometry.faceUvs[ i ][ fi ] = new THREE.Vector2( u, v );
  5786. }
  5787. }
  5788. if ( hasFaceVertexUv ) {
  5789. for ( i = 0; i < nUvLayers; i++ ) {
  5790. uvLayer = json.uvs[ i ];
  5791. uvs = [];
  5792. for ( j = 0; j < nVertices; j ++ ) {
  5793. uvIndex = faces[ offset ++ ];
  5794. u = uvLayer[ uvIndex * 2 ];
  5795. v = uvLayer[ uvIndex * 2 + 1 ];
  5796. uvs[ j ] = new THREE.Vector2( u, v );
  5797. }
  5798. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  5799. }
  5800. }
  5801. if ( hasFaceNormal ) {
  5802. normalIndex = faces[ offset ++ ] * 3;
  5803. normal = new THREE.Vector3();
  5804. normal.x = normals[ normalIndex ++ ];
  5805. normal.y = normals[ normalIndex ++ ];
  5806. normal.z = normals[ normalIndex ];
  5807. face.normal = normal;
  5808. }
  5809. if ( hasFaceVertexNormal ) {
  5810. for ( i = 0; i < nVertices; i++ ) {
  5811. normalIndex = faces[ offset ++ ] * 3;
  5812. normal = new THREE.Vector3();
  5813. normal.x = normals[ normalIndex ++ ];
  5814. normal.y = normals[ normalIndex ++ ];
  5815. normal.z = normals[ normalIndex ];
  5816. face.vertexNormals.push( normal );
  5817. }
  5818. }
  5819. if ( hasFaceColor ) {
  5820. colorIndex = faces[ offset ++ ];
  5821. color = new THREE.Color( colors[ colorIndex ] );
  5822. face.color = color;
  5823. }
  5824. if ( hasFaceVertexColor ) {
  5825. for ( i = 0; i < nVertices; i++ ) {
  5826. colorIndex = faces[ offset ++ ];
  5827. color = new THREE.Color( colors[ colorIndex ] );
  5828. face.vertexColors.push( color );
  5829. }
  5830. }
  5831. geometry.faces.push( face );
  5832. }
  5833. };
  5834. function parseSkin() {
  5835. var i, l, x, y, z, w, a, b, c, d;
  5836. if ( json.skinWeights ) {
  5837. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  5838. x = json.skinWeights[ i ];
  5839. y = json.skinWeights[ i + 1 ];
  5840. z = 0;
  5841. w = 0;
  5842. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  5843. }
  5844. }
  5845. if ( json.skinIndices ) {
  5846. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  5847. a = json.skinIndices[ i ];
  5848. b = json.skinIndices[ i + 1 ];
  5849. c = 0;
  5850. d = 0;
  5851. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  5852. }
  5853. }
  5854. geometry.bones = json.bones;
  5855. geometry.animation = json.animation;
  5856. };
  5857. function parseMorphing( scale ) {
  5858. if ( json.morphTargets !== undefined ) {
  5859. var i, l, v, vl, dstVertices, srcVertices;
  5860. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  5861. geometry.morphTargets[ i ] = {};
  5862. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  5863. geometry.morphTargets[ i ].vertices = [];
  5864. dstVertices = geometry.morphTargets[ i ].vertices;
  5865. srcVertices = json.morphTargets [ i ].vertices;
  5866. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  5867. var vertex = new THREE.Vector3();
  5868. vertex.x = srcVertices[ v ] * scale;
  5869. vertex.y = srcVertices[ v + 1 ] * scale;
  5870. vertex.z = srcVertices[ v + 2 ] * scale;
  5871. dstVertices.push( vertex );
  5872. }
  5873. }
  5874. }
  5875. if ( json.morphColors !== undefined ) {
  5876. var i, l, c, cl, dstColors, srcColors, color;
  5877. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  5878. geometry.morphColors[ i ] = {};
  5879. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  5880. geometry.morphColors[ i ].colors = [];
  5881. dstColors = geometry.morphColors[ i ].colors;
  5882. srcColors = json.morphColors [ i ].colors;
  5883. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  5884. color = new THREE.Color( 0xffaa00 );
  5885. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  5886. dstColors.push( color );
  5887. }
  5888. }
  5889. }
  5890. };
  5891. var materials = this.initMaterials( json.materials, texturePath );
  5892. if ( this.needsTangents( materials ) ) geometry.computeTangents();
  5893. callback( geometry, materials );
  5894. };
  5895. /**
  5896. * @author mrdoob / http://mrdoob.com/
  5897. */
  5898. THREE.LoadingMonitor = function () {
  5899. THREE.EventDispatcher.call( this );
  5900. var scope = this;
  5901. var loaded = 0;
  5902. var total = 0;
  5903. var onLoad = function ( event ) {
  5904. loaded ++;
  5905. scope.dispatchEvent( { type: 'progress', loaded: loaded, total: total } );
  5906. if ( loaded === total ) {
  5907. scope.dispatchEvent( { type: 'load' } );
  5908. }
  5909. };
  5910. this.add = function ( loader ) {
  5911. total ++;
  5912. loader.addEventListener( 'load', onLoad, false );
  5913. };
  5914. };
  5915. /**
  5916. * @author alteredq / http://alteredqualia.com/
  5917. */
  5918. THREE.SceneLoader = function () {
  5919. this.onLoadStart = function () {};
  5920. this.onLoadProgress = function() {};
  5921. this.onLoadComplete = function () {};
  5922. this.callbackSync = function () {};
  5923. this.callbackProgress = function () {};
  5924. this.geometryHandlerMap = {};
  5925. this.hierarchyHandlerMap = {};
  5926. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  5927. };
  5928. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  5929. THREE.SceneLoader.prototype.load = function ( url, callbackFinished ) {
  5930. var scope = this;
  5931. var xhr = new XMLHttpRequest();
  5932. xhr.onreadystatechange = function () {
  5933. if ( xhr.readyState === 4 ) {
  5934. if ( xhr.status === 200 || xhr.status === 0 ) {
  5935. var json = JSON.parse( xhr.responseText );
  5936. scope.parse( json, callbackFinished, url );
  5937. } else {
  5938. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5939. }
  5940. }
  5941. };
  5942. xhr.open( "GET", url, true );
  5943. xhr.send( null );
  5944. };
  5945. THREE.SceneLoader.prototype.addGeometryHandler = function ( typeID, loaderClass ) {
  5946. this.geometryHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5947. };
  5948. THREE.SceneLoader.prototype.addHierarchyHandler = function ( typeID, loaderClass ) {
  5949. this.hierarchyHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5950. };
  5951. THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
  5952. var scope = this;
  5953. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  5954. var geometry, material, camera, fog,
  5955. texture, images, color,
  5956. light, hex, intensity,
  5957. counter_models, counter_textures,
  5958. total_models, total_textures,
  5959. result;
  5960. var target_array = [];
  5961. var data = json;
  5962. // async geometry loaders
  5963. for ( var typeID in this.geometryHandlerMap ) {
  5964. var loaderClass = this.geometryHandlerMap[ typeID ][ "loaderClass" ];
  5965. this.geometryHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5966. }
  5967. // async hierachy loaders
  5968. for ( var typeID in this.hierarchyHandlerMap ) {
  5969. var loaderClass = this.hierarchyHandlerMap[ typeID ][ "loaderClass" ];
  5970. this.hierarchyHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5971. }
  5972. counter_models = 0;
  5973. counter_textures = 0;
  5974. result = {
  5975. scene: new THREE.Scene(),
  5976. geometries: {},
  5977. face_materials: {},
  5978. materials: {},
  5979. textures: {},
  5980. objects: {},
  5981. cameras: {},
  5982. lights: {},
  5983. fogs: {},
  5984. empties: {},
  5985. groups: {}
  5986. };
  5987. if ( data.transform ) {
  5988. var position = data.transform.position,
  5989. rotation = data.transform.rotation,
  5990. scale = data.transform.scale;
  5991. if ( position )
  5992. result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
  5993. if ( rotation )
  5994. result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
  5995. if ( scale )
  5996. result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
  5997. if ( position || rotation || scale ) {
  5998. result.scene.updateMatrix();
  5999. result.scene.updateMatrixWorld();
  6000. }
  6001. }
  6002. function get_url( source_url, url_type ) {
  6003. if ( url_type == "relativeToHTML" ) {
  6004. return source_url;
  6005. } else {
  6006. return urlBase + "/" + source_url;
  6007. }
  6008. };
  6009. // toplevel loader function, delegates to handle_children
  6010. function handle_objects() {
  6011. handle_children( result.scene, data.objects );
  6012. }
  6013. // handle all the children from the loaded json and attach them to given parent
  6014. function handle_children( parent, children ) {
  6015. var mat, dst, pos, rot, scl, quat;
  6016. for ( var objID in children ) {
  6017. // check by id if child has already been handled,
  6018. // if not, create new object
  6019. if ( result.objects[ objID ] === undefined ) {
  6020. var objJSON = children[ objID ];
  6021. var object = null;
  6022. // meshes
  6023. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlerMap ) ) {
  6024. if ( objJSON.loading === undefined ) {
  6025. var reservedTypes = { "type": 1, "url": 1, "material": 1,
  6026. "position": 1, "rotation": 1, "scale" : 1,
  6027. "visible": 1, "children": 1, "properties": 1,
  6028. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1 };
  6029. var loaderParameters = {};
  6030. for ( var parType in objJSON ) {
  6031. if ( ! ( parType in reservedTypes ) ) {
  6032. loaderParameters[ parType ] = objJSON[ parType ];
  6033. }
  6034. }
  6035. material = result.materials[ objJSON.material ];
  6036. objJSON.loading = true;
  6037. var loader = scope.hierarchyHandlerMap[ objJSON.type ][ "loaderObject" ];
  6038. // ColladaLoader
  6039. if ( loader.options ) {
  6040. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  6041. // UTF8Loader
  6042. // OBJLoader
  6043. } else {
  6044. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  6045. }
  6046. }
  6047. } else if ( objJSON.geometry !== undefined ) {
  6048. geometry = result.geometries[ objJSON.geometry ];
  6049. // geometry already loaded
  6050. if ( geometry ) {
  6051. var needsTangents = false;
  6052. material = result.materials[ objJSON.material ];
  6053. needsTangents = material instanceof THREE.ShaderMaterial;
  6054. pos = objJSON.position;
  6055. rot = objJSON.rotation;
  6056. scl = objJSON.scale;
  6057. mat = objJSON.matrix;
  6058. quat = objJSON.quaternion;
  6059. // use materials from the model file
  6060. // if there is no material specified in the object
  6061. if ( ! objJSON.material ) {
  6062. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6063. }
  6064. // use materials from the model file
  6065. // if there is just empty face material
  6066. // (must create new material as each model has its own face material)
  6067. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  6068. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6069. }
  6070. if ( material instanceof THREE.MeshFaceMaterial ) {
  6071. for ( var i = 0; i < material.materials.length; i ++ ) {
  6072. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  6073. }
  6074. }
  6075. if ( needsTangents ) {
  6076. geometry.computeTangents();
  6077. }
  6078. if ( objJSON.skin ) {
  6079. object = new THREE.SkinnedMesh( geometry, material );
  6080. } else if ( objJSON.morph ) {
  6081. object = new THREE.MorphAnimMesh( geometry, material );
  6082. if ( objJSON.duration !== undefined ) {
  6083. object.duration = objJSON.duration;
  6084. }
  6085. if ( objJSON.time !== undefined ) {
  6086. object.time = objJSON.time;
  6087. }
  6088. if ( objJSON.mirroredLoop !== undefined ) {
  6089. object.mirroredLoop = objJSON.mirroredLoop;
  6090. }
  6091. if ( material.morphNormals ) {
  6092. geometry.computeMorphNormals();
  6093. }
  6094. } else {
  6095. object = new THREE.Mesh( geometry, material );
  6096. }
  6097. object.name = objID;
  6098. if ( mat ) {
  6099. object.matrixAutoUpdate = false;
  6100. object.matrix.set(
  6101. mat[0], mat[1], mat[2], mat[3],
  6102. mat[4], mat[5], mat[6], mat[7],
  6103. mat[8], mat[9], mat[10], mat[11],
  6104. mat[12], mat[13], mat[14], mat[15]
  6105. );
  6106. } else {
  6107. object.position.set( pos[0], pos[1], pos[2] );
  6108. if ( quat ) {
  6109. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  6110. object.useQuaternion = true;
  6111. } else {
  6112. object.rotation.set( rot[0], rot[1], rot[2] );
  6113. }
  6114. object.scale.set( scl[0], scl[1], scl[2] );
  6115. }
  6116. object.visible = objJSON.visible;
  6117. object.castShadow = objJSON.castShadow;
  6118. object.receiveShadow = objJSON.receiveShadow;
  6119. parent.add( object );
  6120. result.objects[ objID ] = object;
  6121. }
  6122. // lights
  6123. } else if ( objJSON.type === "DirectionalLight" || objJSON.type === "PointLight" || objJSON.type === "AmbientLight" ) {
  6124. hex = ( objJSON.color !== undefined ) ? objJSON.color : 0xffffff;
  6125. intensity = ( objJSON.intensity !== undefined ) ? objJSON.intensity : 1;
  6126. if ( objJSON.type === "DirectionalLight" ) {
  6127. pos = objJSON.direction;
  6128. light = new THREE.DirectionalLight( hex, intensity );
  6129. light.position.set( pos[0], pos[1], pos[2] );
  6130. if ( objJSON.target ) {
  6131. target_array.push( { "object": light, "targetName" : objJSON.target } );
  6132. // kill existing default target
  6133. // otherwise it gets added to scene when parent gets added
  6134. light.target = null;
  6135. }
  6136. } else if ( objJSON.type === "PointLight" ) {
  6137. pos = objJSON.position;
  6138. dst = objJSON.distance;
  6139. light = new THREE.PointLight( hex, intensity, dst );
  6140. light.position.set( pos[0], pos[1], pos[2] );
  6141. } else if ( objJSON.type === "AmbientLight" ) {
  6142. light = new THREE.AmbientLight( hex );
  6143. }
  6144. parent.add( light );
  6145. light.name = objID;
  6146. result.lights[ objID ] = light;
  6147. result.objects[ objID ] = light;
  6148. // cameras
  6149. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  6150. if ( objJSON.type === "PerspectiveCamera" ) {
  6151. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  6152. } else if ( objJSON.type === "OrthographicCamera" ) {
  6153. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  6154. }
  6155. pos = objJSON.position;
  6156. camera.position.set( pos[0], pos[1], pos[2] );
  6157. parent.add( camera );
  6158. camera.name = objID;
  6159. result.cameras[ objID ] = camera;
  6160. result.objects[ objID ] = camera;
  6161. // pure Object3D
  6162. } else {
  6163. pos = objJSON.position;
  6164. rot = objJSON.rotation;
  6165. scl = objJSON.scale;
  6166. quat = objJSON.quaternion;
  6167. object = new THREE.Object3D();
  6168. object.name = objID;
  6169. object.position.set( pos[0], pos[1], pos[2] );
  6170. if ( quat ) {
  6171. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  6172. object.useQuaternion = true;
  6173. } else {
  6174. object.rotation.set( rot[0], rot[1], rot[2] );
  6175. }
  6176. object.scale.set( scl[0], scl[1], scl[2] );
  6177. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  6178. parent.add( object );
  6179. result.objects[ objID ] = object;
  6180. result.empties[ objID ] = object;
  6181. }
  6182. if ( object ) {
  6183. if ( objJSON.properties !== undefined ) {
  6184. for ( var key in objJSON.properties ) {
  6185. var value = objJSON.properties[ key ];
  6186. object.properties[ key ] = value;
  6187. }
  6188. }
  6189. if ( objJSON.groups !== undefined ) {
  6190. for ( var i = 0; i < objJSON.groups.length; i ++ ) {
  6191. var groupID = objJSON.groups[ i ];
  6192. if ( result.groups[ groupID ] === undefined ) {
  6193. result.groups[ groupID ] = [];
  6194. }
  6195. result.groups[ groupID ].push( objID );
  6196. }
  6197. }
  6198. if ( objJSON.children !== undefined ) {
  6199. handle_children( object, objJSON.children );
  6200. }
  6201. }
  6202. }
  6203. }
  6204. };
  6205. function handle_mesh( geo, mat, id ) {
  6206. result.geometries[ id ] = geo;
  6207. result.face_materials[ id ] = mat;
  6208. handle_objects();
  6209. };
  6210. function handle_hierarchy( node, id, parent, material, obj ) {
  6211. var p = obj.position;
  6212. var r = obj.rotation;
  6213. var q = obj.quaternion;
  6214. var s = obj.scale;
  6215. node.position.set( p[0], p[1], p[2] );
  6216. if ( q ) {
  6217. node.quaternion.set( q[0], q[1], q[2], q[3] );
  6218. node.useQuaternion = true;
  6219. } else {
  6220. node.rotation.set( r[0], r[1], r[2] );
  6221. }
  6222. node.scale.set( s[0], s[1], s[2] );
  6223. // override children materials
  6224. // if object material was specified in JSON explicitly
  6225. if ( material ) {
  6226. node.traverse( function ( child ) {
  6227. child.material = material;
  6228. } );
  6229. }
  6230. // override children visibility
  6231. // with root node visibility as specified in JSON
  6232. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  6233. node.traverse( function ( child ) {
  6234. child.visible = visible;
  6235. } );
  6236. parent.add( node );
  6237. node.name = id;
  6238. result.objects[ id ] = node;
  6239. handle_objects();
  6240. };
  6241. function create_callback_geometry( id ) {
  6242. return function( geo, mat ) {
  6243. handle_mesh( geo, mat, id );
  6244. counter_models -= 1;
  6245. scope.onLoadComplete();
  6246. async_callback_gate();
  6247. }
  6248. };
  6249. function create_callback_hierachy( id, parent, material, obj ) {
  6250. return function( event ) {
  6251. var result;
  6252. // loaders which use EventDispatcher
  6253. if ( event.content ) {
  6254. result = event.content;
  6255. // ColladaLoader
  6256. } else if ( event.dae ) {
  6257. result = event.scene;
  6258. // UTF8Loader
  6259. } else {
  6260. result = event;
  6261. }
  6262. handle_hierarchy( result, id, parent, material, obj );
  6263. counter_models -= 1;
  6264. scope.onLoadComplete();
  6265. async_callback_gate();
  6266. }
  6267. };
  6268. function create_callback_embed( id ) {
  6269. return function( geo, mat ) {
  6270. result.geometries[ id ] = geo;
  6271. result.face_materials[ id ] = mat;
  6272. }
  6273. };
  6274. function async_callback_gate() {
  6275. var progress = {
  6276. totalModels : total_models,
  6277. totalTextures : total_textures,
  6278. loadedModels : total_models - counter_models,
  6279. loadedTextures : total_textures - counter_textures
  6280. };
  6281. scope.callbackProgress( progress, result );
  6282. scope.onLoadProgress();
  6283. if ( counter_models === 0 && counter_textures === 0 ) {
  6284. finalize();
  6285. callbackFinished( result );
  6286. }
  6287. };
  6288. function finalize() {
  6289. // take care of targets which could be asynchronously loaded objects
  6290. for ( var i = 0; i < target_array.length; i ++ ) {
  6291. var ta = target_array[ i ];
  6292. var target = result.objects[ ta.targetName ];
  6293. if ( target ) {
  6294. ta.object.target = target;
  6295. } else {
  6296. // if there was error and target of specified name doesn't exist in the scene file
  6297. // create instead dummy target
  6298. // (target must be added to scene explicitly as parent is already added)
  6299. ta.object.target = new THREE.Object3D();
  6300. result.scene.add( ta.object.target );
  6301. }
  6302. ta.object.target.properties.targetInverse = ta.object;
  6303. }
  6304. };
  6305. var callbackTexture = function ( count ) {
  6306. counter_textures -= count;
  6307. async_callback_gate();
  6308. scope.onLoadComplete();
  6309. };
  6310. // must use this instead of just directly calling callbackTexture
  6311. // because of closure in the calling context loop
  6312. var generateTextureCallback = function ( count ) {
  6313. return function() {
  6314. callbackTexture( count );
  6315. };
  6316. };
  6317. // first go synchronous elements
  6318. // fogs
  6319. var fogID, fogJSON;
  6320. for ( fogID in data.fogs ) {
  6321. fogJSON = data.fogs[ fogID ];
  6322. if ( fogJSON.type === "linear" ) {
  6323. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  6324. } else if ( fogJSON.type === "exp2" ) {
  6325. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  6326. }
  6327. color = fogJSON.color;
  6328. fog.color.setRGB( color[0], color[1], color[2] );
  6329. result.fogs[ fogID ] = fog;
  6330. }
  6331. // now come potentially asynchronous elements
  6332. // geometries
  6333. // count how many geometries will be loaded asynchronously
  6334. var geoID, geoJSON;
  6335. for ( geoID in data.geometries ) {
  6336. geoJSON = data.geometries[ geoID ];
  6337. if ( geoJSON.type in this.geometryHandlerMap ) {
  6338. counter_models += 1;
  6339. scope.onLoadStart();
  6340. }
  6341. }
  6342. // count how many hierarchies will be loaded asynchronously
  6343. var objID, objJSON;
  6344. for ( objID in data.objects ) {
  6345. objJSON = data.objects[ objID ];
  6346. if ( objJSON.type && ( objJSON.type in this.hierarchyHandlerMap ) ) {
  6347. counter_models += 1;
  6348. scope.onLoadStart();
  6349. }
  6350. }
  6351. total_models = counter_models;
  6352. for ( geoID in data.geometries ) {
  6353. geoJSON = data.geometries[ geoID ];
  6354. if ( geoJSON.type === "cube" ) {
  6355. geometry = new THREE.CubeGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  6356. result.geometries[ geoID ] = geometry;
  6357. } else if ( geoJSON.type === "plane" ) {
  6358. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  6359. result.geometries[ geoID ] = geometry;
  6360. } else if ( geoJSON.type === "sphere" ) {
  6361. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  6362. result.geometries[ geoID ] = geometry;
  6363. } else if ( geoJSON.type === "cylinder" ) {
  6364. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  6365. result.geometries[ geoID ] = geometry;
  6366. } else if ( geoJSON.type === "torus" ) {
  6367. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  6368. result.geometries[ geoID ] = geometry;
  6369. } else if ( geoJSON.type === "icosahedron" ) {
  6370. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  6371. result.geometries[ geoID ] = geometry;
  6372. } else if ( geoJSON.type in this.geometryHandlerMap ) {
  6373. var loaderParameters = {};
  6374. for ( var parType in geoJSON ) {
  6375. if ( parType !== "type" && parType !== "url" ) {
  6376. loaderParameters[ parType ] = geoJSON[ parType ];
  6377. }
  6378. }
  6379. var loader = this.geometryHandlerMap[ geoJSON.type ][ "loaderObject" ];
  6380. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  6381. } else if ( geoJSON.type === "embedded" ) {
  6382. var modelJson = data.embeds[ geoJSON.id ],
  6383. texture_path = "";
  6384. // pass metadata along to jsonLoader so it knows the format version
  6385. modelJson.metadata = data.metadata;
  6386. if ( modelJson ) {
  6387. var jsonLoader = this.geometryHandlerMap[ "ascii" ][ "loaderObject" ];
  6388. jsonLoader.createModel( modelJson, create_callback_embed( geoID ), texture_path );
  6389. }
  6390. }
  6391. }
  6392. // textures
  6393. // count how many textures will be loaded asynchronously
  6394. var textureID, textureJSON;
  6395. for ( textureID in data.textures ) {
  6396. textureJSON = data.textures[ textureID ];
  6397. if ( textureJSON.url instanceof Array ) {
  6398. counter_textures += textureJSON.url.length;
  6399. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  6400. scope.onLoadStart();
  6401. }
  6402. } else {
  6403. counter_textures += 1;
  6404. scope.onLoadStart();
  6405. }
  6406. }
  6407. total_textures = counter_textures;
  6408. for ( textureID in data.textures ) {
  6409. textureJSON = data.textures[ textureID ];
  6410. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  6411. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  6412. }
  6413. if ( textureJSON.url instanceof Array ) {
  6414. var count = textureJSON.url.length;
  6415. var url_array = [];
  6416. for( var i = 0; i < count; i ++ ) {
  6417. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  6418. }
  6419. var isCompressed = url_array[ 0 ].endsWith( ".dds" );
  6420. if ( isCompressed ) {
  6421. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6422. } else {
  6423. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6424. }
  6425. } else {
  6426. var isCompressed = textureJSON.url.toLowerCase().endsWith( ".dds" );
  6427. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  6428. var textureCallback = generateTextureCallback( 1 );
  6429. if ( isCompressed ) {
  6430. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  6431. } else {
  6432. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  6433. }
  6434. if ( THREE[ textureJSON.minFilter ] !== undefined )
  6435. texture.minFilter = THREE[ textureJSON.minFilter ];
  6436. if ( THREE[ textureJSON.magFilter ] !== undefined )
  6437. texture.magFilter = THREE[ textureJSON.magFilter ];
  6438. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  6439. if ( textureJSON.repeat ) {
  6440. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  6441. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  6442. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  6443. }
  6444. if ( textureJSON.offset ) {
  6445. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  6446. }
  6447. // handle wrap after repeat so that default repeat can be overriden
  6448. if ( textureJSON.wrap ) {
  6449. var wrapMap = {
  6450. "repeat" : THREE.RepeatWrapping,
  6451. "mirror" : THREE.MirroredRepeatWrapping
  6452. }
  6453. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  6454. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  6455. }
  6456. }
  6457. result.textures[ textureID ] = texture;
  6458. }
  6459. // materials
  6460. var matID, matJSON;
  6461. var parID;
  6462. for ( matID in data.materials ) {
  6463. matJSON = data.materials[ matID ];
  6464. for ( parID in matJSON.parameters ) {
  6465. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  6466. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  6467. } else if ( parID === "shading" ) {
  6468. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  6469. } else if ( parID === "side" ) {
  6470. if ( matJSON.parameters[ parID ] == "double" ) {
  6471. matJSON.parameters[ parID ] = THREE.DoubleSide;
  6472. } else if ( matJSON.parameters[ parID ] == "back" ) {
  6473. matJSON.parameters[ parID ] = THREE.BackSide;
  6474. } else {
  6475. matJSON.parameters[ parID ] = THREE.FrontSide;
  6476. }
  6477. } else if ( parID === "blending" ) {
  6478. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  6479. } else if ( parID === "combine" ) {
  6480. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  6481. } else if ( parID === "vertexColors" ) {
  6482. if ( matJSON.parameters[ parID ] == "face" ) {
  6483. matJSON.parameters[ parID ] = THREE.FaceColors;
  6484. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  6485. } else if ( matJSON.parameters[ parID ] ) {
  6486. matJSON.parameters[ parID ] = THREE.VertexColors;
  6487. }
  6488. } else if ( parID === "wrapRGB" ) {
  6489. var v3 = matJSON.parameters[ parID ];
  6490. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  6491. }
  6492. }
  6493. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  6494. matJSON.parameters.transparent = true;
  6495. }
  6496. if ( matJSON.parameters.normalMap ) {
  6497. var shader = THREE.ShaderLib[ "normalmap" ];
  6498. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6499. var diffuse = matJSON.parameters.color;
  6500. var specular = matJSON.parameters.specular;
  6501. var ambient = matJSON.parameters.ambient;
  6502. var shininess = matJSON.parameters.shininess;
  6503. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  6504. if ( matJSON.parameters.normalScale ) {
  6505. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  6506. }
  6507. if ( matJSON.parameters.map ) {
  6508. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  6509. uniforms[ "enableDiffuse" ].value = true;
  6510. }
  6511. if ( matJSON.parameters.envMap ) {
  6512. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  6513. uniforms[ "enableReflection" ].value = true;
  6514. uniforms[ "uReflectivity" ].value = matJSON.parameters.reflectivity;
  6515. }
  6516. if ( matJSON.parameters.lightMap ) {
  6517. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  6518. uniforms[ "enableAO" ].value = true;
  6519. }
  6520. if ( matJSON.parameters.specularMap ) {
  6521. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  6522. uniforms[ "enableSpecular" ].value = true;
  6523. }
  6524. if ( matJSON.parameters.displacementMap ) {
  6525. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  6526. uniforms[ "enableDisplacement" ].value = true;
  6527. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  6528. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  6529. }
  6530. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  6531. uniforms[ "uSpecularColor" ].value.setHex( specular );
  6532. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  6533. uniforms[ "uShininess" ].value = shininess;
  6534. if ( matJSON.parameters.opacity ) {
  6535. uniforms[ "uOpacity" ].value = matJSON.parameters.opacity;
  6536. }
  6537. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6538. material = new THREE.ShaderMaterial( parameters );
  6539. } else {
  6540. material = new THREE[ matJSON.type ]( matJSON.parameters );
  6541. }
  6542. result.materials[ matID ] = material;
  6543. }
  6544. // second pass through all materials to initialize MeshFaceMaterials
  6545. // that could be referring to other materials out of order
  6546. for ( matID in data.materials ) {
  6547. matJSON = data.materials[ matID ];
  6548. if ( matJSON.parameters.materials ) {
  6549. var materialArray = [];
  6550. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  6551. var label = matJSON.parameters.materials[ i ];
  6552. materialArray.push( result.materials[ label ] );
  6553. }
  6554. result.materials[ matID ].materials = materialArray;
  6555. }
  6556. }
  6557. // objects ( synchronous init of procedural primitives )
  6558. handle_objects();
  6559. // defaults
  6560. if ( result.cameras && data.defaults.camera ) {
  6561. result.currentCamera = result.cameras[ data.defaults.camera ];
  6562. }
  6563. if ( result.fogs && data.defaults.fog ) {
  6564. result.scene.fog = result.fogs[ data.defaults.fog ];
  6565. }
  6566. // synchronous callback
  6567. scope.callbackSync( result );
  6568. // just in case there are no async elements
  6569. async_callback_gate();
  6570. };
  6571. /**
  6572. * @author mrdoob / http://mrdoob.com/
  6573. */
  6574. THREE.TextureLoader = function () {
  6575. THREE.EventDispatcher.call( this );
  6576. this.crossOrigin = null;
  6577. };
  6578. THREE.TextureLoader.prototype = {
  6579. constructor: THREE.TextureLoader,
  6580. load: function ( url ) {
  6581. var scope = this;
  6582. var image = new Image();
  6583. image.addEventListener( 'load', function () {
  6584. var texture = new THREE.Texture( image );
  6585. texture.needsUpdate = true;
  6586. scope.dispatchEvent( { type: 'load', content: texture } );
  6587. }, false );
  6588. image.addEventListener( 'error', function () {
  6589. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  6590. }, false );
  6591. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  6592. image.src = url;
  6593. }
  6594. }
  6595. /**
  6596. * @author mrdoob / http://mrdoob.com/
  6597. * @author alteredq / http://alteredqualia.com/
  6598. */
  6599. THREE.Material = function () {
  6600. THREE.EventDispatcher.call( this );
  6601. this.id = THREE.MaterialIdCount ++;
  6602. this.name = '';
  6603. this.side = THREE.FrontSide;
  6604. this.opacity = 1;
  6605. this.transparent = false;
  6606. this.blending = THREE.NormalBlending;
  6607. this.blendSrc = THREE.SrcAlphaFactor;
  6608. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  6609. this.blendEquation = THREE.AddEquation;
  6610. this.depthTest = true;
  6611. this.depthWrite = true;
  6612. this.polygonOffset = false;
  6613. this.polygonOffsetFactor = 0;
  6614. this.polygonOffsetUnits = 0;
  6615. this.alphaTest = 0;
  6616. this.overdraw = false; // Boolean for fixing antialiasing gaps in CanvasRenderer
  6617. this.visible = true;
  6618. this.needsUpdate = true;
  6619. };
  6620. THREE.Material.prototype.setValues = function ( values ) {
  6621. if ( values === undefined ) return;
  6622. for ( var key in values ) {
  6623. var newValue = values[ key ];
  6624. if ( newValue === undefined ) {
  6625. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  6626. continue;
  6627. }
  6628. if ( key in this ) {
  6629. var currentValue = this[ key ];
  6630. if ( currentValue instanceof THREE.Color && newValue instanceof THREE.Color ) {
  6631. currentValue.copy( newValue );
  6632. } else if ( currentValue instanceof THREE.Color ) {
  6633. currentValue.set( newValue );
  6634. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  6635. currentValue.copy( newValue );
  6636. } else {
  6637. this[ key ] = newValue;
  6638. }
  6639. }
  6640. }
  6641. };
  6642. THREE.Material.prototype.clone = function ( material ) {
  6643. if ( material === undefined ) material = new THREE.Material();
  6644. material.name = this.name;
  6645. material.side = this.side;
  6646. material.opacity = this.opacity;
  6647. material.transparent = this.transparent;
  6648. material.blending = this.blending;
  6649. material.blendSrc = this.blendSrc;
  6650. material.blendDst = this.blendDst;
  6651. material.blendEquation = this.blendEquation;
  6652. material.depthTest = this.depthTest;
  6653. material.depthWrite = this.depthWrite;
  6654. material.polygonOffset = this.polygonOffset;
  6655. material.polygonOffsetFactor = this.polygonOffsetFactor;
  6656. material.polygonOffsetUnits = this.polygonOffsetUnits;
  6657. material.alphaTest = this.alphaTest;
  6658. material.overdraw = this.overdraw;
  6659. material.visible = this.visible;
  6660. return material;
  6661. };
  6662. THREE.Material.prototype.dispose = function () {
  6663. this.dispatchEvent( { type: 'dispose' } );
  6664. };
  6665. THREE.MaterialIdCount = 0;
  6666. /**
  6667. * @author mrdoob / http://mrdoob.com/
  6668. * @author alteredq / http://alteredqualia.com/
  6669. *
  6670. * parameters = {
  6671. * color: <hex>,
  6672. * opacity: <float>,
  6673. *
  6674. * blending: THREE.NormalBlending,
  6675. * depthTest: <bool>,
  6676. * depthWrite: <bool>,
  6677. *
  6678. * linewidth: <float>,
  6679. * linecap: "round",
  6680. * linejoin: "round",
  6681. *
  6682. * vertexColors: <bool>
  6683. *
  6684. * fog: <bool>
  6685. * }
  6686. */
  6687. THREE.LineBasicMaterial = function ( parameters ) {
  6688. THREE.Material.call( this );
  6689. this.color = new THREE.Color( 0xffffff );
  6690. this.linewidth = 1;
  6691. this.linecap = 'round';
  6692. this.linejoin = 'round';
  6693. this.vertexColors = false;
  6694. this.fog = true;
  6695. this.setValues( parameters );
  6696. };
  6697. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6698. THREE.LineBasicMaterial.prototype.clone = function () {
  6699. var material = new THREE.LineBasicMaterial();
  6700. THREE.Material.prototype.clone.call( this, material );
  6701. material.color.copy( this.color );
  6702. material.linewidth = this.linewidth;
  6703. material.linecap = this.linecap;
  6704. material.linejoin = this.linejoin;
  6705. material.vertexColors = this.vertexColors;
  6706. material.fog = this.fog;
  6707. return material;
  6708. };
  6709. /**
  6710. * @author alteredq / http://alteredqualia.com/
  6711. *
  6712. * parameters = {
  6713. * color: <hex>,
  6714. * opacity: <float>,
  6715. *
  6716. * blending: THREE.NormalBlending,
  6717. * depthTest: <bool>,
  6718. * depthWrite: <bool>,
  6719. *
  6720. * linewidth: <float>,
  6721. *
  6722. * scale: <float>,
  6723. * dashSize: <float>,
  6724. * gapSize: <float>,
  6725. *
  6726. * vertexColors: <bool>
  6727. *
  6728. * fog: <bool>
  6729. * }
  6730. */
  6731. THREE.LineDashedMaterial = function ( parameters ) {
  6732. THREE.Material.call( this );
  6733. this.color = new THREE.Color( 0xffffff );
  6734. this.linewidth = 1;
  6735. this.scale = 1;
  6736. this.dashSize = 3;
  6737. this.gapSize = 1;
  6738. this.vertexColors = false;
  6739. this.fog = true;
  6740. this.setValues( parameters );
  6741. };
  6742. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  6743. THREE.LineDashedMaterial.prototype.clone = function () {
  6744. var material = new THREE.LineDashedMaterial();
  6745. THREE.Material.prototype.clone.call( this, material );
  6746. material.color.copy( this.color );
  6747. material.linewidth = this.linewidth;
  6748. material.scale = this.scale;
  6749. material.dashSize = this.dashSize;
  6750. material.gapSize = this.gapSize;
  6751. material.vertexColors = this.vertexColors;
  6752. material.fog = this.fog;
  6753. return material;
  6754. };
  6755. /**
  6756. * @author mrdoob / http://mrdoob.com/
  6757. * @author alteredq / http://alteredqualia.com/
  6758. *
  6759. * parameters = {
  6760. * color: <hex>,
  6761. * opacity: <float>,
  6762. * map: new THREE.Texture( <Image> ),
  6763. *
  6764. * lightMap: new THREE.Texture( <Image> ),
  6765. *
  6766. * specularMap: new THREE.Texture( <Image> ),
  6767. *
  6768. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6769. * combine: THREE.Multiply,
  6770. * reflectivity: <float>,
  6771. * refractionRatio: <float>,
  6772. *
  6773. * shading: THREE.SmoothShading,
  6774. * blending: THREE.NormalBlending,
  6775. * depthTest: <bool>,
  6776. * depthWrite: <bool>,
  6777. *
  6778. * wireframe: <boolean>,
  6779. * wireframeLinewidth: <float>,
  6780. *
  6781. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6782. *
  6783. * skinning: <bool>,
  6784. * morphTargets: <bool>,
  6785. *
  6786. * fog: <bool>
  6787. * }
  6788. */
  6789. THREE.MeshBasicMaterial = function ( parameters ) {
  6790. THREE.Material.call( this );
  6791. this.color = new THREE.Color( 0xffffff ); // emissive
  6792. this.map = null;
  6793. this.lightMap = null;
  6794. this.specularMap = null;
  6795. this.envMap = null;
  6796. this.combine = THREE.MultiplyOperation;
  6797. this.reflectivity = 1;
  6798. this.refractionRatio = 0.98;
  6799. this.fog = true;
  6800. this.shading = THREE.SmoothShading;
  6801. this.wireframe = false;
  6802. this.wireframeLinewidth = 1;
  6803. this.wireframeLinecap = 'round';
  6804. this.wireframeLinejoin = 'round';
  6805. this.vertexColors = THREE.NoColors;
  6806. this.skinning = false;
  6807. this.morphTargets = false;
  6808. this.setValues( parameters );
  6809. };
  6810. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6811. THREE.MeshBasicMaterial.prototype.clone = function () {
  6812. var material = new THREE.MeshBasicMaterial();
  6813. THREE.Material.prototype.clone.call( this, material );
  6814. material.color.copy( this.color );
  6815. material.map = this.map;
  6816. material.lightMap = this.lightMap;
  6817. material.specularMap = this.specularMap;
  6818. material.envMap = this.envMap;
  6819. material.combine = this.combine;
  6820. material.reflectivity = this.reflectivity;
  6821. material.refractionRatio = this.refractionRatio;
  6822. material.fog = this.fog;
  6823. material.shading = this.shading;
  6824. material.wireframe = this.wireframe;
  6825. material.wireframeLinewidth = this.wireframeLinewidth;
  6826. material.wireframeLinecap = this.wireframeLinecap;
  6827. material.wireframeLinejoin = this.wireframeLinejoin;
  6828. material.vertexColors = this.vertexColors;
  6829. material.skinning = this.skinning;
  6830. material.morphTargets = this.morphTargets;
  6831. return material;
  6832. };
  6833. /**
  6834. * @author mrdoob / http://mrdoob.com/
  6835. * @author alteredq / http://alteredqualia.com/
  6836. *
  6837. * parameters = {
  6838. * color: <hex>,
  6839. * ambient: <hex>,
  6840. * emissive: <hex>,
  6841. * opacity: <float>,
  6842. *
  6843. * map: new THREE.Texture( <Image> ),
  6844. *
  6845. * lightMap: new THREE.Texture( <Image> ),
  6846. *
  6847. * specularMap: new THREE.Texture( <Image> ),
  6848. *
  6849. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6850. * combine: THREE.Multiply,
  6851. * reflectivity: <float>,
  6852. * refractionRatio: <float>,
  6853. *
  6854. * shading: THREE.SmoothShading,
  6855. * blending: THREE.NormalBlending,
  6856. * depthTest: <bool>,
  6857. * depthWrite: <bool>,
  6858. *
  6859. * wireframe: <boolean>,
  6860. * wireframeLinewidth: <float>,
  6861. *
  6862. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6863. *
  6864. * skinning: <bool>,
  6865. * morphTargets: <bool>,
  6866. * morphNormals: <bool>,
  6867. *
  6868. * fog: <bool>
  6869. * }
  6870. */
  6871. THREE.MeshLambertMaterial = function ( parameters ) {
  6872. THREE.Material.call( this );
  6873. this.color = new THREE.Color( 0xffffff ); // diffuse
  6874. this.ambient = new THREE.Color( 0xffffff );
  6875. this.emissive = new THREE.Color( 0x000000 );
  6876. this.wrapAround = false;
  6877. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6878. this.map = null;
  6879. this.lightMap = null;
  6880. this.specularMap = null;
  6881. this.envMap = null;
  6882. this.combine = THREE.MultiplyOperation;
  6883. this.reflectivity = 1;
  6884. this.refractionRatio = 0.98;
  6885. this.fog = true;
  6886. this.shading = THREE.SmoothShading;
  6887. this.wireframe = false;
  6888. this.wireframeLinewidth = 1;
  6889. this.wireframeLinecap = 'round';
  6890. this.wireframeLinejoin = 'round';
  6891. this.vertexColors = THREE.NoColors;
  6892. this.skinning = false;
  6893. this.morphTargets = false;
  6894. this.morphNormals = false;
  6895. this.setValues( parameters );
  6896. };
  6897. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  6898. THREE.MeshLambertMaterial.prototype.clone = function () {
  6899. var material = new THREE.MeshLambertMaterial();
  6900. THREE.Material.prototype.clone.call( this, material );
  6901. material.color.copy( this.color );
  6902. material.ambient.copy( this.ambient );
  6903. material.emissive.copy( this.emissive );
  6904. material.wrapAround = this.wrapAround;
  6905. material.wrapRGB.copy( this.wrapRGB );
  6906. material.map = this.map;
  6907. material.lightMap = this.lightMap;
  6908. material.specularMap = this.specularMap;
  6909. material.envMap = this.envMap;
  6910. material.combine = this.combine;
  6911. material.reflectivity = this.reflectivity;
  6912. material.refractionRatio = this.refractionRatio;
  6913. material.fog = this.fog;
  6914. material.shading = this.shading;
  6915. material.wireframe = this.wireframe;
  6916. material.wireframeLinewidth = this.wireframeLinewidth;
  6917. material.wireframeLinecap = this.wireframeLinecap;
  6918. material.wireframeLinejoin = this.wireframeLinejoin;
  6919. material.vertexColors = this.vertexColors;
  6920. material.skinning = this.skinning;
  6921. material.morphTargets = this.morphTargets;
  6922. material.morphNormals = this.morphNormals;
  6923. return material;
  6924. };
  6925. /**
  6926. * @author mrdoob / http://mrdoob.com/
  6927. * @author alteredq / http://alteredqualia.com/
  6928. *
  6929. * parameters = {
  6930. * color: <hex>,
  6931. * ambient: <hex>,
  6932. * emissive: <hex>,
  6933. * specular: <hex>,
  6934. * shininess: <float>,
  6935. * opacity: <float>,
  6936. *
  6937. * map: new THREE.Texture( <Image> ),
  6938. *
  6939. * lightMap: new THREE.Texture( <Image> ),
  6940. *
  6941. * bumpMap: new THREE.Texture( <Image> ),
  6942. * bumpScale: <float>,
  6943. *
  6944. * normalMap: new THREE.Texture( <Image> ),
  6945. * normalScale: <Vector2>,
  6946. *
  6947. * specularMap: new THREE.Texture( <Image> ),
  6948. *
  6949. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6950. * combine: THREE.Multiply,
  6951. * reflectivity: <float>,
  6952. * refractionRatio: <float>,
  6953. *
  6954. * shading: THREE.SmoothShading,
  6955. * blending: THREE.NormalBlending,
  6956. * depthTest: <bool>,
  6957. * depthWrite: <bool>,
  6958. *
  6959. * wireframe: <boolean>,
  6960. * wireframeLinewidth: <float>,
  6961. *
  6962. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6963. *
  6964. * skinning: <bool>,
  6965. * morphTargets: <bool>,
  6966. * morphNormals: <bool>,
  6967. *
  6968. * fog: <bool>
  6969. * }
  6970. */
  6971. THREE.MeshPhongMaterial = function ( parameters ) {
  6972. THREE.Material.call( this );
  6973. this.color = new THREE.Color( 0xffffff ); // diffuse
  6974. this.ambient = new THREE.Color( 0xffffff );
  6975. this.emissive = new THREE.Color( 0x000000 );
  6976. this.specular = new THREE.Color( 0x111111 );
  6977. this.shininess = 30;
  6978. this.metal = false;
  6979. this.perPixel = true;
  6980. this.wrapAround = false;
  6981. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6982. this.map = null;
  6983. this.lightMap = null;
  6984. this.bumpMap = null;
  6985. this.bumpScale = 1;
  6986. this.normalMap = null;
  6987. this.normalScale = new THREE.Vector2( 1, 1 );
  6988. this.specularMap = null;
  6989. this.envMap = null;
  6990. this.combine = THREE.MultiplyOperation;
  6991. this.reflectivity = 1;
  6992. this.refractionRatio = 0.98;
  6993. this.fog = true;
  6994. this.shading = THREE.SmoothShading;
  6995. this.wireframe = false;
  6996. this.wireframeLinewidth = 1;
  6997. this.wireframeLinecap = 'round';
  6998. this.wireframeLinejoin = 'round';
  6999. this.vertexColors = THREE.NoColors;
  7000. this.skinning = false;
  7001. this.morphTargets = false;
  7002. this.morphNormals = false;
  7003. this.setValues( parameters );
  7004. };
  7005. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  7006. THREE.MeshPhongMaterial.prototype.clone = function () {
  7007. var material = new THREE.MeshPhongMaterial();
  7008. THREE.Material.prototype.clone.call( this, material );
  7009. material.color.copy( this.color );
  7010. material.ambient.copy( this.ambient );
  7011. material.emissive.copy( this.emissive );
  7012. material.specular.copy( this.specular );
  7013. material.shininess = this.shininess;
  7014. material.metal = this.metal;
  7015. material.perPixel = this.perPixel;
  7016. material.wrapAround = this.wrapAround;
  7017. material.wrapRGB.copy( this.wrapRGB );
  7018. material.map = this.map;
  7019. material.lightMap = this.lightMap;
  7020. material.bumpMap = this.bumpMap;
  7021. material.bumpScale = this.bumpScale;
  7022. material.normalMap = this.normalMap;
  7023. material.normalScale.copy( this.normalScale );
  7024. material.specularMap = this.specularMap;
  7025. material.envMap = this.envMap;
  7026. material.combine = this.combine;
  7027. material.reflectivity = this.reflectivity;
  7028. material.refractionRatio = this.refractionRatio;
  7029. material.fog = this.fog;
  7030. material.shading = this.shading;
  7031. material.wireframe = this.wireframe;
  7032. material.wireframeLinewidth = this.wireframeLinewidth;
  7033. material.wireframeLinecap = this.wireframeLinecap;
  7034. material.wireframeLinejoin = this.wireframeLinejoin;
  7035. material.vertexColors = this.vertexColors;
  7036. material.skinning = this.skinning;
  7037. material.morphTargets = this.morphTargets;
  7038. material.morphNormals = this.morphNormals;
  7039. return material;
  7040. };
  7041. /**
  7042. * @author mrdoob / http://mrdoob.com/
  7043. * @author alteredq / http://alteredqualia.com/
  7044. *
  7045. * parameters = {
  7046. * opacity: <float>,
  7047. *
  7048. * blending: THREE.NormalBlending,
  7049. * depthTest: <bool>,
  7050. * depthWrite: <bool>,
  7051. *
  7052. * wireframe: <boolean>,
  7053. * wireframeLinewidth: <float>
  7054. * }
  7055. */
  7056. THREE.MeshDepthMaterial = function ( parameters ) {
  7057. THREE.Material.call( this );
  7058. this.wireframe = false;
  7059. this.wireframeLinewidth = 1;
  7060. this.setValues( parameters );
  7061. };
  7062. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  7063. THREE.MeshDepthMaterial.prototype.clone = function () {
  7064. var material = new THREE.LineBasicMaterial();
  7065. THREE.Material.prototype.clone.call( this, material );
  7066. material.wireframe = this.wireframe;
  7067. material.wireframeLinewidth = this.wireframeLinewidth;
  7068. return material;
  7069. };
  7070. /**
  7071. * @author mrdoob / http://mrdoob.com/
  7072. *
  7073. * parameters = {
  7074. * opacity: <float>,
  7075. *
  7076. * shading: THREE.FlatShading,
  7077. * blending: THREE.NormalBlending,
  7078. * depthTest: <bool>,
  7079. * depthWrite: <bool>,
  7080. *
  7081. * wireframe: <boolean>,
  7082. * wireframeLinewidth: <float>
  7083. * }
  7084. */
  7085. THREE.MeshNormalMaterial = function ( parameters ) {
  7086. THREE.Material.call( this, parameters );
  7087. this.shading = THREE.FlatShading;
  7088. this.wireframe = false;
  7089. this.wireframeLinewidth = 1;
  7090. this.setValues( parameters );
  7091. };
  7092. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  7093. THREE.MeshNormalMaterial.prototype.clone = function () {
  7094. var material = new THREE.MeshNormalMaterial();
  7095. THREE.Material.prototype.clone.call( this, material );
  7096. material.shading = this.shading;
  7097. material.wireframe = this.wireframe;
  7098. material.wireframeLinewidth = this.wireframeLinewidth;
  7099. return material;
  7100. };
  7101. /**
  7102. * @author mrdoob / http://mrdoob.com/
  7103. */
  7104. THREE.MeshFaceMaterial = function ( materials ) {
  7105. this.materials = materials instanceof Array ? materials : [];
  7106. };
  7107. THREE.MeshFaceMaterial.prototype.clone = function () {
  7108. return new THREE.MeshFaceMaterial( this.materials.slice( 0 ) );
  7109. };
  7110. /**
  7111. * @author mrdoob / http://mrdoob.com/
  7112. * @author alteredq / http://alteredqualia.com/
  7113. *
  7114. * parameters = {
  7115. * color: <hex>,
  7116. * opacity: <float>,
  7117. * map: new THREE.Texture( <Image> ),
  7118. *
  7119. * size: <float>,
  7120. *
  7121. * blending: THREE.NormalBlending,
  7122. * depthTest: <bool>,
  7123. * depthWrite: <bool>,
  7124. *
  7125. * vertexColors: <bool>,
  7126. *
  7127. * fog: <bool>
  7128. * }
  7129. */
  7130. THREE.ParticleBasicMaterial = function ( parameters ) {
  7131. THREE.Material.call( this );
  7132. this.color = new THREE.Color( 0xffffff );
  7133. this.map = null;
  7134. this.size = 1;
  7135. this.sizeAttenuation = true;
  7136. this.vertexColors = false;
  7137. this.fog = true;
  7138. this.setValues( parameters );
  7139. };
  7140. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7141. THREE.ParticleBasicMaterial.prototype.clone = function () {
  7142. var material = new THREE.ParticleBasicMaterial();
  7143. THREE.Material.prototype.clone.call( this, material );
  7144. material.color.copy( this.color );
  7145. material.map = this.map;
  7146. material.size = this.size;
  7147. material.sizeAttenuation = this.sizeAttenuation;
  7148. material.vertexColors = this.vertexColors;
  7149. material.fog = this.fog;
  7150. return material;
  7151. };
  7152. /**
  7153. * @author mrdoob / http://mrdoob.com/
  7154. *
  7155. * parameters = {
  7156. * color: <hex>,
  7157. * program: <function>,
  7158. * opacity: <float>,
  7159. * blending: THREE.NormalBlending
  7160. * }
  7161. */
  7162. THREE.ParticleCanvasMaterial = function ( parameters ) {
  7163. THREE.Material.call( this );
  7164. this.color = new THREE.Color( 0xffffff );
  7165. this.program = function ( context, color ) {};
  7166. this.setValues( parameters );
  7167. };
  7168. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  7169. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  7170. var material = new THREE.ParticleCanvasMaterial();
  7171. THREE.Material.prototype.clone.call( this, material );
  7172. material.color.copy( this.color );
  7173. material.program = this.program;
  7174. return material;
  7175. };
  7176. /**
  7177. * @author alteredq / http://alteredqualia.com/
  7178. *
  7179. * parameters = {
  7180. * fragmentShader: <string>,
  7181. * vertexShader: <string>,
  7182. *
  7183. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  7184. *
  7185. * defines: { "label" : "value" },
  7186. *
  7187. * shading: THREE.SmoothShading,
  7188. * blending: THREE.NormalBlending,
  7189. * depthTest: <bool>,
  7190. * depthWrite: <bool>,
  7191. *
  7192. * wireframe: <boolean>,
  7193. * wireframeLinewidth: <float>,
  7194. *
  7195. * lights: <bool>,
  7196. *
  7197. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7198. *
  7199. * skinning: <bool>,
  7200. * morphTargets: <bool>,
  7201. * morphNormals: <bool>,
  7202. *
  7203. * fog: <bool>
  7204. * }
  7205. */
  7206. THREE.ShaderMaterial = function ( parameters ) {
  7207. THREE.Material.call( this );
  7208. this.fragmentShader = "void main() {}";
  7209. this.vertexShader = "void main() {}";
  7210. this.uniforms = {};
  7211. this.defines = {};
  7212. this.attributes = null;
  7213. this.shading = THREE.SmoothShading;
  7214. this.wireframe = false;
  7215. this.wireframeLinewidth = 1;
  7216. this.fog = false; // set to use scene fog
  7217. this.lights = false; // set to use scene lights
  7218. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  7219. this.skinning = false; // set to use skinning attribute streams
  7220. this.morphTargets = false; // set to use morph targets
  7221. this.morphNormals = false; // set to use morph normals
  7222. this.setValues( parameters );
  7223. };
  7224. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  7225. THREE.ShaderMaterial.prototype.clone = function () {
  7226. var material = new THREE.ShaderMaterial();
  7227. THREE.Material.prototype.clone.call( this, material );
  7228. material.fragmentShader = this.fragmentShader;
  7229. material.vertexShader = this.vertexShader;
  7230. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  7231. material.attributes = this.attributes;
  7232. material.defines = this.defines;
  7233. material.shading = this.shading;
  7234. material.wireframe = this.wireframe;
  7235. material.wireframeLinewidth = this.wireframeLinewidth;
  7236. material.fog = this.fog;
  7237. material.lights = this.lights;
  7238. material.vertexColors = this.vertexColors;
  7239. material.skinning = this.skinning;
  7240. material.morphTargets = this.morphTargets;
  7241. material.morphNormals = this.morphNormals;
  7242. return material;
  7243. };
  7244. /**
  7245. * @author alteredq / http://alteredqualia.com/
  7246. *
  7247. * parameters = {
  7248. * color: <hex>,
  7249. * opacity: <float>,
  7250. * map: new THREE.Texture( <Image> ),
  7251. *
  7252. * blending: THREE.NormalBlending,
  7253. * depthTest: <bool>,
  7254. * depthWrite: <bool>,
  7255. *
  7256. * useScreenCoordinates: <bool>,
  7257. * sizeAttenuation: <bool>,
  7258. * scaleByViewport: <bool>,
  7259. * alignment: THREE.SpriteAlignment.center,
  7260. *
  7261. * uvOffset: new THREE.Vector2(),
  7262. * uvScale: new THREE.Vector2(),
  7263. *
  7264. * fog: <bool>
  7265. * }
  7266. */
  7267. THREE.SpriteMaterial = function ( parameters ) {
  7268. THREE.Material.call( this );
  7269. // defaults
  7270. this.color = new THREE.Color( 0xffffff );
  7271. this.map = new THREE.Texture();
  7272. this.useScreenCoordinates = true;
  7273. this.depthTest = !this.useScreenCoordinates;
  7274. this.sizeAttenuation = !this.useScreenCoordinates;
  7275. this.scaleByViewport = !this.sizeAttenuation;
  7276. this.alignment = THREE.SpriteAlignment.center.clone();
  7277. this.fog = false;
  7278. this.uvOffset = new THREE.Vector2( 0, 0 );
  7279. this.uvScale = new THREE.Vector2( 1, 1 );
  7280. // set parameters
  7281. this.setValues( parameters );
  7282. // override coupled defaults if not specified explicitly by parameters
  7283. parameters = parameters || {};
  7284. if ( parameters.depthTest === undefined ) this.depthTest = !this.useScreenCoordinates;
  7285. if ( parameters.sizeAttenuation === undefined ) this.sizeAttenuation = !this.useScreenCoordinates;
  7286. if ( parameters.scaleByViewport === undefined ) this.scaleByViewport = !this.sizeAttenuation;
  7287. };
  7288. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  7289. THREE.SpriteMaterial.prototype.clone = function () {
  7290. var material = new THREE.SpriteMaterial();
  7291. THREE.Material.prototype.clone.call( this, material );
  7292. material.color.copy( this.color );
  7293. material.map = this.map;
  7294. material.useScreenCoordinates = this.useScreenCoordinates;
  7295. material.sizeAttenuation = this.sizeAttenuation;
  7296. material.scaleByViewport = this.scaleByViewport;
  7297. material.alignment.copy( this.alignment );
  7298. material.uvOffset.copy( this.uvOffset );
  7299. material.uvScale.copy( this.uvScale );
  7300. material.fog = this.fog;
  7301. return material;
  7302. };
  7303. // Alignment enums
  7304. THREE.SpriteAlignment = {};
  7305. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  7306. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  7307. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  7308. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  7309. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  7310. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  7311. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  7312. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  7313. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  7314. /**
  7315. * @author mrdoob / http://mrdoob.com/
  7316. * @author alteredq / http://alteredqualia.com/
  7317. * @author szimek / https://github.com/szimek/
  7318. */
  7319. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  7320. THREE.EventDispatcher.call( this );
  7321. this.id = THREE.TextureIdCount ++;
  7322. this.name = '';
  7323. this.image = image;
  7324. this.mipmaps = [];
  7325. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  7326. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  7327. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  7328. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  7329. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  7330. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  7331. this.format = format !== undefined ? format : THREE.RGBAFormat;
  7332. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  7333. this.offset = new THREE.Vector2( 0, 0 );
  7334. this.repeat = new THREE.Vector2( 1, 1 );
  7335. this.generateMipmaps = true;
  7336. this.premultiplyAlpha = false;
  7337. this.flipY = true;
  7338. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  7339. this.needsUpdate = false;
  7340. this.onUpdate = null;
  7341. };
  7342. THREE.Texture.prototype = {
  7343. constructor: THREE.Texture,
  7344. clone: function ( texture ) {
  7345. if ( texture === undefined ) texture = new THREE.Texture();
  7346. texture.image = this.image;
  7347. texture.mipmaps = this.mipmaps.slice(0);
  7348. texture.mapping = this.mapping;
  7349. texture.wrapS = this.wrapS;
  7350. texture.wrapT = this.wrapT;
  7351. texture.magFilter = this.magFilter;
  7352. texture.minFilter = this.minFilter;
  7353. texture.anisotropy = this.anisotropy;
  7354. texture.format = this.format;
  7355. texture.type = this.type;
  7356. texture.offset.copy( this.offset );
  7357. texture.repeat.copy( this.repeat );
  7358. texture.generateMipmaps = this.generateMipmaps;
  7359. texture.premultiplyAlpha = this.premultiplyAlpha;
  7360. texture.flipY = this.flipY;
  7361. texture.unpackAlignment = this.unpackAlignment;
  7362. return texture;
  7363. },
  7364. dispose: function () {
  7365. this.dispatchEvent( { type: 'dispose' } );
  7366. }
  7367. };
  7368. THREE.TextureIdCount = 0;
  7369. /**
  7370. * @author alteredq / http://alteredqualia.com/
  7371. */
  7372. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7373. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7374. this.image = { width: width, height: height };
  7375. this.mipmaps = mipmaps;
  7376. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  7377. };
  7378. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  7379. THREE.CompressedTexture.prototype.clone = function () {
  7380. var texture = new THREE.CompressedTexture();
  7381. THREE.Texture.prototype.clone.call( this, texture );
  7382. return texture;
  7383. };
  7384. /**
  7385. * @author alteredq / http://alteredqualia.com/
  7386. */
  7387. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7388. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7389. this.image = { data: data, width: width, height: height };
  7390. };
  7391. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  7392. THREE.DataTexture.prototype.clone = function () {
  7393. var texture = new THREE.DataTexture();
  7394. THREE.Texture.prototype.clone.call( this, texture );
  7395. return texture;
  7396. };
  7397. /**
  7398. * @author mrdoob / http://mrdoob.com/
  7399. */
  7400. THREE.Particle = function ( material ) {
  7401. THREE.Object3D.call( this );
  7402. this.material = material;
  7403. };
  7404. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  7405. THREE.Particle.prototype.clone = function ( object ) {
  7406. if ( object === undefined ) object = new THREE.Particle( this.material );
  7407. THREE.Object3D.prototype.clone.call( this, object );
  7408. return object;
  7409. };
  7410. /**
  7411. * @author alteredq / http://alteredqualia.com/
  7412. */
  7413. THREE.ParticleSystem = function ( geometry, material ) {
  7414. THREE.Object3D.call( this );
  7415. this.geometry = geometry;
  7416. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  7417. this.sortParticles = false;
  7418. if ( this.geometry ) {
  7419. // calc bound radius
  7420. if( this.geometry.boundingSphere === null ) {
  7421. this.geometry.computeBoundingSphere();
  7422. }
  7423. }
  7424. this.frustumCulled = false;
  7425. };
  7426. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  7427. THREE.ParticleSystem.prototype.clone = function ( object ) {
  7428. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  7429. object.sortParticles = this.sortParticles;
  7430. THREE.Object3D.prototype.clone.call( this, object );
  7431. return object;
  7432. };
  7433. /**
  7434. * @author mrdoob / http://mrdoob.com/
  7435. */
  7436. THREE.Line = function ( geometry, material, type ) {
  7437. THREE.Object3D.call( this );
  7438. this.geometry = geometry;
  7439. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  7440. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  7441. if ( this.geometry ) {
  7442. if ( ! this.geometry.boundingSphere ) {
  7443. this.geometry.computeBoundingSphere();
  7444. }
  7445. }
  7446. };
  7447. THREE.LineStrip = 0;
  7448. THREE.LinePieces = 1;
  7449. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  7450. THREE.Line.prototype.clone = function ( object ) {
  7451. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  7452. THREE.Object3D.prototype.clone.call( this, object );
  7453. return object;
  7454. };
  7455. /**
  7456. * @author mrdoob / http://mrdoob.com/
  7457. * @author alteredq / http://alteredqualia.com/
  7458. * @author mikael emtinger / http://gomo.se/
  7459. * @author jonobr1 / http://jonobr1.com/
  7460. */
  7461. THREE.Mesh = function ( geometry, material ) {
  7462. THREE.Object3D.call( this );
  7463. this.geometry = geometry;
  7464. this.material = ( material !== undefined ) ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  7465. if ( this.geometry !== undefined ) {
  7466. if ( this.geometry.boundingSphere === null ) {
  7467. this.geometry.computeBoundingSphere();
  7468. }
  7469. this.updateMorphTargets();
  7470. }
  7471. };
  7472. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  7473. THREE.Mesh.prototype.updateMorphTargets = function () {
  7474. if ( this.geometry.morphTargets.length > 0 ) {
  7475. this.morphTargetBase = -1;
  7476. this.morphTargetForcedOrder = [];
  7477. this.morphTargetInfluences = [];
  7478. this.morphTargetDictionary = {};
  7479. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  7480. this.morphTargetInfluences.push( 0 );
  7481. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  7482. }
  7483. }
  7484. };
  7485. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  7486. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  7487. return this.morphTargetDictionary[ name ];
  7488. }
  7489. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  7490. return 0;
  7491. };
  7492. THREE.Mesh.prototype.clone = function ( object ) {
  7493. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  7494. THREE.Object3D.prototype.clone.call( this, object );
  7495. return object;
  7496. };
  7497. /**
  7498. * @author mikael emtinger / http://gomo.se/
  7499. * @author alteredq / http://alteredqualia.com/
  7500. */
  7501. THREE.Bone = function( belongsToSkin ) {
  7502. THREE.Object3D.call( this );
  7503. this.skin = belongsToSkin;
  7504. this.skinMatrix = new THREE.Matrix4();
  7505. };
  7506. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  7507. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  7508. // update local
  7509. if ( this.matrixAutoUpdate ) {
  7510. forceUpdate |= this.updateMatrix();
  7511. }
  7512. // update skin matrix
  7513. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  7514. if( parentSkinMatrix ) {
  7515. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  7516. } else {
  7517. this.skinMatrix.copy( this.matrix );
  7518. }
  7519. this.matrixWorldNeedsUpdate = false;
  7520. forceUpdate = true;
  7521. }
  7522. // update children
  7523. var child, i, l = this.children.length;
  7524. for ( i = 0; i < l; i ++ ) {
  7525. this.children[ i ].update( this.skinMatrix, forceUpdate );
  7526. }
  7527. };
  7528. /**
  7529. * @author mikael emtinger / http://gomo.se/
  7530. * @author alteredq / http://alteredqualia.com/
  7531. */
  7532. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  7533. THREE.Mesh.call( this, geometry, material );
  7534. //
  7535. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  7536. // init bones
  7537. this.identityMatrix = new THREE.Matrix4();
  7538. this.bones = [];
  7539. this.boneMatrices = [];
  7540. var b, bone, gbone, p, q, s;
  7541. if ( this.geometry && this.geometry.bones !== undefined ) {
  7542. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  7543. gbone = this.geometry.bones[ b ];
  7544. p = gbone.pos;
  7545. q = gbone.rotq;
  7546. s = gbone.scl;
  7547. bone = this.addBone();
  7548. bone.name = gbone.name;
  7549. bone.position.set( p[0], p[1], p[2] );
  7550. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  7551. bone.useQuaternion = true;
  7552. if ( s !== undefined ) {
  7553. bone.scale.set( s[0], s[1], s[2] );
  7554. } else {
  7555. bone.scale.set( 1, 1, 1 );
  7556. }
  7557. }
  7558. for ( b = 0; b < this.bones.length; b ++ ) {
  7559. gbone = this.geometry.bones[ b ];
  7560. bone = this.bones[ b ];
  7561. if ( gbone.parent === -1 ) {
  7562. this.add( bone );
  7563. } else {
  7564. this.bones[ gbone.parent ].add( bone );
  7565. }
  7566. }
  7567. //
  7568. var nBones = this.bones.length;
  7569. if ( this.useVertexTexture ) {
  7570. // layout (1 matrix = 4 pixels)
  7571. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  7572. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  7573. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  7574. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  7575. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  7576. var size;
  7577. if ( nBones > 256 )
  7578. size = 64;
  7579. else if ( nBones > 64 )
  7580. size = 32;
  7581. else if ( nBones > 16 )
  7582. size = 16;
  7583. else
  7584. size = 8;
  7585. this.boneTextureWidth = size;
  7586. this.boneTextureHeight = size;
  7587. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  7588. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  7589. this.boneTexture.minFilter = THREE.NearestFilter;
  7590. this.boneTexture.magFilter = THREE.NearestFilter;
  7591. this.boneTexture.generateMipmaps = false;
  7592. this.boneTexture.flipY = false;
  7593. } else {
  7594. this.boneMatrices = new Float32Array( 16 * nBones );
  7595. }
  7596. this.pose();
  7597. }
  7598. };
  7599. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  7600. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  7601. if ( bone === undefined ) {
  7602. bone = new THREE.Bone( this );
  7603. }
  7604. this.bones.push( bone );
  7605. return bone;
  7606. };
  7607. THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
  7608. this.matrixAutoUpdate && this.updateMatrix();
  7609. // update matrixWorld
  7610. if ( this.matrixWorldNeedsUpdate || force ) {
  7611. if ( this.parent ) {
  7612. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  7613. } else {
  7614. this.matrixWorld.copy( this.matrix );
  7615. }
  7616. this.matrixWorldNeedsUpdate = false;
  7617. force = true;
  7618. }
  7619. // update children
  7620. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  7621. var child = this.children[ i ];
  7622. if ( child instanceof THREE.Bone ) {
  7623. child.update( this.identityMatrix, false );
  7624. } else {
  7625. child.updateMatrixWorld( true );
  7626. }
  7627. }
  7628. // make a snapshot of the bones' rest position
  7629. if ( this.boneInverses == undefined ) {
  7630. this.boneInverses = [];
  7631. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7632. var inverse = new THREE.Matrix4();
  7633. inverse.getInverse( this.bones[ b ].skinMatrix );
  7634. this.boneInverses.push( inverse );
  7635. }
  7636. }
  7637. // flatten bone matrices to array
  7638. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7639. // compute the offset between the current and the original transform;
  7640. //TODO: we could get rid of this multiplication step if the skinMatrix
  7641. // was already representing the offset; however, this requires some
  7642. // major changes to the animation system
  7643. THREE.SkinnedMesh.offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  7644. THREE.SkinnedMesh.offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  7645. }
  7646. if ( this.useVertexTexture ) {
  7647. this.boneTexture.needsUpdate = true;
  7648. }
  7649. };
  7650. THREE.SkinnedMesh.prototype.pose = function () {
  7651. this.updateMatrixWorld( true );
  7652. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  7653. // normalize weights
  7654. var sw = this.geometry.skinWeights[ i ];
  7655. var scale = 1.0 / sw.lengthManhattan();
  7656. if ( scale !== Infinity ) {
  7657. sw.multiplyScalar( scale );
  7658. } else {
  7659. sw.set( 1 ); // this will be normalized by the shader anyway
  7660. }
  7661. }
  7662. };
  7663. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  7664. if ( object === undefined ) object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  7665. THREE.Mesh.prototype.clone.call( this, object );
  7666. return object;
  7667. };
  7668. THREE.SkinnedMesh.offsetMatrix = new THREE.Matrix4();
  7669. /**
  7670. * @author alteredq / http://alteredqualia.com/
  7671. */
  7672. THREE.MorphAnimMesh = function ( geometry, material ) {
  7673. THREE.Mesh.call( this, geometry, material );
  7674. // API
  7675. this.duration = 1000; // milliseconds
  7676. this.mirroredLoop = false;
  7677. this.time = 0;
  7678. // internals
  7679. this.lastKeyframe = 0;
  7680. this.currentKeyframe = 0;
  7681. this.direction = 1;
  7682. this.directionBackwards = false;
  7683. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  7684. };
  7685. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  7686. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  7687. this.startKeyframe = start;
  7688. this.endKeyframe = end;
  7689. this.length = this.endKeyframe - this.startKeyframe + 1;
  7690. };
  7691. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  7692. this.direction = 1;
  7693. this.directionBackwards = false;
  7694. };
  7695. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  7696. this.direction = -1;
  7697. this.directionBackwards = true;
  7698. };
  7699. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  7700. var geometry = this.geometry;
  7701. if ( ! geometry.animations ) geometry.animations = {};
  7702. var firstAnimation, animations = geometry.animations;
  7703. var pattern = /([a-z]+)(\d+)/;
  7704. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  7705. var morph = geometry.morphTargets[ i ];
  7706. var parts = morph.name.match( pattern );
  7707. if ( parts && parts.length > 1 ) {
  7708. var label = parts[ 1 ];
  7709. var num = parts[ 2 ];
  7710. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  7711. var animation = animations[ label ];
  7712. if ( i < animation.start ) animation.start = i;
  7713. if ( i > animation.end ) animation.end = i;
  7714. if ( ! firstAnimation ) firstAnimation = label;
  7715. }
  7716. }
  7717. geometry.firstAnimation = firstAnimation;
  7718. };
  7719. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  7720. if ( ! this.geometry.animations ) this.geometry.animations = {};
  7721. this.geometry.animations[ label ] = { start: start, end: end };
  7722. };
  7723. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  7724. var animation = this.geometry.animations[ label ];
  7725. if ( animation ) {
  7726. this.setFrameRange( animation.start, animation.end );
  7727. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  7728. this.time = 0;
  7729. } else {
  7730. console.warn( "animation[" + label + "] undefined" );
  7731. }
  7732. };
  7733. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  7734. var frameTime = this.duration / this.length;
  7735. this.time += this.direction * delta;
  7736. if ( this.mirroredLoop ) {
  7737. if ( this.time > this.duration || this.time < 0 ) {
  7738. this.direction *= -1;
  7739. if ( this.time > this.duration ) {
  7740. this.time = this.duration;
  7741. this.directionBackwards = true;
  7742. }
  7743. if ( this.time < 0 ) {
  7744. this.time = 0;
  7745. this.directionBackwards = false;
  7746. }
  7747. }
  7748. } else {
  7749. this.time = this.time % this.duration;
  7750. if ( this.time < 0 ) this.time += this.duration;
  7751. }
  7752. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  7753. if ( keyframe !== this.currentKeyframe ) {
  7754. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  7755. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  7756. this.morphTargetInfluences[ keyframe ] = 0;
  7757. this.lastKeyframe = this.currentKeyframe;
  7758. this.currentKeyframe = keyframe;
  7759. }
  7760. var mix = ( this.time % frameTime ) / frameTime;
  7761. if ( this.directionBackwards ) {
  7762. mix = 1 - mix;
  7763. }
  7764. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  7765. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  7766. };
  7767. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  7768. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  7769. object.duration = this.duration;
  7770. object.mirroredLoop = this.mirroredLoop;
  7771. object.time = this.time;
  7772. object.lastKeyframe = this.lastKeyframe;
  7773. object.currentKeyframe = this.currentKeyframe;
  7774. object.direction = this.direction;
  7775. object.directionBackwards = this.directionBackwards;
  7776. THREE.Mesh.prototype.clone.call( this, object );
  7777. return object;
  7778. };
  7779. /**
  7780. * @author alteredq / http://alteredqualia.com/
  7781. */
  7782. THREE.Ribbon = function ( geometry, material ) {
  7783. THREE.Object3D.call( this );
  7784. this.geometry = geometry;
  7785. this.material = material;
  7786. };
  7787. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  7788. THREE.Ribbon.prototype.clone = function ( object ) {
  7789. if ( object === undefined ) object = new THREE.Ribbon( this.geometry, this.material );
  7790. THREE.Object3D.prototype.clone.call( this, object );
  7791. return object;
  7792. };
  7793. /**
  7794. * @author mikael emtinger / http://gomo.se/
  7795. * @author alteredq / http://alteredqualia.com/
  7796. * @author mrdoob / http://mrdoob.com/
  7797. */
  7798. THREE.LOD = function () {
  7799. THREE.Object3D.call( this );
  7800. this.LODs = [];
  7801. };
  7802. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  7803. THREE.LOD.prototype.addLevel = function ( object3D, visibleAtDistance ) {
  7804. if ( visibleAtDistance === undefined ) {
  7805. visibleAtDistance = 0;
  7806. }
  7807. visibleAtDistance = Math.abs( visibleAtDistance );
  7808. for ( var l = 0; l < this.LODs.length; l ++ ) {
  7809. if ( visibleAtDistance < this.LODs[ l ].visibleAtDistance ) {
  7810. break;
  7811. }
  7812. }
  7813. this.LODs.splice( l, 0, { visibleAtDistance: visibleAtDistance, object3D: object3D } );
  7814. this.add( object3D );
  7815. };
  7816. THREE.LOD.prototype.update = function ( camera ) {
  7817. if ( this.LODs.length > 1 ) {
  7818. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  7819. var inverse = camera.matrixWorldInverse;
  7820. 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] );
  7821. this.LODs[ 0 ].object3D.visible = true;
  7822. for ( var l = 1; l < this.LODs.length; l ++ ) {
  7823. if( distance >= this.LODs[ l ].visibleAtDistance ) {
  7824. this.LODs[ l - 1 ].object3D.visible = false;
  7825. this.LODs[ l ].object3D.visible = true;
  7826. } else {
  7827. break;
  7828. }
  7829. }
  7830. for( ; l < this.LODs.length; l ++ ) {
  7831. this.LODs[ l ].object3D.visible = false;
  7832. }
  7833. }
  7834. };
  7835. THREE.LOD.prototype.clone = function () {
  7836. // TODO
  7837. };
  7838. /**
  7839. * @author mikael emtinger / http://gomo.se/
  7840. * @author alteredq / http://alteredqualia.com/
  7841. */
  7842. THREE.Sprite = function ( material ) {
  7843. THREE.Object3D.call( this );
  7844. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  7845. this.rotation3d = this.rotation;
  7846. this.rotation = 0;
  7847. };
  7848. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  7849. /*
  7850. * Custom update matrix
  7851. */
  7852. THREE.Sprite.prototype.updateMatrix = function () {
  7853. this.matrix.setPosition( this.position );
  7854. this.rotation3d.set( 0, 0, this.rotation );
  7855. this.matrix.setRotationFromEuler( this.rotation3d );
  7856. if ( this.scale.x !== 1 || this.scale.y !== 1 ) {
  7857. this.matrix.scale( this.scale );
  7858. }
  7859. this.matrixWorldNeedsUpdate = true;
  7860. };
  7861. THREE.Sprite.prototype.clone = function ( object ) {
  7862. if ( object === undefined ) object = new THREE.Sprite( this.material );
  7863. THREE.Object3D.prototype.clone.call( this, object );
  7864. return object;
  7865. };
  7866. /**
  7867. * @author mrdoob / http://mrdoob.com/
  7868. */
  7869. THREE.Scene = function () {
  7870. THREE.Object3D.call( this );
  7871. this.fog = null;
  7872. this.overrideMaterial = null;
  7873. this.matrixAutoUpdate = false;
  7874. this.__objects = [];
  7875. this.__lights = [];
  7876. this.__objectsAdded = [];
  7877. this.__objectsRemoved = [];
  7878. };
  7879. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  7880. THREE.Scene.prototype.__addObject = function ( object ) {
  7881. if ( object instanceof THREE.Light ) {
  7882. if ( this.__lights.indexOf( object ) === - 1 ) {
  7883. this.__lights.push( object );
  7884. }
  7885. if ( object.target && object.target.parent === undefined ) {
  7886. this.add( object.target );
  7887. }
  7888. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  7889. if ( this.__objects.indexOf( object ) === - 1 ) {
  7890. this.__objects.push( object );
  7891. this.__objectsAdded.push( object );
  7892. // check if previously removed
  7893. var i = this.__objectsRemoved.indexOf( object );
  7894. if ( i !== -1 ) {
  7895. this.__objectsRemoved.splice( i, 1 );
  7896. }
  7897. }
  7898. }
  7899. for ( var c = 0; c < object.children.length; c ++ ) {
  7900. this.__addObject( object.children[ c ] );
  7901. }
  7902. };
  7903. THREE.Scene.prototype.__removeObject = function ( object ) {
  7904. if ( object instanceof THREE.Light ) {
  7905. var i = this.__lights.indexOf( object );
  7906. if ( i !== -1 ) {
  7907. this.__lights.splice( i, 1 );
  7908. }
  7909. } else if ( !( object instanceof THREE.Camera ) ) {
  7910. var i = this.__objects.indexOf( object );
  7911. if( i !== -1 ) {
  7912. this.__objects.splice( i, 1 );
  7913. this.__objectsRemoved.push( object );
  7914. // check if previously added
  7915. var ai = this.__objectsAdded.indexOf( object );
  7916. if ( ai !== -1 ) {
  7917. this.__objectsAdded.splice( ai, 1 );
  7918. }
  7919. }
  7920. }
  7921. for ( var c = 0; c < object.children.length; c ++ ) {
  7922. this.__removeObject( object.children[ c ] );
  7923. }
  7924. };
  7925. /**
  7926. * @author mrdoob / http://mrdoob.com/
  7927. * @author alteredq / http://alteredqualia.com/
  7928. */
  7929. THREE.Fog = function ( hex, near, far ) {
  7930. this.name = '';
  7931. this.color = new THREE.Color( hex );
  7932. this.near = ( near !== undefined ) ? near : 1;
  7933. this.far = ( far !== undefined ) ? far : 1000;
  7934. };
  7935. THREE.Fog.prototype.clone = function () {
  7936. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  7937. };
  7938. /**
  7939. * @author mrdoob / http://mrdoob.com/
  7940. * @author alteredq / http://alteredqualia.com/
  7941. */
  7942. THREE.FogExp2 = function ( hex, density ) {
  7943. this.name = '';
  7944. this.color = new THREE.Color( hex );
  7945. this.density = ( density !== undefined ) ? density : 0.00025;
  7946. };
  7947. THREE.FogExp2.prototype.clone = function () {
  7948. return new THREE.FogExp2( this.color.getHex(), this.density );
  7949. };
  7950. /**
  7951. * @author mrdoob / http://mrdoob.com/
  7952. */
  7953. THREE.CanvasRenderer = function ( parameters ) {
  7954. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  7955. parameters = parameters || {};
  7956. var _this = this,
  7957. _renderData, _elements, _lights,
  7958. _projector = new THREE.Projector(),
  7959. _canvas = parameters.canvas !== undefined
  7960. ? parameters.canvas
  7961. : document.createElement( 'canvas' ),
  7962. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  7963. _context = _canvas.getContext( '2d' ),
  7964. _clearColor = new THREE.Color( 0x000000 ),
  7965. _clearOpacity = 0,
  7966. _contextGlobalAlpha = 1,
  7967. _contextGlobalCompositeOperation = 0,
  7968. _contextStrokeStyle = null,
  7969. _contextFillStyle = null,
  7970. _contextLineWidth = null,
  7971. _contextLineCap = null,
  7972. _contextLineJoin = null,
  7973. _contextDashSize = null,
  7974. _contextGapSize = 0,
  7975. _v1, _v2, _v3, _v4,
  7976. _v5 = new THREE.RenderableVertex(),
  7977. _v6 = new THREE.RenderableVertex(),
  7978. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  7979. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  7980. _color = new THREE.Color(),
  7981. _color1 = new THREE.Color(),
  7982. _color2 = new THREE.Color(),
  7983. _color3 = new THREE.Color(),
  7984. _color4 = new THREE.Color(),
  7985. _diffuseColor = new THREE.Color(),
  7986. _emissiveColor = new THREE.Color(),
  7987. _lightColor = new THREE.Color(),
  7988. _patterns = {}, _imagedatas = {},
  7989. _near, _far,
  7990. _image, _uvs,
  7991. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  7992. _clipBox = new THREE.Box2(),
  7993. _clearBox = new THREE.Box2(),
  7994. _elemBox = new THREE.Box2(),
  7995. _enableLighting = false,
  7996. _ambientLight = new THREE.Color(),
  7997. _directionalLights = new THREE.Color(),
  7998. _pointLights = new THREE.Color(),
  7999. _pi2 = Math.PI * 2,
  8000. _vector3 = new THREE.Vector3(), // Needed for PointLight
  8001. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  8002. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  8003. _pixelMap = document.createElement( 'canvas' );
  8004. _pixelMap.width = _pixelMap.height = 2;
  8005. _pixelMapContext = _pixelMap.getContext( '2d' );
  8006. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  8007. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  8008. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  8009. _pixelMapData = _pixelMapImage.data;
  8010. _gradientMap = document.createElement( 'canvas' );
  8011. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  8012. _gradientMapContext = _gradientMap.getContext( '2d' );
  8013. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  8014. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  8015. _gradientMapQuality --; // Fix UVs
  8016. // dash+gap fallbacks for Firefox and everything else
  8017. if ( _context.setLineDash === undefined ) {
  8018. if ( _context.mozDash !== undefined ) {
  8019. _context.setLineDash = function ( values ) {
  8020. _context.mozDash = values[ 0 ] !== null ? values : null;
  8021. }
  8022. } else {
  8023. _context.setLineDash = function ( values ) {}
  8024. }
  8025. }
  8026. this.domElement = _canvas;
  8027. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  8028. ? parameters.devicePixelRatio
  8029. : window.devicePixelRatio !== undefined
  8030. ? window.devicePixelRatio
  8031. : 1;
  8032. this.autoClear = true;
  8033. this.sortObjects = true;
  8034. this.sortElements = true;
  8035. this.info = {
  8036. render: {
  8037. vertices: 0,
  8038. faces: 0
  8039. }
  8040. }
  8041. // WebGLRenderer compatibility
  8042. this.supportsVertexTextures = function () {};
  8043. this.setFaceCulling = function () {};
  8044. this.setSize = function ( width, height ) {
  8045. _canvasWidth = width * this.devicePixelRatio;
  8046. _canvasHeight = height * this.devicePixelRatio;
  8047. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  8048. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  8049. _canvas.width = _canvasWidth;
  8050. _canvas.height = _canvasHeight;
  8051. _canvas.style.width = width + 'px';
  8052. _canvas.style.height = height + 'px';
  8053. _clipBox.set(
  8054. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8055. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8056. );
  8057. _clearBox.set(
  8058. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8059. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8060. );
  8061. _contextGlobalAlpha = 1;
  8062. _contextGlobalCompositeOperation = 0;
  8063. _contextStrokeStyle = null;
  8064. _contextFillStyle = null;
  8065. _contextLineWidth = null;
  8066. _contextLineCap = null;
  8067. _contextLineJoin = null;
  8068. };
  8069. this.setClearColor = function ( color, opacity ) {
  8070. _clearColor.copy( color );
  8071. _clearOpacity = opacity !== undefined ? opacity : 1;
  8072. _clearBox.set(
  8073. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8074. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8075. );
  8076. };
  8077. this.setClearColorHex = function ( hex, opacity ) {
  8078. _clearColor.setHex( hex );
  8079. _clearOpacity = opacity !== undefined ? opacity : 1;
  8080. _clearBox.set(
  8081. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8082. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8083. );
  8084. };
  8085. this.getMaxAnisotropy = function () {
  8086. return 0;
  8087. };
  8088. this.clear = function () {
  8089. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8090. if ( _clearBox.empty() === false ) {
  8091. _clearBox.intersect( _clipBox );
  8092. _clearBox.expandByScalar( 2 );
  8093. if ( _clearOpacity < 1 ) {
  8094. _context.clearRect(
  8095. _clearBox.min.x | 0,
  8096. _clearBox.min.y | 0,
  8097. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  8098. ( _clearBox.max.y - _clearBox.min.y ) | 0
  8099. );
  8100. }
  8101. if ( _clearOpacity > 0 ) {
  8102. setBlending( THREE.NormalBlending );
  8103. setOpacity( 1 );
  8104. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearOpacity + ')' );
  8105. _context.fillRect(
  8106. _clearBox.min.x | 0,
  8107. _clearBox.min.y | 0,
  8108. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  8109. ( _clearBox.max.y - _clearBox.min.y ) | 0
  8110. );
  8111. }
  8112. _clearBox.makeEmpty();
  8113. }
  8114. };
  8115. this.render = function ( scene, camera ) {
  8116. if ( camera instanceof THREE.Camera === false ) {
  8117. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  8118. return;
  8119. }
  8120. if ( this.autoClear === true ) {
  8121. this.clear();
  8122. }
  8123. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8124. _this.info.render.vertices = 0;
  8125. _this.info.render.faces = 0;
  8126. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  8127. _elements = _renderData.elements;
  8128. _lights = _renderData.lights;
  8129. /* DEBUG
  8130. setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
  8131. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  8132. */
  8133. _enableLighting = _lights.length > 0;
  8134. if ( _enableLighting === true ) {
  8135. calculateLights();
  8136. }
  8137. for ( var e = 0, el = _elements.length; e < el; e++ ) {
  8138. var element = _elements[ e ];
  8139. var material = element.material;
  8140. if ( material === undefined || material.visible === false ) continue;
  8141. _elemBox.makeEmpty();
  8142. if ( element instanceof THREE.RenderableParticle ) {
  8143. _v1 = element;
  8144. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  8145. renderParticle( _v1, element, material, scene );
  8146. } else if ( element instanceof THREE.RenderableLine ) {
  8147. _v1 = element.v1; _v2 = element.v2;
  8148. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8149. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8150. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen ] );
  8151. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8152. renderLine( _v1, _v2, element, material, scene );
  8153. }
  8154. } else if ( element instanceof THREE.RenderableFace3 ) {
  8155. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  8156. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  8157. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  8158. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  8159. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8160. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8161. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8162. if ( material.overdraw === true ) {
  8163. expand( _v1.positionScreen, _v2.positionScreen );
  8164. expand( _v2.positionScreen, _v3.positionScreen );
  8165. expand( _v3.positionScreen, _v1.positionScreen );
  8166. }
  8167. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen, _v3.positionScreen ] );
  8168. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material, scene );
  8169. } else if ( element instanceof THREE.RenderableFace4 ) {
  8170. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  8171. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  8172. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  8173. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  8174. if ( _v4.positionScreen.z < -1 || _v4.positionScreen.z > 1 ) continue;
  8175. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8176. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8177. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8178. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  8179. _v5.positionScreen.copy( _v2.positionScreen );
  8180. _v6.positionScreen.copy( _v4.positionScreen );
  8181. if ( material.overdraw === true ) {
  8182. expand( _v1.positionScreen, _v2.positionScreen );
  8183. expand( _v2.positionScreen, _v4.positionScreen );
  8184. expand( _v4.positionScreen, _v1.positionScreen );
  8185. expand( _v3.positionScreen, _v5.positionScreen );
  8186. expand( _v3.positionScreen, _v6.positionScreen );
  8187. }
  8188. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen, _v3.positionScreen, _v4.positionScreen ] );
  8189. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material, scene );
  8190. }
  8191. /* DEBUG
  8192. setLineWidth( 1 );
  8193. setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
  8194. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  8195. */
  8196. _clearBox.union( _elemBox );
  8197. }
  8198. /* DEBUG
  8199. setLineWidth( 1 );
  8200. setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
  8201. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  8202. */
  8203. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  8204. //
  8205. function calculateLights() {
  8206. _ambientLight.setRGB( 0, 0, 0 );
  8207. _directionalLights.setRGB( 0, 0, 0 );
  8208. _pointLights.setRGB( 0, 0, 0 );
  8209. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8210. var light = _lights[ l ];
  8211. var lightColor = light.color;
  8212. if ( light instanceof THREE.AmbientLight ) {
  8213. _ambientLight.add( lightColor );
  8214. } else if ( light instanceof THREE.DirectionalLight ) {
  8215. // for particles
  8216. _directionalLights.add( lightColor );
  8217. } else if ( light instanceof THREE.PointLight ) {
  8218. // for particles
  8219. _pointLights.add( lightColor );
  8220. }
  8221. }
  8222. }
  8223. function calculateLight( position, normal, color ) {
  8224. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8225. var light = _lights[ l ];
  8226. _lightColor.copy( light.color );
  8227. if ( light instanceof THREE.DirectionalLight ) {
  8228. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld ).normalize();
  8229. var amount = normal.dot( lightPosition );
  8230. if ( amount <= 0 ) continue;
  8231. amount *= light.intensity;
  8232. color.add( _lightColor.multiplyScalar( amount ) );
  8233. } else if ( light instanceof THREE.PointLight ) {
  8234. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld );
  8235. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  8236. if ( amount <= 0 ) continue;
  8237. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  8238. if ( amount == 0 ) continue;
  8239. amount *= light.intensity;
  8240. color.add( _lightColor.multiplyScalar( amount ) );
  8241. }
  8242. }
  8243. }
  8244. function renderParticle( v1, element, material, scene ) {
  8245. setOpacity( material.opacity );
  8246. setBlending( material.blending );
  8247. var width, height, scaleX, scaleY,
  8248. bitmap, bitmapWidth, bitmapHeight;
  8249. if ( material instanceof THREE.ParticleBasicMaterial ) {
  8250. if ( material.map === null ) {
  8251. scaleX = element.object.scale.x;
  8252. scaleY = element.object.scale.y;
  8253. // TODO: Be able to disable this
  8254. scaleX *= element.scale.x * _canvasWidthHalf;
  8255. scaleY *= element.scale.y * _canvasHeightHalf;
  8256. _elemBox.min.set( v1.x - scaleX, v1.y - scaleY );
  8257. _elemBox.max.set( v1.x + scaleX, v1.y + scaleY );
  8258. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8259. return;
  8260. }
  8261. setFillStyle( material.color.getStyle() );
  8262. _context.save();
  8263. _context.translate( v1.x, v1.y );
  8264. _context.rotate( - element.rotation );
  8265. _context.scale( scaleX, scaleY );
  8266. _context.fillRect( -1, -1, 2, 2 );
  8267. _context.restore();
  8268. } else {
  8269. bitmap = material.map.image;
  8270. bitmapWidth = bitmap.width >> 1;
  8271. bitmapHeight = bitmap.height >> 1;
  8272. scaleX = element.scale.x * _canvasWidthHalf;
  8273. scaleY = element.scale.y * _canvasHeightHalf;
  8274. width = scaleX * bitmapWidth;
  8275. height = scaleY * bitmapHeight;
  8276. // TODO: Rotations break this...
  8277. _elemBox.min.set( v1.x - width, v1.y - height );
  8278. _elemBox.max.set( v1.x + width, v1.y + height );
  8279. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8280. return;
  8281. }
  8282. _context.save();
  8283. _context.translate( v1.x, v1.y );
  8284. _context.rotate( - element.rotation );
  8285. _context.scale( scaleX, - scaleY );
  8286. _context.translate( - bitmapWidth, - bitmapHeight );
  8287. _context.drawImage( bitmap, 0, 0 );
  8288. _context.restore();
  8289. }
  8290. /* DEBUG
  8291. setStrokeStyle( 'rgb(255,255,0)' );
  8292. _context.beginPath();
  8293. _context.moveTo( v1.x - 10, v1.y );
  8294. _context.lineTo( v1.x + 10, v1.y );
  8295. _context.moveTo( v1.x, v1.y - 10 );
  8296. _context.lineTo( v1.x, v1.y + 10 );
  8297. _context.stroke();
  8298. */
  8299. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  8300. width = element.scale.x * _canvasWidthHalf;
  8301. height = element.scale.y * _canvasHeightHalf;
  8302. _elemBox.min.set( v1.x - width, v1.y - height );
  8303. _elemBox.max.set( v1.x + width, v1.y + height );
  8304. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8305. return;
  8306. }
  8307. setStrokeStyle( material.color.getStyle() );
  8308. setFillStyle( material.color.getStyle() );
  8309. _context.save();
  8310. _context.translate( v1.x, v1.y );
  8311. _context.rotate( - element.rotation );
  8312. _context.scale( width, height );
  8313. material.program( _context );
  8314. _context.restore();
  8315. }
  8316. }
  8317. function renderLine( v1, v2, element, material, scene ) {
  8318. setOpacity( material.opacity );
  8319. setBlending( material.blending );
  8320. _context.beginPath();
  8321. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  8322. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  8323. if ( material instanceof THREE.LineBasicMaterial ) {
  8324. setLineWidth( material.linewidth );
  8325. setLineCap( material.linecap );
  8326. setLineJoin( material.linejoin );
  8327. setStrokeStyle( material.color.getStyle() );
  8328. setDashAndGap( null, null );
  8329. _context.stroke();
  8330. _elemBox.expandByScalar( material.linewidth * 2 );
  8331. } else if ( material instanceof THREE.LineDashedMaterial ) {
  8332. setLineWidth( material.linewidth );
  8333. setLineCap( material.linecap );
  8334. setLineJoin( material.linejoin );
  8335. setStrokeStyle( material.color.getStyle() );
  8336. setDashAndGap( material.dashSize, material.gapSize );
  8337. _context.stroke();
  8338. _elemBox.expandByScalar( material.linewidth * 2 );
  8339. }
  8340. }
  8341. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material, scene ) {
  8342. _this.info.render.vertices += 3;
  8343. _this.info.render.faces ++;
  8344. setOpacity( material.opacity );
  8345. setBlending( material.blending );
  8346. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8347. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8348. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8349. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  8350. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) {
  8351. _diffuseColor.copy( material.color );
  8352. _emissiveColor.copy( material.emissive );
  8353. if ( material.vertexColors === THREE.FaceColors ) {
  8354. _diffuseColor.multiply( element.color );
  8355. }
  8356. if ( _enableLighting === true ) {
  8357. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  8358. _color1.copy( _ambientLight );
  8359. _color2.copy( _ambientLight );
  8360. _color3.copy( _ambientLight );
  8361. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  8362. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  8363. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color3 );
  8364. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  8365. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  8366. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  8367. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8368. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8369. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8370. } else {
  8371. _color.copy( _ambientLight );
  8372. calculateLight( element.centroidModel, element.normalModel, _color );
  8373. _color.multiply( _diffuseColor ).add( _emissiveColor );
  8374. material.wireframe === true
  8375. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8376. : fillPath( _color );
  8377. }
  8378. } else {
  8379. material.wireframe === true
  8380. ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8381. : fillPath( material.color );
  8382. }
  8383. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8384. if ( material.map !== null ) {
  8385. if ( material.map.mapping instanceof THREE.UVMapping ) {
  8386. _uvs = element.uvs[ 0 ];
  8387. 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 );
  8388. }
  8389. } else if ( material.envMap !== null ) {
  8390. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  8391. _vector3.copy( element.vertexNormalsModelView[ uv1 ] );
  8392. _uv1x = 0.5 * _vector3.x + 0.5;
  8393. _uv1y = 0.5 * _vector3.y + 0.5;
  8394. _vector3.copy( element.vertexNormalsModelView[ uv2 ] );
  8395. _uv2x = 0.5 * _vector3.x + 0.5;
  8396. _uv2y = 0.5 * _vector3.y + 0.5;
  8397. _vector3.copy( element.vertexNormalsModelView[ uv3 ] );
  8398. _uv3x = 0.5 * _vector3.x + 0.5;
  8399. _uv3y = 0.5 * _vector3.y + 0.5;
  8400. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  8401. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  8402. }*/
  8403. } else {
  8404. _color.copy( material.color );
  8405. if ( material.vertexColors === THREE.FaceColors ) {
  8406. _color.multiply( element.color );
  8407. }
  8408. material.wireframe === true
  8409. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8410. : fillPath( _color );
  8411. }
  8412. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8413. _near = camera.near;
  8414. _far = camera.far;
  8415. var depth;
  8416. depth = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  8417. _color1.setRGB( depth, depth, depth );
  8418. depth = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far )
  8419. _color2.setRGB( depth, depth, depth );
  8420. depth = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  8421. _color3.setRGB( depth, depth, depth );
  8422. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8423. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8424. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8425. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8426. var normal;
  8427. if ( material.shading == THREE.FlatShading ) {
  8428. normal = element.normalModelView;
  8429. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8430. material.wireframe === true
  8431. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8432. : fillPath( _color );
  8433. } else if ( material.shading == THREE.SmoothShading ) {
  8434. normal = element.vertexNormalsModelView[ uv1 ];
  8435. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8436. normal = element.vertexNormalsModelView[ uv2 ];
  8437. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8438. normal = element.vertexNormalsModelView[ uv3 ];
  8439. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8440. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8441. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8442. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8443. }
  8444. }
  8445. }
  8446. function renderFace4( v1, v2, v3, v4, v5, v6, element, material, scene ) {
  8447. _this.info.render.vertices += 4;
  8448. _this.info.render.faces ++;
  8449. setOpacity( material.opacity );
  8450. setBlending( material.blending );
  8451. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  8452. // Let renderFace3() handle this
  8453. renderFace3( v1, v2, v4, 0, 1, 3, element, material, scene );
  8454. renderFace3( v5, v3, v6, 1, 2, 3, element, material, scene );
  8455. return;
  8456. }
  8457. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8458. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8459. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8460. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  8461. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  8462. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  8463. if ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8464. _diffuseColor.copy( material.color );
  8465. _emissiveColor.copy( material.emissive );
  8466. if ( material.vertexColors === THREE.FaceColors ) {
  8467. _diffuseColor.multiply( element.color );
  8468. }
  8469. if ( _enableLighting === true ) {
  8470. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  8471. _color1.copy( _ambientLight );
  8472. _color2.copy( _ambientLight );
  8473. _color3.copy( _ambientLight );
  8474. _color4.copy( _ambientLight );
  8475. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  8476. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  8477. calculateLight( element.v4.positionWorld, element.vertexNormalsModel[ 3 ], _color3 );
  8478. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color4 );
  8479. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  8480. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  8481. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  8482. _color4.multiply( _diffuseColor ).add( _emissiveColor );
  8483. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8484. // TODO: UVs are incorrect, v4->v3?
  8485. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8486. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8487. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8488. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8489. } else {
  8490. _color.copy( _ambientLight );
  8491. calculateLight( element.centroidModel, element.normalModel, _color );
  8492. _color.multiply( _diffuseColor ).add( _emissiveColor );
  8493. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8494. material.wireframe === true
  8495. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8496. : fillPath( _color );
  8497. }
  8498. } else {
  8499. _color.addColors( _diffuseColor, _emissiveColor );
  8500. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8501. material.wireframe === true
  8502. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8503. : fillPath( _color );
  8504. }
  8505. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  8506. _color.copy( material.color );
  8507. if ( material.vertexColors === THREE.FaceColors ) {
  8508. _color.multiply( element.color );
  8509. }
  8510. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8511. material.wireframe === true
  8512. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8513. : fillPath( _color );
  8514. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8515. var normal;
  8516. if ( material.shading == THREE.FlatShading ) {
  8517. normal = element.normalModelView;
  8518. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8519. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8520. material.wireframe === true
  8521. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8522. : fillPath( _color );
  8523. } else if ( material.shading == THREE.SmoothShading ) {
  8524. normal = element.vertexNormalsModelView[ 0 ];
  8525. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8526. normal = element.vertexNormalsModelView[ 1 ];
  8527. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8528. normal = element.vertexNormalsModelView[ 3 ];
  8529. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8530. normal = element.vertexNormalsModelView[ 2 ];
  8531. _color4.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8532. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8533. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8534. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8535. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8536. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8537. }
  8538. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8539. _near = camera.near;
  8540. _far = camera.far;
  8541. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  8542. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  8543. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z * v4.positionScreen.w, _near, _far );
  8544. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  8545. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8546. // TODO: UVs are incorrect, v4->v3?
  8547. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8548. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8549. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8550. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8551. }
  8552. }
  8553. //
  8554. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  8555. _context.beginPath();
  8556. _context.moveTo( x0, y0 );
  8557. _context.lineTo( x1, y1 );
  8558. _context.lineTo( x2, y2 );
  8559. _context.closePath();
  8560. }
  8561. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  8562. _context.beginPath();
  8563. _context.moveTo( x0, y0 );
  8564. _context.lineTo( x1, y1 );
  8565. _context.lineTo( x2, y2 );
  8566. _context.lineTo( x3, y3 );
  8567. _context.closePath();
  8568. }
  8569. function strokePath( color, linewidth, linecap, linejoin ) {
  8570. setLineWidth( linewidth );
  8571. setLineCap( linecap );
  8572. setLineJoin( linejoin );
  8573. setStrokeStyle( color.getStyle() );
  8574. _context.stroke();
  8575. _elemBox.expandByScalar( linewidth * 2 );
  8576. }
  8577. function fillPath( color ) {
  8578. setFillStyle( color.getStyle() );
  8579. _context.fill();
  8580. }
  8581. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  8582. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  8583. if ( texture.needsUpdate === true ) {
  8584. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  8585. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  8586. _patterns[ texture.id ] = _context.createPattern(
  8587. texture.image, repeatX === true && repeatY === true
  8588. ? 'repeat'
  8589. : repeatX === true && repeatY === false
  8590. ? 'repeat-x'
  8591. : repeatX === false && repeatY === true
  8592. ? 'repeat-y'
  8593. : 'no-repeat'
  8594. );
  8595. texture.needsUpdate = false;
  8596. }
  8597. _patterns[ texture.id ] === undefined
  8598. ? setFillStyle( 'rgba(0,0,0,1)' )
  8599. : setFillStyle( _patterns[ texture.id ] );
  8600. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8601. var a, b, c, d, e, f, det, idet,
  8602. offsetX = texture.offset.x / texture.repeat.x,
  8603. offsetY = texture.offset.y / texture.repeat.y,
  8604. width = texture.image.width * texture.repeat.x,
  8605. height = texture.image.height * texture.repeat.y;
  8606. u0 = ( u0 + offsetX ) * width;
  8607. v0 = ( 1.0 - v0 + offsetY ) * height;
  8608. u1 = ( u1 + offsetX ) * width;
  8609. v1 = ( 1.0 - v1 + offsetY ) * height;
  8610. u2 = ( u2 + offsetX ) * width;
  8611. v2 = ( 1.0 - v2 + offsetY ) * height;
  8612. x1 -= x0; y1 -= y0;
  8613. x2 -= x0; y2 -= y0;
  8614. u1 -= u0; v1 -= v0;
  8615. u2 -= u0; v2 -= v0;
  8616. det = u1 * v2 - u2 * v1;
  8617. if ( det === 0 ) {
  8618. if ( _imagedatas[ texture.id ] === undefined ) {
  8619. var canvas = document.createElement( 'canvas' )
  8620. canvas.width = texture.image.width;
  8621. canvas.height = texture.image.height;
  8622. var context = canvas.getContext( '2d' );
  8623. context.drawImage( texture.image, 0, 0 );
  8624. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  8625. }
  8626. var data = _imagedatas[ texture.id ];
  8627. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  8628. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  8629. fillPath( _color );
  8630. return;
  8631. }
  8632. idet = 1 / det;
  8633. a = ( v2 * x1 - v1 * x2 ) * idet;
  8634. b = ( v2 * y1 - v1 * y2 ) * idet;
  8635. c = ( u1 * x2 - u2 * x1 ) * idet;
  8636. d = ( u1 * y2 - u2 * y1 ) * idet;
  8637. e = x0 - a * u0 - c * v0;
  8638. f = y0 - b * u0 - d * v0;
  8639. _context.save();
  8640. _context.transform( a, b, c, d, e, f );
  8641. _context.fill();
  8642. _context.restore();
  8643. }
  8644. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  8645. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8646. var a, b, c, d, e, f, det, idet,
  8647. width = image.width - 1,
  8648. height = image.height - 1;
  8649. u0 *= width; v0 *= height;
  8650. u1 *= width; v1 *= height;
  8651. u2 *= width; v2 *= height;
  8652. x1 -= x0; y1 -= y0;
  8653. x2 -= x0; y2 -= y0;
  8654. u1 -= u0; v1 -= v0;
  8655. u2 -= u0; v2 -= v0;
  8656. det = u1 * v2 - u2 * v1;
  8657. idet = 1 / det;
  8658. a = ( v2 * x1 - v1 * x2 ) * idet;
  8659. b = ( v2 * y1 - v1 * y2 ) * idet;
  8660. c = ( u1 * x2 - u2 * x1 ) * idet;
  8661. d = ( u1 * y2 - u2 * y1 ) * idet;
  8662. e = x0 - a * u0 - c * v0;
  8663. f = y0 - b * u0 - d * v0;
  8664. _context.save();
  8665. _context.transform( a, b, c, d, e, f );
  8666. _context.clip();
  8667. _context.drawImage( image, 0, 0 );
  8668. _context.restore();
  8669. }
  8670. function getGradientTexture( color1, color2, color3, color4 ) {
  8671. // http://mrdoob.com/blog/post/710
  8672. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  8673. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  8674. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  8675. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  8676. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  8677. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  8678. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  8679. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  8680. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  8681. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  8682. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  8683. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  8684. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  8685. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  8686. return _gradientMap;
  8687. }
  8688. function smoothstep( value, min, max ) {
  8689. var x = ( value - min ) / ( max - min );
  8690. return x * x * ( 3 - 2 * x );
  8691. }
  8692. // Hide anti-alias gaps
  8693. function expand( v1, v2 ) {
  8694. var x = v2.x - v1.x, y = v2.y - v1.y,
  8695. det = x * x + y * y, idet;
  8696. if ( det === 0 ) return;
  8697. idet = 1 / Math.sqrt( det );
  8698. x *= idet; y *= idet;
  8699. v2.x += x; v2.y += y;
  8700. v1.x -= x; v1.y -= y;
  8701. }
  8702. };
  8703. // Context cached methods.
  8704. function setOpacity( value ) {
  8705. if ( _contextGlobalAlpha !== value ) {
  8706. _context.globalAlpha = value;
  8707. _contextGlobalAlpha = value;
  8708. }
  8709. }
  8710. function setBlending( value ) {
  8711. if ( _contextGlobalCompositeOperation !== value ) {
  8712. if ( value === THREE.NormalBlending ) {
  8713. _context.globalCompositeOperation = 'source-over';
  8714. } else if ( value === THREE.AdditiveBlending ) {
  8715. _context.globalCompositeOperation = 'lighter';
  8716. } else if ( value === THREE.SubtractiveBlending ) {
  8717. _context.globalCompositeOperation = 'darker';
  8718. }
  8719. _contextGlobalCompositeOperation = value;
  8720. }
  8721. }
  8722. function setLineWidth( value ) {
  8723. if ( _contextLineWidth !== value ) {
  8724. _context.lineWidth = value;
  8725. _contextLineWidth = value;
  8726. }
  8727. }
  8728. function setLineCap( value ) {
  8729. // "butt", "round", "square"
  8730. if ( _contextLineCap !== value ) {
  8731. _context.lineCap = value;
  8732. _contextLineCap = value;
  8733. }
  8734. }
  8735. function setLineJoin( value ) {
  8736. // "round", "bevel", "miter"
  8737. if ( _contextLineJoin !== value ) {
  8738. _context.lineJoin = value;
  8739. _contextLineJoin = value;
  8740. }
  8741. }
  8742. function setStrokeStyle( value ) {
  8743. if ( _contextStrokeStyle !== value ) {
  8744. _context.strokeStyle = value;
  8745. _contextStrokeStyle = value;
  8746. }
  8747. }
  8748. function setFillStyle( value ) {
  8749. if ( _contextFillStyle !== value ) {
  8750. _context.fillStyle = value;
  8751. _contextFillStyle = value;
  8752. }
  8753. }
  8754. function setDashAndGap( dashSizeValue, gapSizeValue ) {
  8755. if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) {
  8756. _context.setLineDash( [ dashSizeValue, gapSizeValue ] );
  8757. _contextDashSize = dashSizeValue;
  8758. _contextGapSize = gapSizeValue;
  8759. }
  8760. }
  8761. };
  8762. /**
  8763. * @author alteredq / http://alteredqualia.com/
  8764. * @author mrdoob / http://mrdoob.com/
  8765. * @author mikael emtinger / http://gomo.se/
  8766. */
  8767. THREE.ShaderChunk = {
  8768. // FOG
  8769. fog_pars_fragment: [
  8770. "#ifdef USE_FOG",
  8771. "uniform vec3 fogColor;",
  8772. "#ifdef FOG_EXP2",
  8773. "uniform float fogDensity;",
  8774. "#else",
  8775. "uniform float fogNear;",
  8776. "uniform float fogFar;",
  8777. "#endif",
  8778. "#endif"
  8779. ].join("\n"),
  8780. fog_fragment: [
  8781. "#ifdef USE_FOG",
  8782. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  8783. "#ifdef FOG_EXP2",
  8784. "const float LOG2 = 1.442695;",
  8785. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  8786. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  8787. "#else",
  8788. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  8789. "#endif",
  8790. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  8791. "#endif"
  8792. ].join("\n"),
  8793. // ENVIRONMENT MAP
  8794. envmap_pars_fragment: [
  8795. "#ifdef USE_ENVMAP",
  8796. "uniform float reflectivity;",
  8797. "uniform samplerCube envMap;",
  8798. "uniform float flipEnvMap;",
  8799. "uniform int combine;",
  8800. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8801. "uniform bool useRefract;",
  8802. "uniform float refractionRatio;",
  8803. "#else",
  8804. "varying vec3 vReflect;",
  8805. "#endif",
  8806. "#endif"
  8807. ].join("\n"),
  8808. envmap_fragment: [
  8809. "#ifdef USE_ENVMAP",
  8810. "vec3 reflectVec;",
  8811. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8812. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  8813. "if ( useRefract ) {",
  8814. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  8815. "} else { ",
  8816. "reflectVec = reflect( cameraToVertex, normal );",
  8817. "}",
  8818. "#else",
  8819. "reflectVec = vReflect;",
  8820. "#endif",
  8821. "#ifdef DOUBLE_SIDED",
  8822. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  8823. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8824. "#else",
  8825. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8826. "#endif",
  8827. "#ifdef GAMMA_INPUT",
  8828. "cubeColor.xyz *= cubeColor.xyz;",
  8829. "#endif",
  8830. "if ( combine == 1 ) {",
  8831. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  8832. "} else if ( combine == 2 ) {",
  8833. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  8834. "} else {",
  8835. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  8836. "}",
  8837. "#endif"
  8838. ].join("\n"),
  8839. envmap_pars_vertex: [
  8840. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8841. "varying vec3 vReflect;",
  8842. "uniform float refractionRatio;",
  8843. "uniform bool useRefract;",
  8844. "#endif"
  8845. ].join("\n"),
  8846. worldpos_vertex : [
  8847. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  8848. "#ifdef USE_SKINNING",
  8849. "vec4 worldPosition = modelMatrix * skinned;",
  8850. "#endif",
  8851. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8852. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  8853. "#endif",
  8854. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8855. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  8856. "#endif",
  8857. "#endif"
  8858. ].join("\n"),
  8859. envmap_vertex : [
  8860. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8861. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  8862. "worldNormal = normalize( worldNormal );",
  8863. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  8864. "if ( useRefract ) {",
  8865. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  8866. "} else {",
  8867. "vReflect = reflect( cameraToVertex, worldNormal );",
  8868. "}",
  8869. "#endif"
  8870. ].join("\n"),
  8871. // COLOR MAP (particles)
  8872. map_particle_pars_fragment: [
  8873. "#ifdef USE_MAP",
  8874. "uniform sampler2D map;",
  8875. "#endif"
  8876. ].join("\n"),
  8877. map_particle_fragment: [
  8878. "#ifdef USE_MAP",
  8879. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  8880. "#endif"
  8881. ].join("\n"),
  8882. // COLOR MAP (triangles)
  8883. map_pars_vertex: [
  8884. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8885. "varying vec2 vUv;",
  8886. "uniform vec4 offsetRepeat;",
  8887. "#endif"
  8888. ].join("\n"),
  8889. map_pars_fragment: [
  8890. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8891. "varying vec2 vUv;",
  8892. "#endif",
  8893. "#ifdef USE_MAP",
  8894. "uniform sampler2D map;",
  8895. "#endif"
  8896. ].join("\n"),
  8897. map_vertex: [
  8898. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8899. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  8900. "#endif"
  8901. ].join("\n"),
  8902. map_fragment: [
  8903. "#ifdef USE_MAP",
  8904. "vec4 texelColor = texture2D( map, vUv );",
  8905. "#ifdef GAMMA_INPUT",
  8906. "texelColor.xyz *= texelColor.xyz;",
  8907. "#endif",
  8908. "gl_FragColor = gl_FragColor * texelColor;",
  8909. "#endif"
  8910. ].join("\n"),
  8911. // LIGHT MAP
  8912. lightmap_pars_fragment: [
  8913. "#ifdef USE_LIGHTMAP",
  8914. "varying vec2 vUv2;",
  8915. "uniform sampler2D lightMap;",
  8916. "#endif"
  8917. ].join("\n"),
  8918. lightmap_pars_vertex: [
  8919. "#ifdef USE_LIGHTMAP",
  8920. "varying vec2 vUv2;",
  8921. "#endif"
  8922. ].join("\n"),
  8923. lightmap_fragment: [
  8924. "#ifdef USE_LIGHTMAP",
  8925. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  8926. "#endif"
  8927. ].join("\n"),
  8928. lightmap_vertex: [
  8929. "#ifdef USE_LIGHTMAP",
  8930. "vUv2 = uv2;",
  8931. "#endif"
  8932. ].join("\n"),
  8933. // BUMP MAP
  8934. bumpmap_pars_fragment: [
  8935. "#ifdef USE_BUMPMAP",
  8936. "uniform sampler2D bumpMap;",
  8937. "uniform float bumpScale;",
  8938. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  8939. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  8940. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8941. "vec2 dHdxy_fwd() {",
  8942. "vec2 dSTdx = dFdx( vUv );",
  8943. "vec2 dSTdy = dFdy( vUv );",
  8944. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  8945. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  8946. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  8947. "return vec2( dBx, dBy );",
  8948. "}",
  8949. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  8950. "vec3 vSigmaX = dFdx( surf_pos );",
  8951. "vec3 vSigmaY = dFdy( surf_pos );",
  8952. "vec3 vN = surf_norm;", // normalized
  8953. "vec3 R1 = cross( vSigmaY, vN );",
  8954. "vec3 R2 = cross( vN, vSigmaX );",
  8955. "float fDet = dot( vSigmaX, R1 );",
  8956. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  8957. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  8958. "}",
  8959. "#endif"
  8960. ].join("\n"),
  8961. // NORMAL MAP
  8962. normalmap_pars_fragment: [
  8963. "#ifdef USE_NORMALMAP",
  8964. "uniform sampler2D normalMap;",
  8965. "uniform vec2 normalScale;",
  8966. // Per-Pixel Tangent Space Normal Mapping
  8967. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  8968. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  8969. "vec3 q0 = dFdx( eye_pos.xyz );",
  8970. "vec3 q1 = dFdy( eye_pos.xyz );",
  8971. "vec2 st0 = dFdx( vUv.st );",
  8972. "vec2 st1 = dFdy( vUv.st );",
  8973. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  8974. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  8975. "vec3 N = normalize( surf_norm );",
  8976. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  8977. "mapN.xy = normalScale * mapN.xy;",
  8978. "mat3 tsn = mat3( S, T, N );",
  8979. "return normalize( tsn * mapN );",
  8980. "}",
  8981. "#endif"
  8982. ].join("\n"),
  8983. // SPECULAR MAP
  8984. specularmap_pars_fragment: [
  8985. "#ifdef USE_SPECULARMAP",
  8986. "uniform sampler2D specularMap;",
  8987. "#endif"
  8988. ].join("\n"),
  8989. specularmap_fragment: [
  8990. "float specularStrength;",
  8991. "#ifdef USE_SPECULARMAP",
  8992. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  8993. "specularStrength = texelSpecular.r;",
  8994. "#else",
  8995. "specularStrength = 1.0;",
  8996. "#endif"
  8997. ].join("\n"),
  8998. // LIGHTS LAMBERT
  8999. lights_lambert_pars_vertex: [
  9000. "uniform vec3 ambient;",
  9001. "uniform vec3 diffuse;",
  9002. "uniform vec3 emissive;",
  9003. "uniform vec3 ambientLightColor;",
  9004. "#if MAX_DIR_LIGHTS > 0",
  9005. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9006. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9007. "#endif",
  9008. "#if MAX_HEMI_LIGHTS > 0",
  9009. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9010. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9011. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9012. "#endif",
  9013. "#if MAX_POINT_LIGHTS > 0",
  9014. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9015. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9016. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9017. "#endif",
  9018. "#if MAX_SPOT_LIGHTS > 0",
  9019. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9020. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9021. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9022. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9023. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9024. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9025. "#endif",
  9026. "#ifdef WRAP_AROUND",
  9027. "uniform vec3 wrapRGB;",
  9028. "#endif"
  9029. ].join("\n"),
  9030. lights_lambert_vertex: [
  9031. "vLightFront = vec3( 0.0 );",
  9032. "#ifdef DOUBLE_SIDED",
  9033. "vLightBack = vec3( 0.0 );",
  9034. "#endif",
  9035. "transformedNormal = normalize( transformedNormal );",
  9036. "#if MAX_DIR_LIGHTS > 0",
  9037. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9038. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9039. "vec3 dirVector = normalize( lDirection.xyz );",
  9040. "float dotProduct = dot( transformedNormal, dirVector );",
  9041. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9042. "#ifdef DOUBLE_SIDED",
  9043. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9044. "#ifdef WRAP_AROUND",
  9045. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9046. "#endif",
  9047. "#endif",
  9048. "#ifdef WRAP_AROUND",
  9049. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9050. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  9051. "#ifdef DOUBLE_SIDED",
  9052. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  9053. "#endif",
  9054. "#endif",
  9055. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  9056. "#ifdef DOUBLE_SIDED",
  9057. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  9058. "#endif",
  9059. "}",
  9060. "#endif",
  9061. "#if MAX_POINT_LIGHTS > 0",
  9062. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9063. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9064. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9065. "float lDistance = 1.0;",
  9066. "if ( pointLightDistance[ i ] > 0.0 )",
  9067. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9068. "lVector = normalize( lVector );",
  9069. "float dotProduct = dot( transformedNormal, lVector );",
  9070. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9071. "#ifdef DOUBLE_SIDED",
  9072. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9073. "#ifdef WRAP_AROUND",
  9074. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9075. "#endif",
  9076. "#endif",
  9077. "#ifdef WRAP_AROUND",
  9078. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9079. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  9080. "#ifdef DOUBLE_SIDED",
  9081. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  9082. "#endif",
  9083. "#endif",
  9084. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  9085. "#ifdef DOUBLE_SIDED",
  9086. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  9087. "#endif",
  9088. "}",
  9089. "#endif",
  9090. "#if MAX_SPOT_LIGHTS > 0",
  9091. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9092. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9093. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9094. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  9095. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9096. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9097. "float lDistance = 1.0;",
  9098. "if ( spotLightDistance[ i ] > 0.0 )",
  9099. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9100. "lVector = normalize( lVector );",
  9101. "float dotProduct = dot( transformedNormal, lVector );",
  9102. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9103. "#ifdef DOUBLE_SIDED",
  9104. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9105. "#ifdef WRAP_AROUND",
  9106. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9107. "#endif",
  9108. "#endif",
  9109. "#ifdef WRAP_AROUND",
  9110. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9111. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  9112. "#ifdef DOUBLE_SIDED",
  9113. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  9114. "#endif",
  9115. "#endif",
  9116. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  9117. "#ifdef DOUBLE_SIDED",
  9118. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  9119. "#endif",
  9120. "}",
  9121. "}",
  9122. "#endif",
  9123. "#if MAX_HEMI_LIGHTS > 0",
  9124. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9125. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9126. "vec3 lVector = normalize( lDirection.xyz );",
  9127. "float dotProduct = dot( transformedNormal, lVector );",
  9128. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9129. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  9130. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9131. "#ifdef DOUBLE_SIDED",
  9132. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  9133. "#endif",
  9134. "}",
  9135. "#endif",
  9136. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  9137. "#ifdef DOUBLE_SIDED",
  9138. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  9139. "#endif"
  9140. ].join("\n"),
  9141. // LIGHTS PHONG
  9142. lights_phong_pars_vertex: [
  9143. "#ifndef PHONG_PER_PIXEL",
  9144. "#if MAX_POINT_LIGHTS > 0",
  9145. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9146. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9147. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9148. "#endif",
  9149. "#if MAX_SPOT_LIGHTS > 0",
  9150. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9151. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9152. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9153. "#endif",
  9154. "#endif",
  9155. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9156. "varying vec3 vWorldPosition;",
  9157. "#endif"
  9158. ].join("\n"),
  9159. lights_phong_vertex: [
  9160. "#ifndef PHONG_PER_PIXEL",
  9161. "#if MAX_POINT_LIGHTS > 0",
  9162. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9163. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9164. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9165. "float lDistance = 1.0;",
  9166. "if ( pointLightDistance[ i ] > 0.0 )",
  9167. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9168. "vPointLight[ i ] = vec4( lVector, lDistance );",
  9169. "}",
  9170. "#endif",
  9171. "#if MAX_SPOT_LIGHTS > 0",
  9172. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9173. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9174. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9175. "float lDistance = 1.0;",
  9176. "if ( spotLightDistance[ i ] > 0.0 )",
  9177. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9178. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  9179. "}",
  9180. "#endif",
  9181. "#endif",
  9182. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9183. "vWorldPosition = worldPosition.xyz;",
  9184. "#endif"
  9185. ].join("\n"),
  9186. lights_phong_pars_fragment: [
  9187. "uniform vec3 ambientLightColor;",
  9188. "#if MAX_DIR_LIGHTS > 0",
  9189. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9190. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9191. "#endif",
  9192. "#if MAX_HEMI_LIGHTS > 0",
  9193. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9194. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9195. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9196. "#endif",
  9197. "#if MAX_POINT_LIGHTS > 0",
  9198. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9199. "#ifdef PHONG_PER_PIXEL",
  9200. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9201. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9202. "#else",
  9203. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9204. "#endif",
  9205. "#endif",
  9206. "#if MAX_SPOT_LIGHTS > 0",
  9207. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9208. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9209. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9210. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9211. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9212. "#ifdef PHONG_PER_PIXEL",
  9213. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9214. "#else",
  9215. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9216. "#endif",
  9217. "#endif",
  9218. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9219. "varying vec3 vWorldPosition;",
  9220. "#endif",
  9221. "#ifdef WRAP_AROUND",
  9222. "uniform vec3 wrapRGB;",
  9223. "#endif",
  9224. "varying vec3 vViewPosition;",
  9225. "varying vec3 vNormal;"
  9226. ].join("\n"),
  9227. lights_phong_fragment: [
  9228. "vec3 normal = normalize( vNormal );",
  9229. "vec3 viewPosition = normalize( vViewPosition );",
  9230. "#ifdef DOUBLE_SIDED",
  9231. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9232. "#endif",
  9233. "#ifdef USE_NORMALMAP",
  9234. "normal = perturbNormal2Arb( -viewPosition, normal );",
  9235. "#elif defined( USE_BUMPMAP )",
  9236. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  9237. "#endif",
  9238. "#if MAX_POINT_LIGHTS > 0",
  9239. "vec3 pointDiffuse = vec3( 0.0 );",
  9240. "vec3 pointSpecular = vec3( 0.0 );",
  9241. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9242. "#ifdef PHONG_PER_PIXEL",
  9243. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9244. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9245. "float lDistance = 1.0;",
  9246. "if ( pointLightDistance[ i ] > 0.0 )",
  9247. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9248. "lVector = normalize( lVector );",
  9249. "#else",
  9250. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  9251. "float lDistance = vPointLight[ i ].w;",
  9252. "#endif",
  9253. // diffuse
  9254. "float dotProduct = dot( normal, lVector );",
  9255. "#ifdef WRAP_AROUND",
  9256. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  9257. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9258. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  9259. "#else",
  9260. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  9261. "#endif",
  9262. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  9263. // specular
  9264. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  9265. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  9266. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  9267. "#ifdef PHYSICALLY_BASED_SHADING",
  9268. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9269. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9270. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  9271. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  9272. "#else",
  9273. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  9274. "#endif",
  9275. "}",
  9276. "#endif",
  9277. "#if MAX_SPOT_LIGHTS > 0",
  9278. "vec3 spotDiffuse = vec3( 0.0 );",
  9279. "vec3 spotSpecular = vec3( 0.0 );",
  9280. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9281. "#ifdef PHONG_PER_PIXEL",
  9282. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9283. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9284. "float lDistance = 1.0;",
  9285. "if ( spotLightDistance[ i ] > 0.0 )",
  9286. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9287. "lVector = normalize( lVector );",
  9288. "#else",
  9289. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  9290. "float lDistance = vSpotLight[ i ].w;",
  9291. "#endif",
  9292. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  9293. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9294. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9295. // diffuse
  9296. "float dotProduct = dot( normal, lVector );",
  9297. "#ifdef WRAP_AROUND",
  9298. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  9299. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9300. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  9301. "#else",
  9302. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  9303. "#endif",
  9304. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  9305. // specular
  9306. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  9307. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  9308. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  9309. "#ifdef PHYSICALLY_BASED_SHADING",
  9310. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9311. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9312. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  9313. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  9314. "#else",
  9315. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  9316. "#endif",
  9317. "}",
  9318. "}",
  9319. "#endif",
  9320. "#if MAX_DIR_LIGHTS > 0",
  9321. "vec3 dirDiffuse = vec3( 0.0 );",
  9322. "vec3 dirSpecular = vec3( 0.0 );" ,
  9323. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9324. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9325. "vec3 dirVector = normalize( lDirection.xyz );",
  9326. // diffuse
  9327. "float dotProduct = dot( normal, dirVector );",
  9328. "#ifdef WRAP_AROUND",
  9329. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  9330. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9331. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  9332. "#else",
  9333. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  9334. "#endif",
  9335. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  9336. // specular
  9337. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  9338. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  9339. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  9340. "#ifdef PHYSICALLY_BASED_SHADING",
  9341. /*
  9342. // fresnel term from skin shader
  9343. "const float F0 = 0.128;",
  9344. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  9345. "float exponential = pow( base, 5.0 );",
  9346. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  9347. */
  9348. /*
  9349. // fresnel term from fresnel shader
  9350. "const float mFresnelBias = 0.08;",
  9351. "const float mFresnelScale = 0.3;",
  9352. "const float mFresnelPower = 5.0;",
  9353. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  9354. */
  9355. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9356. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9357. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  9358. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  9359. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  9360. "#else",
  9361. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  9362. "#endif",
  9363. "}",
  9364. "#endif",
  9365. "#if MAX_HEMI_LIGHTS > 0",
  9366. "vec3 hemiDiffuse = vec3( 0.0 );",
  9367. "vec3 hemiSpecular = vec3( 0.0 );" ,
  9368. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9369. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9370. "vec3 lVector = normalize( lDirection.xyz );",
  9371. // diffuse
  9372. "float dotProduct = dot( normal, lVector );",
  9373. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9374. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9375. "hemiDiffuse += diffuse * hemiColor;",
  9376. // specular (sky light)
  9377. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  9378. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  9379. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  9380. // specular (ground light)
  9381. "vec3 lVectorGround = -lVector;",
  9382. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  9383. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  9384. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  9385. "#ifdef PHYSICALLY_BASED_SHADING",
  9386. "float dotProductGround = dot( normal, lVectorGround );",
  9387. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9388. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9389. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  9390. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  9391. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  9392. "#else",
  9393. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  9394. "#endif",
  9395. "}",
  9396. "#endif",
  9397. "vec3 totalDiffuse = vec3( 0.0 );",
  9398. "vec3 totalSpecular = vec3( 0.0 );",
  9399. "#if MAX_DIR_LIGHTS > 0",
  9400. "totalDiffuse += dirDiffuse;",
  9401. "totalSpecular += dirSpecular;",
  9402. "#endif",
  9403. "#if MAX_HEMI_LIGHTS > 0",
  9404. "totalDiffuse += hemiDiffuse;",
  9405. "totalSpecular += hemiSpecular;",
  9406. "#endif",
  9407. "#if MAX_POINT_LIGHTS > 0",
  9408. "totalDiffuse += pointDiffuse;",
  9409. "totalSpecular += pointSpecular;",
  9410. "#endif",
  9411. "#if MAX_SPOT_LIGHTS > 0",
  9412. "totalDiffuse += spotDiffuse;",
  9413. "totalSpecular += spotSpecular;",
  9414. "#endif",
  9415. "#ifdef METAL",
  9416. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  9417. "#else",
  9418. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  9419. "#endif"
  9420. ].join("\n"),
  9421. // VERTEX COLORS
  9422. color_pars_fragment: [
  9423. "#ifdef USE_COLOR",
  9424. "varying vec3 vColor;",
  9425. "#endif"
  9426. ].join("\n"),
  9427. color_fragment: [
  9428. "#ifdef USE_COLOR",
  9429. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  9430. "#endif"
  9431. ].join("\n"),
  9432. color_pars_vertex: [
  9433. "#ifdef USE_COLOR",
  9434. "varying vec3 vColor;",
  9435. "#endif"
  9436. ].join("\n"),
  9437. color_vertex: [
  9438. "#ifdef USE_COLOR",
  9439. "#ifdef GAMMA_INPUT",
  9440. "vColor = color * color;",
  9441. "#else",
  9442. "vColor = color;",
  9443. "#endif",
  9444. "#endif"
  9445. ].join("\n"),
  9446. // SKINNING
  9447. skinning_pars_vertex: [
  9448. "#ifdef USE_SKINNING",
  9449. "#ifdef BONE_TEXTURE",
  9450. "uniform sampler2D boneTexture;",
  9451. "mat4 getBoneMatrix( const in float i ) {",
  9452. "float j = i * 4.0;",
  9453. "float x = mod( j, N_BONE_PIXEL_X );",
  9454. "float y = floor( j / N_BONE_PIXEL_X );",
  9455. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  9456. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  9457. "y = dy * ( y + 0.5 );",
  9458. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  9459. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  9460. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  9461. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  9462. "mat4 bone = mat4( v1, v2, v3, v4 );",
  9463. "return bone;",
  9464. "}",
  9465. "#else",
  9466. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  9467. "mat4 getBoneMatrix( const in float i ) {",
  9468. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  9469. "return bone;",
  9470. "}",
  9471. "#endif",
  9472. "#endif"
  9473. ].join("\n"),
  9474. skinbase_vertex: [
  9475. "#ifdef USE_SKINNING",
  9476. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  9477. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  9478. "#endif"
  9479. ].join("\n"),
  9480. skinning_vertex: [
  9481. "#ifdef USE_SKINNING",
  9482. "#ifdef USE_MORPHTARGETS",
  9483. "vec4 skinVertex = vec4( morphed, 1.0 );",
  9484. "#else",
  9485. "vec4 skinVertex = vec4( position, 1.0 );",
  9486. "#endif",
  9487. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  9488. "skinned += boneMatY * skinVertex * skinWeight.y;",
  9489. "#endif"
  9490. ].join("\n"),
  9491. // MORPHING
  9492. morphtarget_pars_vertex: [
  9493. "#ifdef USE_MORPHTARGETS",
  9494. "#ifndef USE_MORPHNORMALS",
  9495. "uniform float morphTargetInfluences[ 8 ];",
  9496. "#else",
  9497. "uniform float morphTargetInfluences[ 4 ];",
  9498. "#endif",
  9499. "#endif"
  9500. ].join("\n"),
  9501. morphtarget_vertex: [
  9502. "#ifdef USE_MORPHTARGETS",
  9503. "vec3 morphed = vec3( 0.0 );",
  9504. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  9505. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  9506. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  9507. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  9508. "#ifndef USE_MORPHNORMALS",
  9509. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  9510. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  9511. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  9512. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  9513. "#endif",
  9514. "morphed += position;",
  9515. "#endif"
  9516. ].join("\n"),
  9517. default_vertex : [
  9518. "vec4 mvPosition;",
  9519. "#ifdef USE_SKINNING",
  9520. "mvPosition = modelViewMatrix * skinned;",
  9521. "#endif",
  9522. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  9523. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  9524. "#endif",
  9525. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  9526. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9527. "#endif",
  9528. "gl_Position = projectionMatrix * mvPosition;"
  9529. ].join("\n"),
  9530. morphnormal_vertex: [
  9531. "#ifdef USE_MORPHNORMALS",
  9532. "vec3 morphedNormal = vec3( 0.0 );",
  9533. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  9534. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  9535. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  9536. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  9537. "morphedNormal += normal;",
  9538. "#endif"
  9539. ].join("\n"),
  9540. skinnormal_vertex: [
  9541. "#ifdef USE_SKINNING",
  9542. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  9543. "skinMatrix += skinWeight.y * boneMatY;",
  9544. "#ifdef USE_MORPHNORMALS",
  9545. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  9546. "#else",
  9547. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  9548. "#endif",
  9549. "#endif"
  9550. ].join("\n"),
  9551. defaultnormal_vertex: [
  9552. "vec3 objectNormal;",
  9553. "#ifdef USE_SKINNING",
  9554. "objectNormal = skinnedNormal.xyz;",
  9555. "#endif",
  9556. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  9557. "objectNormal = morphedNormal;",
  9558. "#endif",
  9559. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  9560. "objectNormal = normal;",
  9561. "#endif",
  9562. "#ifdef FLIP_SIDED",
  9563. "objectNormal = -objectNormal;",
  9564. "#endif",
  9565. "vec3 transformedNormal = normalMatrix * objectNormal;"
  9566. ].join("\n"),
  9567. // SHADOW MAP
  9568. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  9569. // http://spidergl.org/example.php?id=6
  9570. // http://fabiensanglard.net/shadowmapping
  9571. shadowmap_pars_fragment: [
  9572. "#ifdef USE_SHADOWMAP",
  9573. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  9574. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  9575. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  9576. "uniform float shadowBias[ MAX_SHADOWS ];",
  9577. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  9578. "float unpackDepth( const in vec4 rgba_depth ) {",
  9579. "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 );",
  9580. "float depth = dot( rgba_depth, bit_shift );",
  9581. "return depth;",
  9582. "}",
  9583. "#endif"
  9584. ].join("\n"),
  9585. shadowmap_fragment: [
  9586. "#ifdef USE_SHADOWMAP",
  9587. "#ifdef SHADOWMAP_DEBUG",
  9588. "vec3 frustumColors[3];",
  9589. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  9590. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  9591. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  9592. "#endif",
  9593. "#ifdef SHADOWMAP_CASCADE",
  9594. "int inFrustumCount = 0;",
  9595. "#endif",
  9596. "float fDepth;",
  9597. "vec3 shadowColor = vec3( 1.0 );",
  9598. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  9599. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  9600. // "if ( something && something )" breaks ATI OpenGL shader compiler
  9601. // "if ( all( something, something ) )" using this instead
  9602. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  9603. "bool inFrustum = all( inFrustumVec );",
  9604. // don't shadow pixels outside of light frustum
  9605. // use just first frustum (for cascades)
  9606. // don't shadow pixels behind far plane of light frustum
  9607. "#ifdef SHADOWMAP_CASCADE",
  9608. "inFrustumCount += int( inFrustum );",
  9609. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  9610. "#else",
  9611. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  9612. "#endif",
  9613. "bool frustumTest = all( frustumTestVec );",
  9614. "if ( frustumTest ) {",
  9615. "shadowCoord.z += shadowBias[ i ];",
  9616. "#if defined( SHADOWMAP_TYPE_PCF )",
  9617. // Percentage-close filtering
  9618. // (9 pixel kernel)
  9619. // http://fabiensanglard.net/shadowmappingPCF/
  9620. "float shadow = 0.0;",
  9621. /*
  9622. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  9623. // must enroll loop manually
  9624. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  9625. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  9626. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  9627. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  9628. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  9629. "float fDepth = unpackDepth( rgbaDepth );",
  9630. "if ( fDepth < shadowCoord.z )",
  9631. "shadow += 1.0;",
  9632. "}",
  9633. "shadow /= 9.0;",
  9634. */
  9635. "const float shadowDelta = 1.0 / 9.0;",
  9636. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  9637. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  9638. "float dx0 = -1.25 * xPixelOffset;",
  9639. "float dy0 = -1.25 * yPixelOffset;",
  9640. "float dx1 = 1.25 * xPixelOffset;",
  9641. "float dy1 = 1.25 * yPixelOffset;",
  9642. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  9643. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9644. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  9645. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9646. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  9647. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9648. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  9649. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9650. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  9651. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9652. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  9653. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9654. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  9655. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9656. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  9657. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9658. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  9659. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9660. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  9661. "#elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  9662. // Percentage-close filtering
  9663. // (9 pixel kernel)
  9664. // http://fabiensanglard.net/shadowmappingPCF/
  9665. "float shadow = 0.0;",
  9666. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  9667. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  9668. "float dx0 = -1.0 * xPixelOffset;",
  9669. "float dy0 = -1.0 * yPixelOffset;",
  9670. "float dx1 = 1.0 * xPixelOffset;",
  9671. "float dy1 = 1.0 * yPixelOffset;",
  9672. "mat3 shadowKernel;",
  9673. "mat3 depthKernel;",
  9674. "depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  9675. "if ( depthKernel[0][0] < shadowCoord.z ) shadowKernel[0][0] = 0.25;",
  9676. "else shadowKernel[0][0] = 0.0;",
  9677. "depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  9678. "if ( depthKernel[0][1] < shadowCoord.z ) shadowKernel[0][1] = 0.25;",
  9679. "else shadowKernel[0][1] = 0.0;",
  9680. "depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  9681. "if ( depthKernel[0][2] < shadowCoord.z ) shadowKernel[0][2] = 0.25;",
  9682. "else shadowKernel[0][2] = 0.0;",
  9683. "depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  9684. "if ( depthKernel[1][0] < shadowCoord.z ) shadowKernel[1][0] = 0.25;",
  9685. "else shadowKernel[1][0] = 0.0;",
  9686. "depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  9687. "if ( depthKernel[1][1] < shadowCoord.z ) shadowKernel[1][1] = 0.25;",
  9688. "else shadowKernel[1][1] = 0.0;",
  9689. "depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  9690. "if ( depthKernel[1][2] < shadowCoord.z ) shadowKernel[1][2] = 0.25;",
  9691. "else shadowKernel[1][2] = 0.0;",
  9692. "depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  9693. "if ( depthKernel[2][0] < shadowCoord.z ) shadowKernel[2][0] = 0.25;",
  9694. "else shadowKernel[2][0] = 0.0;",
  9695. "depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  9696. "if ( depthKernel[2][1] < shadowCoord.z ) shadowKernel[2][1] = 0.25;",
  9697. "else shadowKernel[2][1] = 0.0;",
  9698. "depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  9699. "if ( depthKernel[2][2] < shadowCoord.z ) shadowKernel[2][2] = 0.25;",
  9700. "else shadowKernel[2][2] = 0.0;",
  9701. "vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  9702. "shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  9703. "shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  9704. "vec4 shadowValues;",
  9705. "shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  9706. "shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  9707. "shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  9708. "shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  9709. "shadow = dot( shadowValues, vec4( 1.0 ) );",
  9710. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  9711. "#else",
  9712. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  9713. "float fDepth = unpackDepth( rgbaDepth );",
  9714. "if ( fDepth < shadowCoord.z )",
  9715. // spot with multiple shadows is darker
  9716. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  9717. // spot with multiple shadows has the same color as single shadow spot
  9718. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  9719. "#endif",
  9720. "}",
  9721. "#ifdef SHADOWMAP_DEBUG",
  9722. "#ifdef SHADOWMAP_CASCADE",
  9723. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  9724. "#else",
  9725. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  9726. "#endif",
  9727. "#endif",
  9728. "}",
  9729. "#ifdef GAMMA_OUTPUT",
  9730. "shadowColor *= shadowColor;",
  9731. "#endif",
  9732. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  9733. "#endif"
  9734. ].join("\n"),
  9735. shadowmap_pars_vertex: [
  9736. "#ifdef USE_SHADOWMAP",
  9737. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  9738. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  9739. "#endif"
  9740. ].join("\n"),
  9741. shadowmap_vertex: [
  9742. "#ifdef USE_SHADOWMAP",
  9743. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  9744. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  9745. "}",
  9746. "#endif"
  9747. ].join("\n"),
  9748. // ALPHATEST
  9749. alphatest_fragment: [
  9750. "#ifdef ALPHATEST",
  9751. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  9752. "#endif"
  9753. ].join("\n"),
  9754. // LINEAR SPACE
  9755. linear_to_gamma_fragment: [
  9756. "#ifdef GAMMA_OUTPUT",
  9757. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  9758. "#endif"
  9759. ].join("\n")
  9760. };
  9761. THREE.UniformsUtils = {
  9762. merge: function ( uniforms ) {
  9763. var u, p, tmp, merged = {};
  9764. for ( u = 0; u < uniforms.length; u ++ ) {
  9765. tmp = this.clone( uniforms[ u ] );
  9766. for ( p in tmp ) {
  9767. merged[ p ] = tmp[ p ];
  9768. }
  9769. }
  9770. return merged;
  9771. },
  9772. clone: function ( uniforms_src ) {
  9773. var u, p, parameter, parameter_src, uniforms_dst = {};
  9774. for ( u in uniforms_src ) {
  9775. uniforms_dst[ u ] = {};
  9776. for ( p in uniforms_src[ u ] ) {
  9777. parameter_src = uniforms_src[ u ][ p ];
  9778. if ( parameter_src instanceof THREE.Color ||
  9779. parameter_src instanceof THREE.Vector2 ||
  9780. parameter_src instanceof THREE.Vector3 ||
  9781. parameter_src instanceof THREE.Vector4 ||
  9782. parameter_src instanceof THREE.Matrix4 ||
  9783. parameter_src instanceof THREE.Texture ) {
  9784. uniforms_dst[ u ][ p ] = parameter_src.clone();
  9785. } else if ( parameter_src instanceof Array ) {
  9786. uniforms_dst[ u ][ p ] = parameter_src.slice();
  9787. } else {
  9788. uniforms_dst[ u ][ p ] = parameter_src;
  9789. }
  9790. }
  9791. }
  9792. return uniforms_dst;
  9793. }
  9794. };
  9795. THREE.UniformsLib = {
  9796. common: {
  9797. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9798. "opacity" : { type: "f", value: 1.0 },
  9799. "map" : { type: "t", value: null },
  9800. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  9801. "lightMap" : { type: "t", value: null },
  9802. "specularMap" : { type: "t", value: null },
  9803. "envMap" : { type: "t", value: null },
  9804. "flipEnvMap" : { type: "f", value: -1 },
  9805. "useRefract" : { type: "i", value: 0 },
  9806. "reflectivity" : { type: "f", value: 1.0 },
  9807. "refractionRatio" : { type: "f", value: 0.98 },
  9808. "combine" : { type: "i", value: 0 },
  9809. "morphTargetInfluences" : { type: "f", value: 0 }
  9810. },
  9811. bump: {
  9812. "bumpMap" : { type: "t", value: null },
  9813. "bumpScale" : { type: "f", value: 1 }
  9814. },
  9815. normalmap: {
  9816. "normalMap" : { type: "t", value: null },
  9817. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  9818. },
  9819. fog : {
  9820. "fogDensity" : { type: "f", value: 0.00025 },
  9821. "fogNear" : { type: "f", value: 1 },
  9822. "fogFar" : { type: "f", value: 2000 },
  9823. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9824. },
  9825. lights: {
  9826. "ambientLightColor" : { type: "fv", value: [] },
  9827. "directionalLightDirection" : { type: "fv", value: [] },
  9828. "directionalLightColor" : { type: "fv", value: [] },
  9829. "hemisphereLightDirection" : { type: "fv", value: [] },
  9830. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  9831. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  9832. "pointLightColor" : { type: "fv", value: [] },
  9833. "pointLightPosition" : { type: "fv", value: [] },
  9834. "pointLightDistance" : { type: "fv1", value: [] },
  9835. "spotLightColor" : { type: "fv", value: [] },
  9836. "spotLightPosition" : { type: "fv", value: [] },
  9837. "spotLightDirection" : { type: "fv", value: [] },
  9838. "spotLightDistance" : { type: "fv1", value: [] },
  9839. "spotLightAngleCos" : { type: "fv1", value: [] },
  9840. "spotLightExponent" : { type: "fv1", value: [] }
  9841. },
  9842. particle: {
  9843. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9844. "opacity" : { type: "f", value: 1.0 },
  9845. "size" : { type: "f", value: 1.0 },
  9846. "scale" : { type: "f", value: 1.0 },
  9847. "map" : { type: "t", value: null },
  9848. "fogDensity" : { type: "f", value: 0.00025 },
  9849. "fogNear" : { type: "f", value: 1 },
  9850. "fogFar" : { type: "f", value: 2000 },
  9851. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9852. },
  9853. shadowmap: {
  9854. "shadowMap": { type: "tv", value: [] },
  9855. "shadowMapSize": { type: "v2v", value: [] },
  9856. "shadowBias" : { type: "fv1", value: [] },
  9857. "shadowDarkness": { type: "fv1", value: [] },
  9858. "shadowMatrix" : { type: "m4v", value: [] }
  9859. }
  9860. };
  9861. THREE.ShaderLib = {
  9862. 'basic': {
  9863. uniforms: THREE.UniformsUtils.merge( [
  9864. THREE.UniformsLib[ "common" ],
  9865. THREE.UniformsLib[ "fog" ],
  9866. THREE.UniformsLib[ "shadowmap" ]
  9867. ] ),
  9868. vertexShader: [
  9869. THREE.ShaderChunk[ "map_pars_vertex" ],
  9870. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9871. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9872. THREE.ShaderChunk[ "color_pars_vertex" ],
  9873. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9874. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9875. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9876. "void main() {",
  9877. THREE.ShaderChunk[ "map_vertex" ],
  9878. THREE.ShaderChunk[ "lightmap_vertex" ],
  9879. THREE.ShaderChunk[ "color_vertex" ],
  9880. THREE.ShaderChunk[ "skinbase_vertex" ],
  9881. "#ifdef USE_ENVMAP",
  9882. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9883. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9884. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9885. "#endif",
  9886. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9887. THREE.ShaderChunk[ "skinning_vertex" ],
  9888. THREE.ShaderChunk[ "default_vertex" ],
  9889. THREE.ShaderChunk[ "worldpos_vertex" ],
  9890. THREE.ShaderChunk[ "envmap_vertex" ],
  9891. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9892. "}"
  9893. ].join("\n"),
  9894. fragmentShader: [
  9895. "uniform vec3 diffuse;",
  9896. "uniform float opacity;",
  9897. THREE.ShaderChunk[ "color_pars_fragment" ],
  9898. THREE.ShaderChunk[ "map_pars_fragment" ],
  9899. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9900. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9901. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9902. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9903. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9904. "void main() {",
  9905. "gl_FragColor = vec4( diffuse, opacity );",
  9906. THREE.ShaderChunk[ "map_fragment" ],
  9907. THREE.ShaderChunk[ "alphatest_fragment" ],
  9908. THREE.ShaderChunk[ "specularmap_fragment" ],
  9909. THREE.ShaderChunk[ "lightmap_fragment" ],
  9910. THREE.ShaderChunk[ "color_fragment" ],
  9911. THREE.ShaderChunk[ "envmap_fragment" ],
  9912. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9913. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9914. THREE.ShaderChunk[ "fog_fragment" ],
  9915. "}"
  9916. ].join("\n")
  9917. },
  9918. 'lambert': {
  9919. uniforms: THREE.UniformsUtils.merge( [
  9920. THREE.UniformsLib[ "common" ],
  9921. THREE.UniformsLib[ "fog" ],
  9922. THREE.UniformsLib[ "lights" ],
  9923. THREE.UniformsLib[ "shadowmap" ],
  9924. {
  9925. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9926. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9927. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9928. }
  9929. ] ),
  9930. vertexShader: [
  9931. "#define LAMBERT",
  9932. "varying vec3 vLightFront;",
  9933. "#ifdef DOUBLE_SIDED",
  9934. "varying vec3 vLightBack;",
  9935. "#endif",
  9936. THREE.ShaderChunk[ "map_pars_vertex" ],
  9937. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9938. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9939. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  9940. THREE.ShaderChunk[ "color_pars_vertex" ],
  9941. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9942. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9943. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9944. "void main() {",
  9945. THREE.ShaderChunk[ "map_vertex" ],
  9946. THREE.ShaderChunk[ "lightmap_vertex" ],
  9947. THREE.ShaderChunk[ "color_vertex" ],
  9948. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9949. THREE.ShaderChunk[ "skinbase_vertex" ],
  9950. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9951. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9952. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9953. THREE.ShaderChunk[ "skinning_vertex" ],
  9954. THREE.ShaderChunk[ "default_vertex" ],
  9955. THREE.ShaderChunk[ "worldpos_vertex" ],
  9956. THREE.ShaderChunk[ "envmap_vertex" ],
  9957. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  9958. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9959. "}"
  9960. ].join("\n"),
  9961. fragmentShader: [
  9962. "uniform float opacity;",
  9963. "varying vec3 vLightFront;",
  9964. "#ifdef DOUBLE_SIDED",
  9965. "varying vec3 vLightBack;",
  9966. "#endif",
  9967. THREE.ShaderChunk[ "color_pars_fragment" ],
  9968. THREE.ShaderChunk[ "map_pars_fragment" ],
  9969. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9970. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9971. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9972. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9973. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9974. "void main() {",
  9975. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  9976. THREE.ShaderChunk[ "map_fragment" ],
  9977. THREE.ShaderChunk[ "alphatest_fragment" ],
  9978. THREE.ShaderChunk[ "specularmap_fragment" ],
  9979. "#ifdef DOUBLE_SIDED",
  9980. //"float isFront = float( gl_FrontFacing );",
  9981. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  9982. "if ( gl_FrontFacing )",
  9983. "gl_FragColor.xyz *= vLightFront;",
  9984. "else",
  9985. "gl_FragColor.xyz *= vLightBack;",
  9986. "#else",
  9987. "gl_FragColor.xyz *= vLightFront;",
  9988. "#endif",
  9989. THREE.ShaderChunk[ "lightmap_fragment" ],
  9990. THREE.ShaderChunk[ "color_fragment" ],
  9991. THREE.ShaderChunk[ "envmap_fragment" ],
  9992. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9993. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9994. THREE.ShaderChunk[ "fog_fragment" ],
  9995. "}"
  9996. ].join("\n")
  9997. },
  9998. 'phong': {
  9999. uniforms: THREE.UniformsUtils.merge( [
  10000. THREE.UniformsLib[ "common" ],
  10001. THREE.UniformsLib[ "bump" ],
  10002. THREE.UniformsLib[ "normalmap" ],
  10003. THREE.UniformsLib[ "fog" ],
  10004. THREE.UniformsLib[ "lights" ],
  10005. THREE.UniformsLib[ "shadowmap" ],
  10006. {
  10007. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10008. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10009. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  10010. "shininess": { type: "f", value: 30 },
  10011. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10012. }
  10013. ] ),
  10014. vertexShader: [
  10015. "#define PHONG",
  10016. "varying vec3 vViewPosition;",
  10017. "varying vec3 vNormal;",
  10018. THREE.ShaderChunk[ "map_pars_vertex" ],
  10019. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10020. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10021. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  10022. THREE.ShaderChunk[ "color_pars_vertex" ],
  10023. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10024. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10025. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10026. "void main() {",
  10027. THREE.ShaderChunk[ "map_vertex" ],
  10028. THREE.ShaderChunk[ "lightmap_vertex" ],
  10029. THREE.ShaderChunk[ "color_vertex" ],
  10030. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10031. THREE.ShaderChunk[ "skinbase_vertex" ],
  10032. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10033. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10034. "vNormal = normalize( transformedNormal );",
  10035. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10036. THREE.ShaderChunk[ "skinning_vertex" ],
  10037. THREE.ShaderChunk[ "default_vertex" ],
  10038. "vViewPosition = -mvPosition.xyz;",
  10039. THREE.ShaderChunk[ "worldpos_vertex" ],
  10040. THREE.ShaderChunk[ "envmap_vertex" ],
  10041. THREE.ShaderChunk[ "lights_phong_vertex" ],
  10042. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10043. "}"
  10044. ].join("\n"),
  10045. fragmentShader: [
  10046. "uniform vec3 diffuse;",
  10047. "uniform float opacity;",
  10048. "uniform vec3 ambient;",
  10049. "uniform vec3 emissive;",
  10050. "uniform vec3 specular;",
  10051. "uniform float shininess;",
  10052. THREE.ShaderChunk[ "color_pars_fragment" ],
  10053. THREE.ShaderChunk[ "map_pars_fragment" ],
  10054. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10055. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10056. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10057. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  10058. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10059. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  10060. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  10061. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10062. "void main() {",
  10063. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10064. THREE.ShaderChunk[ "map_fragment" ],
  10065. THREE.ShaderChunk[ "alphatest_fragment" ],
  10066. THREE.ShaderChunk[ "specularmap_fragment" ],
  10067. THREE.ShaderChunk[ "lights_phong_fragment" ],
  10068. THREE.ShaderChunk[ "lightmap_fragment" ],
  10069. THREE.ShaderChunk[ "color_fragment" ],
  10070. THREE.ShaderChunk[ "envmap_fragment" ],
  10071. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10072. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10073. THREE.ShaderChunk[ "fog_fragment" ],
  10074. "}"
  10075. ].join("\n")
  10076. },
  10077. 'particle_basic': {
  10078. uniforms: THREE.UniformsUtils.merge( [
  10079. THREE.UniformsLib[ "particle" ],
  10080. THREE.UniformsLib[ "shadowmap" ]
  10081. ] ),
  10082. vertexShader: [
  10083. "uniform float size;",
  10084. "uniform float scale;",
  10085. THREE.ShaderChunk[ "color_pars_vertex" ],
  10086. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10087. "void main() {",
  10088. THREE.ShaderChunk[ "color_vertex" ],
  10089. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10090. "#ifdef USE_SIZEATTENUATION",
  10091. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  10092. "#else",
  10093. "gl_PointSize = size;",
  10094. "#endif",
  10095. "gl_Position = projectionMatrix * mvPosition;",
  10096. THREE.ShaderChunk[ "worldpos_vertex" ],
  10097. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10098. "}"
  10099. ].join("\n"),
  10100. fragmentShader: [
  10101. "uniform vec3 psColor;",
  10102. "uniform float opacity;",
  10103. THREE.ShaderChunk[ "color_pars_fragment" ],
  10104. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  10105. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10106. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10107. "void main() {",
  10108. "gl_FragColor = vec4( psColor, opacity );",
  10109. THREE.ShaderChunk[ "map_particle_fragment" ],
  10110. THREE.ShaderChunk[ "alphatest_fragment" ],
  10111. THREE.ShaderChunk[ "color_fragment" ],
  10112. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10113. THREE.ShaderChunk[ "fog_fragment" ],
  10114. "}"
  10115. ].join("\n")
  10116. },
  10117. 'dashed': {
  10118. uniforms: THREE.UniformsUtils.merge( [
  10119. THREE.UniformsLib[ "common" ],
  10120. THREE.UniformsLib[ "fog" ],
  10121. {
  10122. "scale": { type: "f", value: 1 },
  10123. "dashSize": { type: "f", value: 1 },
  10124. "totalSize": { type: "f", value: 2 }
  10125. }
  10126. ] ),
  10127. vertexShader: [
  10128. "uniform float scale;",
  10129. "attribute float lineDistance;",
  10130. "varying float vLineDistance;",
  10131. THREE.ShaderChunk[ "color_pars_vertex" ],
  10132. "void main() {",
  10133. THREE.ShaderChunk[ "color_vertex" ],
  10134. "vLineDistance = scale * lineDistance;",
  10135. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10136. "gl_Position = projectionMatrix * mvPosition;",
  10137. "}"
  10138. ].join("\n"),
  10139. fragmentShader: [
  10140. "uniform vec3 diffuse;",
  10141. "uniform float opacity;",
  10142. "uniform float dashSize;",
  10143. "uniform float totalSize;",
  10144. "varying float vLineDistance;",
  10145. THREE.ShaderChunk[ "color_pars_fragment" ],
  10146. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10147. "void main() {",
  10148. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  10149. "discard;",
  10150. "}",
  10151. "gl_FragColor = vec4( diffuse, opacity );",
  10152. THREE.ShaderChunk[ "color_fragment" ],
  10153. THREE.ShaderChunk[ "fog_fragment" ],
  10154. "}"
  10155. ].join("\n")
  10156. },
  10157. 'depth': {
  10158. uniforms: {
  10159. "mNear": { type: "f", value: 1.0 },
  10160. "mFar" : { type: "f", value: 2000.0 },
  10161. "opacity" : { type: "f", value: 1.0 }
  10162. },
  10163. vertexShader: [
  10164. "void main() {",
  10165. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  10166. "}"
  10167. ].join("\n"),
  10168. fragmentShader: [
  10169. "uniform float mNear;",
  10170. "uniform float mFar;",
  10171. "uniform float opacity;",
  10172. "void main() {",
  10173. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  10174. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  10175. "gl_FragColor = vec4( vec3( color ), opacity );",
  10176. "}"
  10177. ].join("\n")
  10178. },
  10179. 'normal': {
  10180. uniforms: {
  10181. "opacity" : { type: "f", value: 1.0 }
  10182. },
  10183. vertexShader: [
  10184. "varying vec3 vNormal;",
  10185. "void main() {",
  10186. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10187. "vNormal = normalize( normalMatrix * normal );",
  10188. "gl_Position = projectionMatrix * mvPosition;",
  10189. "}"
  10190. ].join("\n"),
  10191. fragmentShader: [
  10192. "uniform float opacity;",
  10193. "varying vec3 vNormal;",
  10194. "void main() {",
  10195. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  10196. "}"
  10197. ].join("\n")
  10198. },
  10199. /* -------------------------------------------------------------------------
  10200. // Normal map shader
  10201. // - Blinn-Phong
  10202. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  10203. // - point and directional lights (use with "lights: true" material option)
  10204. ------------------------------------------------------------------------- */
  10205. 'normalmap' : {
  10206. uniforms: THREE.UniformsUtils.merge( [
  10207. THREE.UniformsLib[ "fog" ],
  10208. THREE.UniformsLib[ "lights" ],
  10209. THREE.UniformsLib[ "shadowmap" ],
  10210. {
  10211. "enableAO" : { type: "i", value: 0 },
  10212. "enableDiffuse" : { type: "i", value: 0 },
  10213. "enableSpecular" : { type: "i", value: 0 },
  10214. "enableReflection": { type: "i", value: 0 },
  10215. "enableDisplacement": { type: "i", value: 0 },
  10216. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  10217. "tDiffuse" : { type: "t", value: null },
  10218. "tCube" : { type: "t", value: null },
  10219. "tNormal" : { type: "t", value: null },
  10220. "tSpecular" : { type: "t", value: null },
  10221. "tAO" : { type: "t", value: null },
  10222. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  10223. "uDisplacementBias": { type: "f", value: 0.0 },
  10224. "uDisplacementScale": { type: "f", value: 1.0 },
  10225. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  10226. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  10227. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  10228. "uShininess": { type: "f", value: 30 },
  10229. "uOpacity": { type: "f", value: 1 },
  10230. "useRefract": { type: "i", value: 0 },
  10231. "uRefractionRatio": { type: "f", value: 0.98 },
  10232. "uReflectivity": { type: "f", value: 0.5 },
  10233. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  10234. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  10235. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10236. }
  10237. ] ),
  10238. fragmentShader: [
  10239. "uniform vec3 uAmbientColor;",
  10240. "uniform vec3 uDiffuseColor;",
  10241. "uniform vec3 uSpecularColor;",
  10242. "uniform float uShininess;",
  10243. "uniform float uOpacity;",
  10244. "uniform bool enableDiffuse;",
  10245. "uniform bool enableSpecular;",
  10246. "uniform bool enableAO;",
  10247. "uniform bool enableReflection;",
  10248. "uniform sampler2D tDiffuse;",
  10249. "uniform sampler2D tNormal;",
  10250. "uniform sampler2D tSpecular;",
  10251. "uniform sampler2D tAO;",
  10252. "uniform samplerCube tCube;",
  10253. "uniform vec2 uNormalScale;",
  10254. "uniform bool useRefract;",
  10255. "uniform float uRefractionRatio;",
  10256. "uniform float uReflectivity;",
  10257. "varying vec3 vTangent;",
  10258. "varying vec3 vBinormal;",
  10259. "varying vec3 vNormal;",
  10260. "varying vec2 vUv;",
  10261. "uniform vec3 ambientLightColor;",
  10262. "#if MAX_DIR_LIGHTS > 0",
  10263. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10264. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10265. "#endif",
  10266. "#if MAX_HEMI_LIGHTS > 0",
  10267. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10268. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10269. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10270. "#endif",
  10271. "#if MAX_POINT_LIGHTS > 0",
  10272. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10273. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10274. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10275. "#endif",
  10276. "#if MAX_SPOT_LIGHTS > 0",
  10277. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10278. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10279. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10280. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10281. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10282. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10283. "#endif",
  10284. "#ifdef WRAP_AROUND",
  10285. "uniform vec3 wrapRGB;",
  10286. "#endif",
  10287. "varying vec3 vWorldPosition;",
  10288. "varying vec3 vViewPosition;",
  10289. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10290. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10291. "void main() {",
  10292. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  10293. "vec3 specularTex = vec3( 1.0 );",
  10294. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  10295. "normalTex.xy *= uNormalScale;",
  10296. "normalTex = normalize( normalTex );",
  10297. "if( enableDiffuse ) {",
  10298. "#ifdef GAMMA_INPUT",
  10299. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  10300. "texelColor.xyz *= texelColor.xyz;",
  10301. "gl_FragColor = gl_FragColor * texelColor;",
  10302. "#else",
  10303. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  10304. "#endif",
  10305. "}",
  10306. "if( enableAO ) {",
  10307. "#ifdef GAMMA_INPUT",
  10308. "vec4 aoColor = texture2D( tAO, vUv );",
  10309. "aoColor.xyz *= aoColor.xyz;",
  10310. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  10311. "#else",
  10312. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  10313. "#endif",
  10314. "}",
  10315. "if( enableSpecular )",
  10316. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  10317. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  10318. "vec3 finalNormal = tsb * normalTex;",
  10319. "#ifdef FLIP_SIDED",
  10320. "finalNormal = -finalNormal;",
  10321. "#endif",
  10322. "vec3 normal = normalize( finalNormal );",
  10323. "vec3 viewPosition = normalize( vViewPosition );",
  10324. // point lights
  10325. "#if MAX_POINT_LIGHTS > 0",
  10326. "vec3 pointDiffuse = vec3( 0.0 );",
  10327. "vec3 pointSpecular = vec3( 0.0 );",
  10328. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10329. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10330. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  10331. "float pointDistance = 1.0;",
  10332. "if ( pointLightDistance[ i ] > 0.0 )",
  10333. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  10334. "pointVector = normalize( pointVector );",
  10335. // diffuse
  10336. "#ifdef WRAP_AROUND",
  10337. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  10338. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  10339. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  10340. "#else",
  10341. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  10342. "#endif",
  10343. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  10344. // specular
  10345. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  10346. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  10347. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  10348. "#ifdef PHYSICALLY_BASED_SHADING",
  10349. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10350. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10351. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  10352. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  10353. "#else",
  10354. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  10355. "#endif",
  10356. "}",
  10357. "#endif",
  10358. // spot lights
  10359. "#if MAX_SPOT_LIGHTS > 0",
  10360. "vec3 spotDiffuse = vec3( 0.0 );",
  10361. "vec3 spotSpecular = vec3( 0.0 );",
  10362. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10363. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10364. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  10365. "float spotDistance = 1.0;",
  10366. "if ( spotLightDistance[ i ] > 0.0 )",
  10367. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  10368. "spotVector = normalize( spotVector );",
  10369. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  10370. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10371. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10372. // diffuse
  10373. "#ifdef WRAP_AROUND",
  10374. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  10375. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  10376. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  10377. "#else",
  10378. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  10379. "#endif",
  10380. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  10381. // specular
  10382. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  10383. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  10384. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  10385. "#ifdef PHYSICALLY_BASED_SHADING",
  10386. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10387. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10388. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  10389. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  10390. "#else",
  10391. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  10392. "#endif",
  10393. "}",
  10394. "}",
  10395. "#endif",
  10396. // directional lights
  10397. "#if MAX_DIR_LIGHTS > 0",
  10398. "vec3 dirDiffuse = vec3( 0.0 );",
  10399. "vec3 dirSpecular = vec3( 0.0 );",
  10400. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  10401. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10402. "vec3 dirVector = normalize( lDirection.xyz );",
  10403. // diffuse
  10404. "#ifdef WRAP_AROUND",
  10405. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  10406. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  10407. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  10408. "#else",
  10409. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  10410. "#endif",
  10411. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  10412. // specular
  10413. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  10414. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  10415. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  10416. "#ifdef PHYSICALLY_BASED_SHADING",
  10417. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10418. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10419. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  10420. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  10421. "#else",
  10422. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  10423. "#endif",
  10424. "}",
  10425. "#endif",
  10426. // hemisphere lights
  10427. "#if MAX_HEMI_LIGHTS > 0",
  10428. "vec3 hemiDiffuse = vec3( 0.0 );",
  10429. "vec3 hemiSpecular = vec3( 0.0 );" ,
  10430. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10431. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10432. "vec3 lVector = normalize( lDirection.xyz );",
  10433. // diffuse
  10434. "float dotProduct = dot( normal, lVector );",
  10435. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10436. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10437. "hemiDiffuse += uDiffuseColor * hemiColor;",
  10438. // specular (sky light)
  10439. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  10440. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  10441. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  10442. // specular (ground light)
  10443. "vec3 lVectorGround = -lVector;",
  10444. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  10445. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  10446. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  10447. "#ifdef PHYSICALLY_BASED_SHADING",
  10448. "float dotProductGround = dot( normal, lVectorGround );",
  10449. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10450. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  10451. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  10452. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  10453. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  10454. "#else",
  10455. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  10456. "#endif",
  10457. "}",
  10458. "#endif",
  10459. // all lights contribution summation
  10460. "vec3 totalDiffuse = vec3( 0.0 );",
  10461. "vec3 totalSpecular = vec3( 0.0 );",
  10462. "#if MAX_DIR_LIGHTS > 0",
  10463. "totalDiffuse += dirDiffuse;",
  10464. "totalSpecular += dirSpecular;",
  10465. "#endif",
  10466. "#if MAX_HEMI_LIGHTS > 0",
  10467. "totalDiffuse += hemiDiffuse;",
  10468. "totalSpecular += hemiSpecular;",
  10469. "#endif",
  10470. "#if MAX_POINT_LIGHTS > 0",
  10471. "totalDiffuse += pointDiffuse;",
  10472. "totalSpecular += pointSpecular;",
  10473. "#endif",
  10474. "#if MAX_SPOT_LIGHTS > 0",
  10475. "totalDiffuse += spotDiffuse;",
  10476. "totalSpecular += spotSpecular;",
  10477. "#endif",
  10478. "#ifdef METAL",
  10479. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  10480. "#else",
  10481. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  10482. "#endif",
  10483. "if ( enableReflection ) {",
  10484. "vec3 vReflect;",
  10485. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  10486. "if ( useRefract ) {",
  10487. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  10488. "} else {",
  10489. "vReflect = reflect( cameraToVertex, normal );",
  10490. "}",
  10491. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  10492. "#ifdef GAMMA_INPUT",
  10493. "cubeColor.xyz *= cubeColor.xyz;",
  10494. "#endif",
  10495. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  10496. "}",
  10497. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10498. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10499. THREE.ShaderChunk[ "fog_fragment" ],
  10500. "}"
  10501. ].join("\n"),
  10502. vertexShader: [
  10503. "attribute vec4 tangent;",
  10504. "uniform vec2 uOffset;",
  10505. "uniform vec2 uRepeat;",
  10506. "uniform bool enableDisplacement;",
  10507. "#ifdef VERTEX_TEXTURES",
  10508. "uniform sampler2D tDisplacement;",
  10509. "uniform float uDisplacementScale;",
  10510. "uniform float uDisplacementBias;",
  10511. "#endif",
  10512. "varying vec3 vTangent;",
  10513. "varying vec3 vBinormal;",
  10514. "varying vec3 vNormal;",
  10515. "varying vec2 vUv;",
  10516. "varying vec3 vWorldPosition;",
  10517. "varying vec3 vViewPosition;",
  10518. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10519. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10520. "void main() {",
  10521. THREE.ShaderChunk[ "skinbase_vertex" ],
  10522. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10523. // normal, tangent and binormal vectors
  10524. "#ifdef USE_SKINNING",
  10525. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  10526. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  10527. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  10528. "#else",
  10529. "vNormal = normalize( normalMatrix * normal );",
  10530. "vTangent = normalize( normalMatrix * tangent.xyz );",
  10531. "#endif",
  10532. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  10533. "vUv = uv * uRepeat + uOffset;",
  10534. // displacement mapping
  10535. "vec3 displacedPosition;",
  10536. "#ifdef VERTEX_TEXTURES",
  10537. "if ( enableDisplacement ) {",
  10538. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  10539. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  10540. "displacedPosition = position + normalize( normal ) * df;",
  10541. "} else {",
  10542. "#ifdef USE_SKINNING",
  10543. "vec4 skinVertex = vec4( position, 1.0 );",
  10544. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10545. "skinned += boneMatY * skinVertex * skinWeight.y;",
  10546. "displacedPosition = skinned.xyz;",
  10547. "#else",
  10548. "displacedPosition = position;",
  10549. "#endif",
  10550. "}",
  10551. "#else",
  10552. "#ifdef USE_SKINNING",
  10553. "vec4 skinVertex = vec4( position, 1.0 );",
  10554. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10555. "skinned += boneMatY * skinVertex * skinWeight.y;",
  10556. "displacedPosition = skinned.xyz;",
  10557. "#else",
  10558. "displacedPosition = position;",
  10559. "#endif",
  10560. "#endif",
  10561. //
  10562. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  10563. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  10564. "gl_Position = projectionMatrix * mvPosition;",
  10565. //
  10566. "vWorldPosition = worldPosition.xyz;",
  10567. "vViewPosition = -mvPosition.xyz;",
  10568. // shadows
  10569. "#ifdef USE_SHADOWMAP",
  10570. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10571. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  10572. "}",
  10573. "#endif",
  10574. "}"
  10575. ].join("\n")
  10576. },
  10577. /* -------------------------------------------------------------------------
  10578. // Cube map shader
  10579. ------------------------------------------------------------------------- */
  10580. 'cube': {
  10581. uniforms: { "tCube": { type: "t", value: null },
  10582. "tFlip": { type: "f", value: -1 } },
  10583. vertexShader: [
  10584. "varying vec3 vWorldPosition;",
  10585. "void main() {",
  10586. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  10587. "vWorldPosition = worldPosition.xyz;",
  10588. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  10589. "}"
  10590. ].join("\n"),
  10591. fragmentShader: [
  10592. "uniform samplerCube tCube;",
  10593. "uniform float tFlip;",
  10594. "varying vec3 vWorldPosition;",
  10595. "void main() {",
  10596. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  10597. "}"
  10598. ].join("\n")
  10599. },
  10600. // Depth encoding into RGBA texture
  10601. // based on SpiderGL shadow map example
  10602. // http://spidergl.org/example.php?id=6
  10603. // originally from
  10604. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  10605. // see also here:
  10606. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  10607. 'depthRGBA': {
  10608. uniforms: {},
  10609. vertexShader: [
  10610. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10611. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10612. "void main() {",
  10613. THREE.ShaderChunk[ "skinbase_vertex" ],
  10614. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10615. THREE.ShaderChunk[ "skinning_vertex" ],
  10616. THREE.ShaderChunk[ "default_vertex" ],
  10617. "}"
  10618. ].join("\n"),
  10619. fragmentShader: [
  10620. "vec4 pack_depth( const in float depth ) {",
  10621. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  10622. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  10623. "vec4 res = fract( depth * bit_shift );",
  10624. "res -= res.xxyz * bit_mask;",
  10625. "return res;",
  10626. "}",
  10627. "void main() {",
  10628. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  10629. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  10630. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  10631. //"gl_FragData[ 0 ] = pack_depth( z );",
  10632. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  10633. "}"
  10634. ].join("\n")
  10635. }
  10636. };
  10637. /**
  10638. * @author supereggbert / http://www.paulbrunt.co.uk/
  10639. * @author mrdoob / http://mrdoob.com/
  10640. * @author alteredq / http://alteredqualia.com/
  10641. * @author szimek / https://github.com/szimek/
  10642. */
  10643. THREE.WebGLRenderer = function ( parameters ) {
  10644. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  10645. parameters = parameters || {};
  10646. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  10647. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  10648. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  10649. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  10650. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  10651. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  10652. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  10653. _clearColor = parameters.clearColor !== undefined ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ),
  10654. _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0;
  10655. // public properties
  10656. this.domElement = _canvas;
  10657. this.context = null;
  10658. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  10659. ? parameters.devicePixelRatio
  10660. : window.devicePixelRatio !== undefined
  10661. ? window.devicePixelRatio
  10662. : 1;
  10663. // clearing
  10664. this.autoClear = true;
  10665. this.autoClearColor = true;
  10666. this.autoClearDepth = true;
  10667. this.autoClearStencil = true;
  10668. // scene graph
  10669. this.sortObjects = true;
  10670. this.autoUpdateObjects = true;
  10671. this.autoUpdateScene = true;
  10672. // physically based shading
  10673. this.gammaInput = false;
  10674. this.gammaOutput = false;
  10675. this.physicallyBasedShading = false;
  10676. // shadow map
  10677. this.shadowMapEnabled = false;
  10678. this.shadowMapAutoUpdate = true;
  10679. this.shadowMapType = THREE.PCFShadowMap;
  10680. this.shadowMapCullFace = THREE.CullFaceFront;
  10681. this.shadowMapDebug = false;
  10682. this.shadowMapCascade = false;
  10683. // morphs
  10684. this.maxMorphTargets = 8;
  10685. this.maxMorphNormals = 4;
  10686. // flags
  10687. this.autoScaleCubemaps = true;
  10688. // custom render plugins
  10689. this.renderPluginsPre = [];
  10690. this.renderPluginsPost = [];
  10691. // info
  10692. this.info = {
  10693. memory: {
  10694. programs: 0,
  10695. geometries: 0,
  10696. textures: 0
  10697. },
  10698. render: {
  10699. calls: 0,
  10700. vertices: 0,
  10701. faces: 0,
  10702. points: 0
  10703. }
  10704. };
  10705. // internal properties
  10706. var _this = this,
  10707. _programs = [],
  10708. _programs_counter = 0,
  10709. // internal state cache
  10710. _currentProgram = null,
  10711. _currentFramebuffer = null,
  10712. _currentMaterialId = -1,
  10713. _currentGeometryGroupHash = null,
  10714. _currentCamera = null,
  10715. _geometryGroupCounter = 0,
  10716. _usedTextureUnits = 0,
  10717. // GL state cache
  10718. _oldDoubleSided = -1,
  10719. _oldFlipSided = -1,
  10720. _oldBlending = -1,
  10721. _oldBlendEquation = -1,
  10722. _oldBlendSrc = -1,
  10723. _oldBlendDst = -1,
  10724. _oldDepthTest = -1,
  10725. _oldDepthWrite = -1,
  10726. _oldPolygonOffset = null,
  10727. _oldPolygonOffsetFactor = null,
  10728. _oldPolygonOffsetUnits = null,
  10729. _oldLineWidth = null,
  10730. _viewportX = 0,
  10731. _viewportY = 0,
  10732. _viewportWidth = 0,
  10733. _viewportHeight = 0,
  10734. _currentWidth = 0,
  10735. _currentHeight = 0,
  10736. _enabledAttributes = {},
  10737. // frustum
  10738. _frustum = new THREE.Frustum(),
  10739. // camera matrices cache
  10740. _projScreenMatrix = new THREE.Matrix4(),
  10741. _projScreenMatrixPS = new THREE.Matrix4(),
  10742. _vector3 = new THREE.Vector3(),
  10743. // light arrays cache
  10744. _direction = new THREE.Vector3(),
  10745. _lightsNeedUpdate = true,
  10746. _lights = {
  10747. ambient: [ 0, 0, 0 ],
  10748. directional: { length: 0, colors: new Array(), positions: new Array() },
  10749. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  10750. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  10751. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  10752. };
  10753. // initialize
  10754. var _gl;
  10755. var _glExtensionTextureFloat;
  10756. var _glExtensionStandardDerivatives;
  10757. var _glExtensionTextureFilterAnisotropic;
  10758. var _glExtensionCompressedTextureS3TC;
  10759. initGL();
  10760. setDefaultGLState();
  10761. this.context = _gl;
  10762. // GPU capabilities
  10763. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  10764. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  10765. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  10766. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  10767. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  10768. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  10769. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  10770. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  10771. //
  10772. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  10773. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  10774. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  10775. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  10776. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  10777. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  10778. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  10779. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  10780. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  10781. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  10782. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  10783. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  10784. // clamp precision to maximum available
  10785. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  10786. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  10787. if ( _precision === "highp" && ! highpAvailable ) {
  10788. if ( mediumpAvailable ) {
  10789. _precision = "mediump";
  10790. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  10791. } else {
  10792. _precision = "lowp";
  10793. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  10794. }
  10795. }
  10796. if ( _precision === "mediump" && ! mediumpAvailable ) {
  10797. _precision = "lowp";
  10798. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  10799. }
  10800. // API
  10801. this.getContext = function () {
  10802. return _gl;
  10803. };
  10804. this.supportsVertexTextures = function () {
  10805. return _supportsVertexTextures;
  10806. };
  10807. this.supportsFloatTextures = function () {
  10808. return _glExtensionTextureFloat;
  10809. };
  10810. this.supportsStandardDerivatives = function () {
  10811. return _glExtensionStandardDerivatives;
  10812. };
  10813. this.supportsCompressedTextureS3TC = function () {
  10814. return _glExtensionCompressedTextureS3TC;
  10815. };
  10816. this.getMaxAnisotropy = function () {
  10817. return _maxAnisotropy;
  10818. };
  10819. this.getPrecision = function () {
  10820. return _precision;
  10821. };
  10822. this.setSize = function ( width, height ) {
  10823. _canvas.width = width * this.devicePixelRatio;
  10824. _canvas.height = height * this.devicePixelRatio;
  10825. _canvas.style.width = width + 'px';
  10826. _canvas.style.height = height + 'px';
  10827. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  10828. };
  10829. this.setViewport = function ( x, y, width, height ) {
  10830. _viewportX = x !== undefined ? x : 0;
  10831. _viewportY = y !== undefined ? y : 0;
  10832. _viewportWidth = width !== undefined ? width : _canvas.width;
  10833. _viewportHeight = height !== undefined ? height : _canvas.height;
  10834. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  10835. };
  10836. this.setScissor = function ( x, y, width, height ) {
  10837. _gl.scissor( x, y, width, height );
  10838. };
  10839. this.enableScissorTest = function ( enable ) {
  10840. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  10841. };
  10842. // Clearing
  10843. this.setClearColorHex = function ( hex, alpha ) {
  10844. _clearColor.setHex( hex );
  10845. _clearAlpha = alpha;
  10846. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  10847. };
  10848. this.setClearColor = function ( color, alpha ) {
  10849. _clearColor.copy( color );
  10850. _clearAlpha = alpha;
  10851. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  10852. };
  10853. this.getClearColor = function () {
  10854. return _clearColor;
  10855. };
  10856. this.getClearAlpha = function () {
  10857. return _clearAlpha;
  10858. };
  10859. this.clear = function ( color, depth, stencil ) {
  10860. var bits = 0;
  10861. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  10862. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  10863. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  10864. _gl.clear( bits );
  10865. };
  10866. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  10867. this.setRenderTarget( renderTarget );
  10868. this.clear( color, depth, stencil );
  10869. };
  10870. // Plugins
  10871. this.addPostPlugin = function ( plugin ) {
  10872. plugin.init( this );
  10873. this.renderPluginsPost.push( plugin );
  10874. };
  10875. this.addPrePlugin = function ( plugin ) {
  10876. plugin.init( this );
  10877. this.renderPluginsPre.push( plugin );
  10878. };
  10879. // Rendering
  10880. this.updateShadowMap = function ( scene, camera ) {
  10881. _currentProgram = null;
  10882. _oldBlending = -1;
  10883. _oldDepthTest = -1;
  10884. _oldDepthWrite = -1;
  10885. _currentGeometryGroupHash = -1;
  10886. _currentMaterialId = -1;
  10887. _lightsNeedUpdate = true;
  10888. _oldDoubleSided = -1;
  10889. _oldFlipSided = -1;
  10890. this.shadowMapPlugin.update( scene, camera );
  10891. };
  10892. // Internal functions
  10893. // Buffer allocation
  10894. function createParticleBuffers ( geometry ) {
  10895. geometry.__webglVertexBuffer = _gl.createBuffer();
  10896. geometry.__webglColorBuffer = _gl.createBuffer();
  10897. _this.info.memory.geometries ++;
  10898. };
  10899. function createLineBuffers ( geometry ) {
  10900. geometry.__webglVertexBuffer = _gl.createBuffer();
  10901. geometry.__webglColorBuffer = _gl.createBuffer();
  10902. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  10903. _this.info.memory.geometries ++;
  10904. };
  10905. function createRibbonBuffers ( geometry ) {
  10906. geometry.__webglVertexBuffer = _gl.createBuffer();
  10907. geometry.__webglColorBuffer = _gl.createBuffer();
  10908. geometry.__webglNormalBuffer = _gl.createBuffer();
  10909. _this.info.memory.geometries ++;
  10910. };
  10911. function createMeshBuffers ( geometryGroup ) {
  10912. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  10913. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  10914. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  10915. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  10916. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  10917. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  10918. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  10919. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  10920. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  10921. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  10922. var m, ml;
  10923. if ( geometryGroup.numMorphTargets ) {
  10924. geometryGroup.__webglMorphTargetsBuffers = [];
  10925. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10926. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  10927. }
  10928. }
  10929. if ( geometryGroup.numMorphNormals ) {
  10930. geometryGroup.__webglMorphNormalsBuffers = [];
  10931. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10932. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  10933. }
  10934. }
  10935. _this.info.memory.geometries ++;
  10936. };
  10937. // Events
  10938. var onGeometryDispose = function ( event ) {
  10939. var geometry = event.target;
  10940. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10941. deallocateGeometry( geometry );
  10942. _this.info.memory.geometries --;
  10943. };
  10944. var onTextureDispose = function ( event ) {
  10945. var texture = event.target;
  10946. texture.removeEventListener( 'dispose', onTextureDispose );
  10947. deallocateTexture( texture );
  10948. _this.info.memory.textures --;
  10949. };
  10950. var onRenderTargetDispose = function ( event ) {
  10951. var renderTarget = event.target;
  10952. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  10953. deallocateRenderTarget( renderTarget );
  10954. _this.info.memory.textures --;
  10955. };
  10956. var onMaterialDispose = function ( event ) {
  10957. var material = event.target;
  10958. material.removeEventListener( 'dispose', onMaterialDispose );
  10959. deallocateMaterial( material );
  10960. };
  10961. // Buffer deallocation
  10962. var deallocateGeometry = function ( geometry ) {
  10963. geometry.__webglInit = undefined;
  10964. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10965. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  10966. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  10967. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  10968. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  10969. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  10970. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  10971. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  10972. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  10973. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  10974. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  10975. // geometry groups
  10976. if ( geometry.geometryGroups !== undefined ) {
  10977. for ( var g in geometry.geometryGroups ) {
  10978. var geometryGroup = geometry.geometryGroups[ g ];
  10979. if ( geometryGroup.numMorphTargets !== undefined ) {
  10980. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10981. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  10982. }
  10983. }
  10984. if ( geometryGroup.numMorphNormals !== undefined ) {
  10985. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10986. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  10987. }
  10988. }
  10989. deleteCustomAttributesBuffers( geometryGroup );
  10990. }
  10991. }
  10992. deleteCustomAttributesBuffers( geometry );
  10993. };
  10994. var deallocateTexture = function ( texture ) {
  10995. if ( texture.image && texture.image.__webglTextureCube ) {
  10996. // cube texture
  10997. _gl.deleteTexture( texture.image.__webglTextureCube );
  10998. } else {
  10999. // 2D texture
  11000. if ( ! texture.__webglInit ) return;
  11001. texture.__webglInit = false;
  11002. _gl.deleteTexture( texture.__webglTexture );
  11003. }
  11004. };
  11005. var deallocateRenderTarget = function ( renderTarget ) {
  11006. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  11007. _gl.deleteTexture( renderTarget.__webglTexture );
  11008. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  11009. for ( var i = 0; i < 6; i ++ ) {
  11010. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  11011. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  11012. }
  11013. } else {
  11014. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  11015. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  11016. }
  11017. };
  11018. var deallocateMaterial = function ( material ) {
  11019. var program = material.program;
  11020. if ( program === undefined ) return;
  11021. material.program = undefined;
  11022. // only deallocate GL program if this was the last use of shared program
  11023. // assumed there is only single copy of any program in the _programs list
  11024. // (that's how it's constructed)
  11025. var i, il, programInfo;
  11026. var deleteProgram = false;
  11027. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11028. programInfo = _programs[ i ];
  11029. if ( programInfo.program === program ) {
  11030. programInfo.usedTimes --;
  11031. if ( programInfo.usedTimes === 0 ) {
  11032. deleteProgram = true;
  11033. }
  11034. break;
  11035. }
  11036. }
  11037. if ( deleteProgram === true ) {
  11038. // avoid using array.splice, this is costlier than creating new array from scratch
  11039. var newPrograms = [];
  11040. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11041. programInfo = _programs[ i ];
  11042. if ( programInfo.program !== program ) {
  11043. newPrograms.push( programInfo );
  11044. }
  11045. }
  11046. _programs = newPrograms;
  11047. _gl.deleteProgram( program );
  11048. _this.info.memory.programs --;
  11049. }
  11050. };
  11051. //
  11052. /*
  11053. function deleteParticleBuffers ( geometry ) {
  11054. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  11055. _gl.deleteBuffer( geometry.__webglColorBuffer );
  11056. deleteCustomAttributesBuffers( geometry );
  11057. _this.info.memory.geometries --;
  11058. };
  11059. function deleteLineBuffers ( geometry ) {
  11060. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  11061. _gl.deleteBuffer( geometry.__webglColorBuffer );
  11062. _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  11063. deleteCustomAttributesBuffers( geometry );
  11064. _this.info.memory.geometries --;
  11065. };
  11066. function deleteRibbonBuffers ( geometry ) {
  11067. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  11068. _gl.deleteBuffer( geometry.__webglColorBuffer );
  11069. _gl.deleteBuffer( geometry.__webglNormalBuffer );
  11070. deleteCustomAttributesBuffers( geometry );
  11071. _this.info.memory.geometries --;
  11072. };
  11073. function deleteMeshBuffers ( geometryGroup ) {
  11074. _gl.deleteBuffer( geometryGroup.__webglVertexBuffer );
  11075. _gl.deleteBuffer( geometryGroup.__webglNormalBuffer );
  11076. _gl.deleteBuffer( geometryGroup.__webglTangentBuffer );
  11077. _gl.deleteBuffer( geometryGroup.__webglColorBuffer );
  11078. _gl.deleteBuffer( geometryGroup.__webglUVBuffer );
  11079. _gl.deleteBuffer( geometryGroup.__webglUV2Buffer );
  11080. _gl.deleteBuffer( geometryGroup.__webglSkinIndicesBuffer );
  11081. _gl.deleteBuffer( geometryGroup.__webglSkinWeightsBuffer );
  11082. _gl.deleteBuffer( geometryGroup.__webglFaceBuffer );
  11083. _gl.deleteBuffer( geometryGroup.__webglLineBuffer );
  11084. var m, ml;
  11085. if ( geometryGroup.numMorphTargets ) {
  11086. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11087. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  11088. }
  11089. }
  11090. if ( geometryGroup.numMorphNormals ) {
  11091. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11092. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  11093. }
  11094. }
  11095. deleteCustomAttributesBuffers( geometryGroup );
  11096. _this.info.memory.geometries --;
  11097. };
  11098. */
  11099. function deleteCustomAttributesBuffers( geometry ) {
  11100. if ( geometry.__webglCustomAttributesList ) {
  11101. for ( var id in geometry.__webglCustomAttributesList ) {
  11102. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  11103. }
  11104. }
  11105. };
  11106. // Buffer initialization
  11107. function initCustomAttributes ( geometry, object ) {
  11108. var nvertices = geometry.vertices.length;
  11109. var material = object.material;
  11110. if ( material.attributes ) {
  11111. if ( geometry.__webglCustomAttributesList === undefined ) {
  11112. geometry.__webglCustomAttributesList = [];
  11113. }
  11114. for ( var a in material.attributes ) {
  11115. var attribute = material.attributes[ a ];
  11116. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  11117. attribute.__webglInitialized = true;
  11118. var size = 1; // "f" and "i"
  11119. if ( attribute.type === "v2" ) size = 2;
  11120. else if ( attribute.type === "v3" ) size = 3;
  11121. else if ( attribute.type === "v4" ) size = 4;
  11122. else if ( attribute.type === "c" ) size = 3;
  11123. attribute.size = size;
  11124. attribute.array = new Float32Array( nvertices * size );
  11125. attribute.buffer = _gl.createBuffer();
  11126. attribute.buffer.belongsToAttribute = a;
  11127. attribute.needsUpdate = true;
  11128. }
  11129. geometry.__webglCustomAttributesList.push( attribute );
  11130. }
  11131. }
  11132. };
  11133. function initParticleBuffers ( geometry, object ) {
  11134. var nvertices = geometry.vertices.length;
  11135. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11136. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11137. geometry.__sortArray = [];
  11138. geometry.__webglParticleCount = nvertices;
  11139. initCustomAttributes ( geometry, object );
  11140. };
  11141. function initLineBuffers ( geometry, object ) {
  11142. var nvertices = geometry.vertices.length;
  11143. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11144. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11145. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  11146. geometry.__webglLineCount = nvertices;
  11147. initCustomAttributes ( geometry, object );
  11148. };
  11149. function initRibbonBuffers ( geometry, object ) {
  11150. var nvertices = geometry.vertices.length;
  11151. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11152. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11153. geometry.__normalArray = new Float32Array( nvertices * 3 );
  11154. geometry.__webglVertexCount = nvertices;
  11155. initCustomAttributes ( geometry, object );
  11156. };
  11157. function initMeshBuffers ( geometryGroup, object ) {
  11158. var geometry = object.geometry,
  11159. faces3 = geometryGroup.faces3,
  11160. faces4 = geometryGroup.faces4,
  11161. nvertices = faces3.length * 3 + faces4.length * 4,
  11162. ntris = faces3.length * 1 + faces4.length * 2,
  11163. nlines = faces3.length * 3 + faces4.length * 4,
  11164. material = getBufferMaterial( object, geometryGroup ),
  11165. uvType = bufferGuessUVType( material ),
  11166. normalType = bufferGuessNormalType( material ),
  11167. vertexColorType = bufferGuessVertexColorType( material );
  11168. //console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  11169. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  11170. if ( normalType ) {
  11171. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  11172. }
  11173. if ( geometry.hasTangents ) {
  11174. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  11175. }
  11176. if ( vertexColorType ) {
  11177. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  11178. }
  11179. if ( uvType ) {
  11180. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  11181. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  11182. }
  11183. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  11184. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  11185. }
  11186. }
  11187. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  11188. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  11189. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  11190. }
  11191. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  11192. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  11193. var m, ml;
  11194. if ( geometryGroup.numMorphTargets ) {
  11195. geometryGroup.__morphTargetsArrays = [];
  11196. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11197. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  11198. }
  11199. }
  11200. if ( geometryGroup.numMorphNormals ) {
  11201. geometryGroup.__morphNormalsArrays = [];
  11202. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11203. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  11204. }
  11205. }
  11206. geometryGroup.__webglFaceCount = ntris * 3;
  11207. geometryGroup.__webglLineCount = nlines * 2;
  11208. // custom attributes
  11209. if ( material.attributes ) {
  11210. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  11211. geometryGroup.__webglCustomAttributesList = [];
  11212. }
  11213. for ( var a in material.attributes ) {
  11214. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  11215. // attribute buffers which are correctly indexed in the setMeshBuffers function
  11216. var originalAttribute = material.attributes[ a ];
  11217. var attribute = {};
  11218. for ( var property in originalAttribute ) {
  11219. attribute[ property ] = originalAttribute[ property ];
  11220. }
  11221. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  11222. attribute.__webglInitialized = true;
  11223. var size = 1; // "f" and "i"
  11224. if( attribute.type === "v2" ) size = 2;
  11225. else if( attribute.type === "v3" ) size = 3;
  11226. else if( attribute.type === "v4" ) size = 4;
  11227. else if( attribute.type === "c" ) size = 3;
  11228. attribute.size = size;
  11229. attribute.array = new Float32Array( nvertices * size );
  11230. attribute.buffer = _gl.createBuffer();
  11231. attribute.buffer.belongsToAttribute = a;
  11232. originalAttribute.needsUpdate = true;
  11233. attribute.__original = originalAttribute;
  11234. }
  11235. geometryGroup.__webglCustomAttributesList.push( attribute );
  11236. }
  11237. }
  11238. geometryGroup.__inittedArrays = true;
  11239. };
  11240. function getBufferMaterial( object, geometryGroup ) {
  11241. return object.material instanceof THREE.MeshFaceMaterial
  11242. ? object.material.materials[ geometryGroup.materialIndex ]
  11243. : object.material;
  11244. };
  11245. function materialNeedsSmoothNormals ( material ) {
  11246. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  11247. };
  11248. function bufferGuessNormalType ( material ) {
  11249. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  11250. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  11251. return false;
  11252. }
  11253. if ( materialNeedsSmoothNormals( material ) ) {
  11254. return THREE.SmoothShading;
  11255. } else {
  11256. return THREE.FlatShading;
  11257. }
  11258. };
  11259. function bufferGuessVertexColorType ( material ) {
  11260. if ( material.vertexColors ) {
  11261. return material.vertexColors;
  11262. }
  11263. return false;
  11264. };
  11265. function bufferGuessUVType ( material ) {
  11266. // material must use some texture to require uvs
  11267. if ( material.map || material.lightMap || material.bumpMap || material.normalMap || material.specularMap || material instanceof THREE.ShaderMaterial ) {
  11268. return true;
  11269. }
  11270. return false;
  11271. };
  11272. //
  11273. function initDirectBuffers( geometry ) {
  11274. var a, attribute, type;
  11275. for ( a in geometry.attributes ) {
  11276. if ( a === "index" ) {
  11277. type = _gl.ELEMENT_ARRAY_BUFFER;
  11278. } else {
  11279. type = _gl.ARRAY_BUFFER;
  11280. }
  11281. attribute = geometry.attributes[ a ];
  11282. attribute.buffer = _gl.createBuffer();
  11283. _gl.bindBuffer( type, attribute.buffer );
  11284. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  11285. }
  11286. };
  11287. // Buffer setting
  11288. function setParticleBuffers ( geometry, hint, object ) {
  11289. var v, c, vertex, offset, index, color,
  11290. vertices = geometry.vertices,
  11291. vl = vertices.length,
  11292. colors = geometry.colors,
  11293. cl = colors.length,
  11294. vertexArray = geometry.__vertexArray,
  11295. colorArray = geometry.__colorArray,
  11296. sortArray = geometry.__sortArray,
  11297. dirtyVertices = geometry.verticesNeedUpdate,
  11298. dirtyElements = geometry.elementsNeedUpdate,
  11299. dirtyColors = geometry.colorsNeedUpdate,
  11300. customAttributes = geometry.__webglCustomAttributesList,
  11301. i, il,
  11302. a, ca, cal, value,
  11303. customAttribute;
  11304. if ( object.sortParticles ) {
  11305. _projScreenMatrixPS.copy( _projScreenMatrix );
  11306. _projScreenMatrixPS.multiply( object.matrixWorld );
  11307. for ( v = 0; v < vl; v ++ ) {
  11308. vertex = vertices[ v ];
  11309. _vector3.copy( vertex );
  11310. _vector3.applyProjection( _projScreenMatrixPS );
  11311. sortArray[ v ] = [ _vector3.z, v ];
  11312. }
  11313. sortArray.sort( numericalSort );
  11314. for ( v = 0; v < vl; v ++ ) {
  11315. vertex = vertices[ sortArray[v][1] ];
  11316. offset = v * 3;
  11317. vertexArray[ offset ] = vertex.x;
  11318. vertexArray[ offset + 1 ] = vertex.y;
  11319. vertexArray[ offset + 2 ] = vertex.z;
  11320. }
  11321. for ( c = 0; c < cl; c ++ ) {
  11322. offset = c * 3;
  11323. color = colors[ sortArray[c][1] ];
  11324. colorArray[ offset ] = color.r;
  11325. colorArray[ offset + 1 ] = color.g;
  11326. colorArray[ offset + 2 ] = color.b;
  11327. }
  11328. if ( customAttributes ) {
  11329. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11330. customAttribute = customAttributes[ i ];
  11331. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  11332. offset = 0;
  11333. cal = customAttribute.value.length;
  11334. if ( customAttribute.size === 1 ) {
  11335. for ( ca = 0; ca < cal; ca ++ ) {
  11336. index = sortArray[ ca ][ 1 ];
  11337. customAttribute.array[ ca ] = customAttribute.value[ index ];
  11338. }
  11339. } else if ( customAttribute.size === 2 ) {
  11340. for ( ca = 0; ca < cal; ca ++ ) {
  11341. index = sortArray[ ca ][ 1 ];
  11342. value = customAttribute.value[ index ];
  11343. customAttribute.array[ offset ] = value.x;
  11344. customAttribute.array[ offset + 1 ] = value.y;
  11345. offset += 2;
  11346. }
  11347. } else if ( customAttribute.size === 3 ) {
  11348. if ( customAttribute.type === "c" ) {
  11349. for ( ca = 0; ca < cal; ca ++ ) {
  11350. index = sortArray[ ca ][ 1 ];
  11351. value = customAttribute.value[ index ];
  11352. customAttribute.array[ offset ] = value.r;
  11353. customAttribute.array[ offset + 1 ] = value.g;
  11354. customAttribute.array[ offset + 2 ] = value.b;
  11355. offset += 3;
  11356. }
  11357. } else {
  11358. for ( ca = 0; ca < cal; ca ++ ) {
  11359. index = sortArray[ ca ][ 1 ];
  11360. value = customAttribute.value[ index ];
  11361. customAttribute.array[ offset ] = value.x;
  11362. customAttribute.array[ offset + 1 ] = value.y;
  11363. customAttribute.array[ offset + 2 ] = value.z;
  11364. offset += 3;
  11365. }
  11366. }
  11367. } else if ( customAttribute.size === 4 ) {
  11368. for ( ca = 0; ca < cal; ca ++ ) {
  11369. index = sortArray[ ca ][ 1 ];
  11370. value = customAttribute.value[ index ];
  11371. customAttribute.array[ offset ] = value.x;
  11372. customAttribute.array[ offset + 1 ] = value.y;
  11373. customAttribute.array[ offset + 2 ] = value.z;
  11374. customAttribute.array[ offset + 3 ] = value.w;
  11375. offset += 4;
  11376. }
  11377. }
  11378. }
  11379. }
  11380. } else {
  11381. if ( dirtyVertices ) {
  11382. for ( v = 0; v < vl; v ++ ) {
  11383. vertex = vertices[ v ];
  11384. offset = v * 3;
  11385. vertexArray[ offset ] = vertex.x;
  11386. vertexArray[ offset + 1 ] = vertex.y;
  11387. vertexArray[ offset + 2 ] = vertex.z;
  11388. }
  11389. }
  11390. if ( dirtyColors ) {
  11391. for ( c = 0; c < cl; c ++ ) {
  11392. color = colors[ c ];
  11393. offset = c * 3;
  11394. colorArray[ offset ] = color.r;
  11395. colorArray[ offset + 1 ] = color.g;
  11396. colorArray[ offset + 2 ] = color.b;
  11397. }
  11398. }
  11399. if ( customAttributes ) {
  11400. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11401. customAttribute = customAttributes[ i ];
  11402. if ( customAttribute.needsUpdate &&
  11403. ( customAttribute.boundTo === undefined ||
  11404. customAttribute.boundTo === "vertices") ) {
  11405. cal = customAttribute.value.length;
  11406. offset = 0;
  11407. if ( customAttribute.size === 1 ) {
  11408. for ( ca = 0; ca < cal; ca ++ ) {
  11409. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11410. }
  11411. } else if ( customAttribute.size === 2 ) {
  11412. for ( ca = 0; ca < cal; ca ++ ) {
  11413. value = customAttribute.value[ ca ];
  11414. customAttribute.array[ offset ] = value.x;
  11415. customAttribute.array[ offset + 1 ] = value.y;
  11416. offset += 2;
  11417. }
  11418. } else if ( customAttribute.size === 3 ) {
  11419. if ( customAttribute.type === "c" ) {
  11420. for ( ca = 0; ca < cal; ca ++ ) {
  11421. value = customAttribute.value[ ca ];
  11422. customAttribute.array[ offset ] = value.r;
  11423. customAttribute.array[ offset + 1 ] = value.g;
  11424. customAttribute.array[ offset + 2 ] = value.b;
  11425. offset += 3;
  11426. }
  11427. } else {
  11428. for ( ca = 0; ca < cal; ca ++ ) {
  11429. value = customAttribute.value[ ca ];
  11430. customAttribute.array[ offset ] = value.x;
  11431. customAttribute.array[ offset + 1 ] = value.y;
  11432. customAttribute.array[ offset + 2 ] = value.z;
  11433. offset += 3;
  11434. }
  11435. }
  11436. } else if ( customAttribute.size === 4 ) {
  11437. for ( ca = 0; ca < cal; ca ++ ) {
  11438. value = customAttribute.value[ ca ];
  11439. customAttribute.array[ offset ] = value.x;
  11440. customAttribute.array[ offset + 1 ] = value.y;
  11441. customAttribute.array[ offset + 2 ] = value.z;
  11442. customAttribute.array[ offset + 3 ] = value.w;
  11443. offset += 4;
  11444. }
  11445. }
  11446. }
  11447. }
  11448. }
  11449. }
  11450. if ( dirtyVertices || object.sortParticles ) {
  11451. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11452. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11453. }
  11454. if ( dirtyColors || object.sortParticles ) {
  11455. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11456. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11457. }
  11458. if ( customAttributes ) {
  11459. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11460. customAttribute = customAttributes[ i ];
  11461. if ( customAttribute.needsUpdate || object.sortParticles ) {
  11462. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11463. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11464. }
  11465. }
  11466. }
  11467. };
  11468. function setLineBuffers ( geometry, hint ) {
  11469. var v, c, d, vertex, offset, color,
  11470. vertices = geometry.vertices,
  11471. colors = geometry.colors,
  11472. lineDistances = geometry.lineDistances,
  11473. vl = vertices.length,
  11474. cl = colors.length,
  11475. dl = lineDistances.length,
  11476. vertexArray = geometry.__vertexArray,
  11477. colorArray = geometry.__colorArray,
  11478. lineDistanceArray = geometry.__lineDistanceArray,
  11479. dirtyVertices = geometry.verticesNeedUpdate,
  11480. dirtyColors = geometry.colorsNeedUpdate,
  11481. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  11482. customAttributes = geometry.__webglCustomAttributesList,
  11483. i, il,
  11484. a, ca, cal, value,
  11485. customAttribute;
  11486. if ( dirtyVertices ) {
  11487. for ( v = 0; v < vl; v ++ ) {
  11488. vertex = vertices[ v ];
  11489. offset = v * 3;
  11490. vertexArray[ offset ] = vertex.x;
  11491. vertexArray[ offset + 1 ] = vertex.y;
  11492. vertexArray[ offset + 2 ] = vertex.z;
  11493. }
  11494. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11495. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11496. }
  11497. if ( dirtyColors ) {
  11498. for ( c = 0; c < cl; c ++ ) {
  11499. color = colors[ c ];
  11500. offset = c * 3;
  11501. colorArray[ offset ] = color.r;
  11502. colorArray[ offset + 1 ] = color.g;
  11503. colorArray[ offset + 2 ] = color.b;
  11504. }
  11505. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11506. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11507. }
  11508. if ( dirtyLineDistances ) {
  11509. for ( d = 0; d < dl; d ++ ) {
  11510. lineDistanceArray[ d ] = lineDistances[ d ];
  11511. }
  11512. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  11513. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  11514. }
  11515. if ( customAttributes ) {
  11516. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11517. customAttribute = customAttributes[ i ];
  11518. if ( customAttribute.needsUpdate &&
  11519. ( customAttribute.boundTo === undefined ||
  11520. customAttribute.boundTo === "vertices" ) ) {
  11521. offset = 0;
  11522. cal = customAttribute.value.length;
  11523. if ( customAttribute.size === 1 ) {
  11524. for ( ca = 0; ca < cal; ca ++ ) {
  11525. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11526. }
  11527. } else if ( customAttribute.size === 2 ) {
  11528. for ( ca = 0; ca < cal; ca ++ ) {
  11529. value = customAttribute.value[ ca ];
  11530. customAttribute.array[ offset ] = value.x;
  11531. customAttribute.array[ offset + 1 ] = value.y;
  11532. offset += 2;
  11533. }
  11534. } else if ( customAttribute.size === 3 ) {
  11535. if ( customAttribute.type === "c" ) {
  11536. for ( ca = 0; ca < cal; ca ++ ) {
  11537. value = customAttribute.value[ ca ];
  11538. customAttribute.array[ offset ] = value.r;
  11539. customAttribute.array[ offset + 1 ] = value.g;
  11540. customAttribute.array[ offset + 2 ] = value.b;
  11541. offset += 3;
  11542. }
  11543. } else {
  11544. for ( ca = 0; ca < cal; ca ++ ) {
  11545. value = customAttribute.value[ ca ];
  11546. customAttribute.array[ offset ] = value.x;
  11547. customAttribute.array[ offset + 1 ] = value.y;
  11548. customAttribute.array[ offset + 2 ] = value.z;
  11549. offset += 3;
  11550. }
  11551. }
  11552. } else if ( customAttribute.size === 4 ) {
  11553. for ( ca = 0; ca < cal; ca ++ ) {
  11554. value = customAttribute.value[ ca ];
  11555. customAttribute.array[ offset ] = value.x;
  11556. customAttribute.array[ offset + 1 ] = value.y;
  11557. customAttribute.array[ offset + 2 ] = value.z;
  11558. customAttribute.array[ offset + 3 ] = value.w;
  11559. offset += 4;
  11560. }
  11561. }
  11562. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11563. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11564. }
  11565. }
  11566. }
  11567. };
  11568. function setRibbonBuffers ( geometry, hint ) {
  11569. var v, c, n, vertex, offset, color, normal,
  11570. i, il, ca, cal, customAttribute, value,
  11571. vertices = geometry.vertices,
  11572. colors = geometry.colors,
  11573. normals = geometry.normals,
  11574. vl = vertices.length,
  11575. cl = colors.length,
  11576. nl = normals.length,
  11577. vertexArray = geometry.__vertexArray,
  11578. colorArray = geometry.__colorArray,
  11579. normalArray = geometry.__normalArray,
  11580. dirtyVertices = geometry.verticesNeedUpdate,
  11581. dirtyColors = geometry.colorsNeedUpdate,
  11582. dirtyNormals = geometry.normalsNeedUpdate,
  11583. customAttributes = geometry.__webglCustomAttributesList;
  11584. if ( dirtyVertices ) {
  11585. for ( v = 0; v < vl; v ++ ) {
  11586. vertex = vertices[ v ];
  11587. offset = v * 3;
  11588. vertexArray[ offset ] = vertex.x;
  11589. vertexArray[ offset + 1 ] = vertex.y;
  11590. vertexArray[ offset + 2 ] = vertex.z;
  11591. }
  11592. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11593. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11594. }
  11595. if ( dirtyColors ) {
  11596. for ( c = 0; c < cl; c ++ ) {
  11597. color = colors[ c ];
  11598. offset = c * 3;
  11599. colorArray[ offset ] = color.r;
  11600. colorArray[ offset + 1 ] = color.g;
  11601. colorArray[ offset + 2 ] = color.b;
  11602. }
  11603. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11604. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11605. }
  11606. if ( dirtyNormals ) {
  11607. for ( n = 0; n < nl; n ++ ) {
  11608. normal = normals[ n ];
  11609. offset = n * 3;
  11610. normalArray[ offset ] = normal.x;
  11611. normalArray[ offset + 1 ] = normal.y;
  11612. normalArray[ offset + 2 ] = normal.z;
  11613. }
  11614. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglNormalBuffer );
  11615. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  11616. }
  11617. if ( customAttributes ) {
  11618. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11619. customAttribute = customAttributes[ i ];
  11620. if ( customAttribute.needsUpdate &&
  11621. ( customAttribute.boundTo === undefined ||
  11622. customAttribute.boundTo === "vertices" ) ) {
  11623. offset = 0;
  11624. cal = customAttribute.value.length;
  11625. if ( customAttribute.size === 1 ) {
  11626. for ( ca = 0; ca < cal; ca ++ ) {
  11627. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11628. }
  11629. } else if ( customAttribute.size === 2 ) {
  11630. for ( ca = 0; ca < cal; ca ++ ) {
  11631. value = customAttribute.value[ ca ];
  11632. customAttribute.array[ offset ] = value.x;
  11633. customAttribute.array[ offset + 1 ] = value.y;
  11634. offset += 2;
  11635. }
  11636. } else if ( customAttribute.size === 3 ) {
  11637. if ( customAttribute.type === "c" ) {
  11638. for ( ca = 0; ca < cal; ca ++ ) {
  11639. value = customAttribute.value[ ca ];
  11640. customAttribute.array[ offset ] = value.r;
  11641. customAttribute.array[ offset + 1 ] = value.g;
  11642. customAttribute.array[ offset + 2 ] = value.b;
  11643. offset += 3;
  11644. }
  11645. } else {
  11646. for ( ca = 0; ca < cal; ca ++ ) {
  11647. value = customAttribute.value[ ca ];
  11648. customAttribute.array[ offset ] = value.x;
  11649. customAttribute.array[ offset + 1 ] = value.y;
  11650. customAttribute.array[ offset + 2 ] = value.z;
  11651. offset += 3;
  11652. }
  11653. }
  11654. } else if ( customAttribute.size === 4 ) {
  11655. for ( ca = 0; ca < cal; ca ++ ) {
  11656. value = customAttribute.value[ ca ];
  11657. customAttribute.array[ offset ] = value.x;
  11658. customAttribute.array[ offset + 1 ] = value.y;
  11659. customAttribute.array[ offset + 2 ] = value.z;
  11660. customAttribute.array[ offset + 3 ] = value.w;
  11661. offset += 4;
  11662. }
  11663. }
  11664. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11665. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11666. }
  11667. }
  11668. }
  11669. };
  11670. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  11671. if ( ! geometryGroup.__inittedArrays ) {
  11672. return;
  11673. }
  11674. var normalType = bufferGuessNormalType( material ),
  11675. vertexColorType = bufferGuessVertexColorType( material ),
  11676. uvType = bufferGuessUVType( material ),
  11677. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  11678. var f, fl, fi, face,
  11679. vertexNormals, faceNormal, normal,
  11680. vertexColors, faceColor,
  11681. vertexTangents,
  11682. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  11683. c1, c2, c3, c4,
  11684. sw1, sw2, sw3, sw4,
  11685. si1, si2, si3, si4,
  11686. sa1, sa2, sa3, sa4,
  11687. sb1, sb2, sb3, sb4,
  11688. m, ml, i, il,
  11689. vn, uvi, uv2i,
  11690. vk, vkl, vka,
  11691. nka, chf, faceVertexNormals,
  11692. a,
  11693. vertexIndex = 0,
  11694. offset = 0,
  11695. offset_uv = 0,
  11696. offset_uv2 = 0,
  11697. offset_face = 0,
  11698. offset_normal = 0,
  11699. offset_tangent = 0,
  11700. offset_line = 0,
  11701. offset_color = 0,
  11702. offset_skin = 0,
  11703. offset_morphTarget = 0,
  11704. offset_custom = 0,
  11705. offset_customSrc = 0,
  11706. value,
  11707. vertexArray = geometryGroup.__vertexArray,
  11708. uvArray = geometryGroup.__uvArray,
  11709. uv2Array = geometryGroup.__uv2Array,
  11710. normalArray = geometryGroup.__normalArray,
  11711. tangentArray = geometryGroup.__tangentArray,
  11712. colorArray = geometryGroup.__colorArray,
  11713. skinIndexArray = geometryGroup.__skinIndexArray,
  11714. skinWeightArray = geometryGroup.__skinWeightArray,
  11715. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  11716. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  11717. customAttributes = geometryGroup.__webglCustomAttributesList,
  11718. customAttribute,
  11719. faceArray = geometryGroup.__faceArray,
  11720. lineArray = geometryGroup.__lineArray,
  11721. geometry = object.geometry, // this is shared for all chunks
  11722. dirtyVertices = geometry.verticesNeedUpdate,
  11723. dirtyElements = geometry.elementsNeedUpdate,
  11724. dirtyUvs = geometry.uvsNeedUpdate,
  11725. dirtyNormals = geometry.normalsNeedUpdate,
  11726. dirtyTangents = geometry.tangentsNeedUpdate,
  11727. dirtyColors = geometry.colorsNeedUpdate,
  11728. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  11729. vertices = geometry.vertices,
  11730. chunk_faces3 = geometryGroup.faces3,
  11731. chunk_faces4 = geometryGroup.faces4,
  11732. obj_faces = geometry.faces,
  11733. obj_uvs = geometry.faceVertexUvs[ 0 ],
  11734. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  11735. obj_colors = geometry.colors,
  11736. obj_skinIndices = geometry.skinIndices,
  11737. obj_skinWeights = geometry.skinWeights,
  11738. morphTargets = geometry.morphTargets,
  11739. morphNormals = geometry.morphNormals;
  11740. if ( dirtyVertices ) {
  11741. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11742. face = obj_faces[ chunk_faces3[ f ] ];
  11743. v1 = vertices[ face.a ];
  11744. v2 = vertices[ face.b ];
  11745. v3 = vertices[ face.c ];
  11746. vertexArray[ offset ] = v1.x;
  11747. vertexArray[ offset + 1 ] = v1.y;
  11748. vertexArray[ offset + 2 ] = v1.z;
  11749. vertexArray[ offset + 3 ] = v2.x;
  11750. vertexArray[ offset + 4 ] = v2.y;
  11751. vertexArray[ offset + 5 ] = v2.z;
  11752. vertexArray[ offset + 6 ] = v3.x;
  11753. vertexArray[ offset + 7 ] = v3.y;
  11754. vertexArray[ offset + 8 ] = v3.z;
  11755. offset += 9;
  11756. }
  11757. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11758. face = obj_faces[ chunk_faces4[ f ] ];
  11759. v1 = vertices[ face.a ];
  11760. v2 = vertices[ face.b ];
  11761. v3 = vertices[ face.c ];
  11762. v4 = vertices[ face.d ];
  11763. vertexArray[ offset ] = v1.x;
  11764. vertexArray[ offset + 1 ] = v1.y;
  11765. vertexArray[ offset + 2 ] = v1.z;
  11766. vertexArray[ offset + 3 ] = v2.x;
  11767. vertexArray[ offset + 4 ] = v2.y;
  11768. vertexArray[ offset + 5 ] = v2.z;
  11769. vertexArray[ offset + 6 ] = v3.x;
  11770. vertexArray[ offset + 7 ] = v3.y;
  11771. vertexArray[ offset + 8 ] = v3.z;
  11772. vertexArray[ offset + 9 ] = v4.x;
  11773. vertexArray[ offset + 10 ] = v4.y;
  11774. vertexArray[ offset + 11 ] = v4.z;
  11775. offset += 12;
  11776. }
  11777. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11778. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11779. }
  11780. if ( dirtyMorphTargets ) {
  11781. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  11782. offset_morphTarget = 0;
  11783. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11784. chf = chunk_faces3[ f ];
  11785. face = obj_faces[ chf ];
  11786. // morph positions
  11787. v1 = morphTargets[ vk ].vertices[ face.a ];
  11788. v2 = morphTargets[ vk ].vertices[ face.b ];
  11789. v3 = morphTargets[ vk ].vertices[ face.c ];
  11790. vka = morphTargetsArrays[ vk ];
  11791. vka[ offset_morphTarget ] = v1.x;
  11792. vka[ offset_morphTarget + 1 ] = v1.y;
  11793. vka[ offset_morphTarget + 2 ] = v1.z;
  11794. vka[ offset_morphTarget + 3 ] = v2.x;
  11795. vka[ offset_morphTarget + 4 ] = v2.y;
  11796. vka[ offset_morphTarget + 5 ] = v2.z;
  11797. vka[ offset_morphTarget + 6 ] = v3.x;
  11798. vka[ offset_morphTarget + 7 ] = v3.y;
  11799. vka[ offset_morphTarget + 8 ] = v3.z;
  11800. // morph normals
  11801. if ( material.morphNormals ) {
  11802. if ( needsSmoothNormals ) {
  11803. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  11804. n1 = faceVertexNormals.a;
  11805. n2 = faceVertexNormals.b;
  11806. n3 = faceVertexNormals.c;
  11807. } else {
  11808. n1 = morphNormals[ vk ].faceNormals[ chf ];
  11809. n2 = n1;
  11810. n3 = n1;
  11811. }
  11812. nka = morphNormalsArrays[ vk ];
  11813. nka[ offset_morphTarget ] = n1.x;
  11814. nka[ offset_morphTarget + 1 ] = n1.y;
  11815. nka[ offset_morphTarget + 2 ] = n1.z;
  11816. nka[ offset_morphTarget + 3 ] = n2.x;
  11817. nka[ offset_morphTarget + 4 ] = n2.y;
  11818. nka[ offset_morphTarget + 5 ] = n2.z;
  11819. nka[ offset_morphTarget + 6 ] = n3.x;
  11820. nka[ offset_morphTarget + 7 ] = n3.y;
  11821. nka[ offset_morphTarget + 8 ] = n3.z;
  11822. }
  11823. //
  11824. offset_morphTarget += 9;
  11825. }
  11826. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11827. chf = chunk_faces4[ f ];
  11828. face = obj_faces[ chf ];
  11829. // morph positions
  11830. v1 = morphTargets[ vk ].vertices[ face.a ];
  11831. v2 = morphTargets[ vk ].vertices[ face.b ];
  11832. v3 = morphTargets[ vk ].vertices[ face.c ];
  11833. v4 = morphTargets[ vk ].vertices[ face.d ];
  11834. vka = morphTargetsArrays[ vk ];
  11835. vka[ offset_morphTarget ] = v1.x;
  11836. vka[ offset_morphTarget + 1 ] = v1.y;
  11837. vka[ offset_morphTarget + 2 ] = v1.z;
  11838. vka[ offset_morphTarget + 3 ] = v2.x;
  11839. vka[ offset_morphTarget + 4 ] = v2.y;
  11840. vka[ offset_morphTarget + 5 ] = v2.z;
  11841. vka[ offset_morphTarget + 6 ] = v3.x;
  11842. vka[ offset_morphTarget + 7 ] = v3.y;
  11843. vka[ offset_morphTarget + 8 ] = v3.z;
  11844. vka[ offset_morphTarget + 9 ] = v4.x;
  11845. vka[ offset_morphTarget + 10 ] = v4.y;
  11846. vka[ offset_morphTarget + 11 ] = v4.z;
  11847. // morph normals
  11848. if ( material.morphNormals ) {
  11849. if ( needsSmoothNormals ) {
  11850. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  11851. n1 = faceVertexNormals.a;
  11852. n2 = faceVertexNormals.b;
  11853. n3 = faceVertexNormals.c;
  11854. n4 = faceVertexNormals.d;
  11855. } else {
  11856. n1 = morphNormals[ vk ].faceNormals[ chf ];
  11857. n2 = n1;
  11858. n3 = n1;
  11859. n4 = n1;
  11860. }
  11861. nka = morphNormalsArrays[ vk ];
  11862. nka[ offset_morphTarget ] = n1.x;
  11863. nka[ offset_morphTarget + 1 ] = n1.y;
  11864. nka[ offset_morphTarget + 2 ] = n1.z;
  11865. nka[ offset_morphTarget + 3 ] = n2.x;
  11866. nka[ offset_morphTarget + 4 ] = n2.y;
  11867. nka[ offset_morphTarget + 5 ] = n2.z;
  11868. nka[ offset_morphTarget + 6 ] = n3.x;
  11869. nka[ offset_morphTarget + 7 ] = n3.y;
  11870. nka[ offset_morphTarget + 8 ] = n3.z;
  11871. nka[ offset_morphTarget + 9 ] = n4.x;
  11872. nka[ offset_morphTarget + 10 ] = n4.y;
  11873. nka[ offset_morphTarget + 11 ] = n4.z;
  11874. }
  11875. //
  11876. offset_morphTarget += 12;
  11877. }
  11878. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  11879. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  11880. if ( material.morphNormals ) {
  11881. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  11882. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  11883. }
  11884. }
  11885. }
  11886. if ( obj_skinWeights.length ) {
  11887. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11888. face = obj_faces[ chunk_faces3[ f ] ];
  11889. // weights
  11890. sw1 = obj_skinWeights[ face.a ];
  11891. sw2 = obj_skinWeights[ face.b ];
  11892. sw3 = obj_skinWeights[ face.c ];
  11893. skinWeightArray[ offset_skin ] = sw1.x;
  11894. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  11895. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  11896. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  11897. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  11898. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  11899. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  11900. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  11901. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  11902. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  11903. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  11904. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  11905. // indices
  11906. si1 = obj_skinIndices[ face.a ];
  11907. si2 = obj_skinIndices[ face.b ];
  11908. si3 = obj_skinIndices[ face.c ];
  11909. skinIndexArray[ offset_skin ] = si1.x;
  11910. skinIndexArray[ offset_skin + 1 ] = si1.y;
  11911. skinIndexArray[ offset_skin + 2 ] = si1.z;
  11912. skinIndexArray[ offset_skin + 3 ] = si1.w;
  11913. skinIndexArray[ offset_skin + 4 ] = si2.x;
  11914. skinIndexArray[ offset_skin + 5 ] = si2.y;
  11915. skinIndexArray[ offset_skin + 6 ] = si2.z;
  11916. skinIndexArray[ offset_skin + 7 ] = si2.w;
  11917. skinIndexArray[ offset_skin + 8 ] = si3.x;
  11918. skinIndexArray[ offset_skin + 9 ] = si3.y;
  11919. skinIndexArray[ offset_skin + 10 ] = si3.z;
  11920. skinIndexArray[ offset_skin + 11 ] = si3.w;
  11921. offset_skin += 12;
  11922. }
  11923. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11924. face = obj_faces[ chunk_faces4[ f ] ];
  11925. // weights
  11926. sw1 = obj_skinWeights[ face.a ];
  11927. sw2 = obj_skinWeights[ face.b ];
  11928. sw3 = obj_skinWeights[ face.c ];
  11929. sw4 = obj_skinWeights[ face.d ];
  11930. skinWeightArray[ offset_skin ] = sw1.x;
  11931. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  11932. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  11933. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  11934. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  11935. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  11936. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  11937. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  11938. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  11939. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  11940. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  11941. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  11942. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  11943. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  11944. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  11945. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  11946. // indices
  11947. si1 = obj_skinIndices[ face.a ];
  11948. si2 = obj_skinIndices[ face.b ];
  11949. si3 = obj_skinIndices[ face.c ];
  11950. si4 = obj_skinIndices[ face.d ];
  11951. skinIndexArray[ offset_skin ] = si1.x;
  11952. skinIndexArray[ offset_skin + 1 ] = si1.y;
  11953. skinIndexArray[ offset_skin + 2 ] = si1.z;
  11954. skinIndexArray[ offset_skin + 3 ] = si1.w;
  11955. skinIndexArray[ offset_skin + 4 ] = si2.x;
  11956. skinIndexArray[ offset_skin + 5 ] = si2.y;
  11957. skinIndexArray[ offset_skin + 6 ] = si2.z;
  11958. skinIndexArray[ offset_skin + 7 ] = si2.w;
  11959. skinIndexArray[ offset_skin + 8 ] = si3.x;
  11960. skinIndexArray[ offset_skin + 9 ] = si3.y;
  11961. skinIndexArray[ offset_skin + 10 ] = si3.z;
  11962. skinIndexArray[ offset_skin + 11 ] = si3.w;
  11963. skinIndexArray[ offset_skin + 12 ] = si4.x;
  11964. skinIndexArray[ offset_skin + 13 ] = si4.y;
  11965. skinIndexArray[ offset_skin + 14 ] = si4.z;
  11966. skinIndexArray[ offset_skin + 15 ] = si4.w;
  11967. offset_skin += 16;
  11968. }
  11969. if ( offset_skin > 0 ) {
  11970. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  11971. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  11972. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  11973. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  11974. }
  11975. }
  11976. if ( dirtyColors && vertexColorType ) {
  11977. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11978. face = obj_faces[ chunk_faces3[ f ] ];
  11979. vertexColors = face.vertexColors;
  11980. faceColor = face.color;
  11981. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  11982. c1 = vertexColors[ 0 ];
  11983. c2 = vertexColors[ 1 ];
  11984. c3 = vertexColors[ 2 ];
  11985. } else {
  11986. c1 = faceColor;
  11987. c2 = faceColor;
  11988. c3 = faceColor;
  11989. }
  11990. colorArray[ offset_color ] = c1.r;
  11991. colorArray[ offset_color + 1 ] = c1.g;
  11992. colorArray[ offset_color + 2 ] = c1.b;
  11993. colorArray[ offset_color + 3 ] = c2.r;
  11994. colorArray[ offset_color + 4 ] = c2.g;
  11995. colorArray[ offset_color + 5 ] = c2.b;
  11996. colorArray[ offset_color + 6 ] = c3.r;
  11997. colorArray[ offset_color + 7 ] = c3.g;
  11998. colorArray[ offset_color + 8 ] = c3.b;
  11999. offset_color += 9;
  12000. }
  12001. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12002. face = obj_faces[ chunk_faces4[ f ] ];
  12003. vertexColors = face.vertexColors;
  12004. faceColor = face.color;
  12005. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  12006. c1 = vertexColors[ 0 ];
  12007. c2 = vertexColors[ 1 ];
  12008. c3 = vertexColors[ 2 ];
  12009. c4 = vertexColors[ 3 ];
  12010. } else {
  12011. c1 = faceColor;
  12012. c2 = faceColor;
  12013. c3 = faceColor;
  12014. c4 = faceColor;
  12015. }
  12016. colorArray[ offset_color ] = c1.r;
  12017. colorArray[ offset_color + 1 ] = c1.g;
  12018. colorArray[ offset_color + 2 ] = c1.b;
  12019. colorArray[ offset_color + 3 ] = c2.r;
  12020. colorArray[ offset_color + 4 ] = c2.g;
  12021. colorArray[ offset_color + 5 ] = c2.b;
  12022. colorArray[ offset_color + 6 ] = c3.r;
  12023. colorArray[ offset_color + 7 ] = c3.g;
  12024. colorArray[ offset_color + 8 ] = c3.b;
  12025. colorArray[ offset_color + 9 ] = c4.r;
  12026. colorArray[ offset_color + 10 ] = c4.g;
  12027. colorArray[ offset_color + 11 ] = c4.b;
  12028. offset_color += 12;
  12029. }
  12030. if ( offset_color > 0 ) {
  12031. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12032. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12033. }
  12034. }
  12035. if ( dirtyTangents && geometry.hasTangents ) {
  12036. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12037. face = obj_faces[ chunk_faces3[ f ] ];
  12038. vertexTangents = face.vertexTangents;
  12039. t1 = vertexTangents[ 0 ];
  12040. t2 = vertexTangents[ 1 ];
  12041. t3 = vertexTangents[ 2 ];
  12042. tangentArray[ offset_tangent ] = t1.x;
  12043. tangentArray[ offset_tangent + 1 ] = t1.y;
  12044. tangentArray[ offset_tangent + 2 ] = t1.z;
  12045. tangentArray[ offset_tangent + 3 ] = t1.w;
  12046. tangentArray[ offset_tangent + 4 ] = t2.x;
  12047. tangentArray[ offset_tangent + 5 ] = t2.y;
  12048. tangentArray[ offset_tangent + 6 ] = t2.z;
  12049. tangentArray[ offset_tangent + 7 ] = t2.w;
  12050. tangentArray[ offset_tangent + 8 ] = t3.x;
  12051. tangentArray[ offset_tangent + 9 ] = t3.y;
  12052. tangentArray[ offset_tangent + 10 ] = t3.z;
  12053. tangentArray[ offset_tangent + 11 ] = t3.w;
  12054. offset_tangent += 12;
  12055. }
  12056. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12057. face = obj_faces[ chunk_faces4[ f ] ];
  12058. vertexTangents = face.vertexTangents;
  12059. t1 = vertexTangents[ 0 ];
  12060. t2 = vertexTangents[ 1 ];
  12061. t3 = vertexTangents[ 2 ];
  12062. t4 = vertexTangents[ 3 ];
  12063. tangentArray[ offset_tangent ] = t1.x;
  12064. tangentArray[ offset_tangent + 1 ] = t1.y;
  12065. tangentArray[ offset_tangent + 2 ] = t1.z;
  12066. tangentArray[ offset_tangent + 3 ] = t1.w;
  12067. tangentArray[ offset_tangent + 4 ] = t2.x;
  12068. tangentArray[ offset_tangent + 5 ] = t2.y;
  12069. tangentArray[ offset_tangent + 6 ] = t2.z;
  12070. tangentArray[ offset_tangent + 7 ] = t2.w;
  12071. tangentArray[ offset_tangent + 8 ] = t3.x;
  12072. tangentArray[ offset_tangent + 9 ] = t3.y;
  12073. tangentArray[ offset_tangent + 10 ] = t3.z;
  12074. tangentArray[ offset_tangent + 11 ] = t3.w;
  12075. tangentArray[ offset_tangent + 12 ] = t4.x;
  12076. tangentArray[ offset_tangent + 13 ] = t4.y;
  12077. tangentArray[ offset_tangent + 14 ] = t4.z;
  12078. tangentArray[ offset_tangent + 15 ] = t4.w;
  12079. offset_tangent += 16;
  12080. }
  12081. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12082. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  12083. }
  12084. if ( dirtyNormals && normalType ) {
  12085. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12086. face = obj_faces[ chunk_faces3[ f ] ];
  12087. vertexNormals = face.vertexNormals;
  12088. faceNormal = face.normal;
  12089. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  12090. for ( i = 0; i < 3; i ++ ) {
  12091. vn = vertexNormals[ i ];
  12092. normalArray[ offset_normal ] = vn.x;
  12093. normalArray[ offset_normal + 1 ] = vn.y;
  12094. normalArray[ offset_normal + 2 ] = vn.z;
  12095. offset_normal += 3;
  12096. }
  12097. } else {
  12098. for ( i = 0; i < 3; i ++ ) {
  12099. normalArray[ offset_normal ] = faceNormal.x;
  12100. normalArray[ offset_normal + 1 ] = faceNormal.y;
  12101. normalArray[ offset_normal + 2 ] = faceNormal.z;
  12102. offset_normal += 3;
  12103. }
  12104. }
  12105. }
  12106. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12107. face = obj_faces[ chunk_faces4[ f ] ];
  12108. vertexNormals = face.vertexNormals;
  12109. faceNormal = face.normal;
  12110. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  12111. for ( i = 0; i < 4; i ++ ) {
  12112. vn = vertexNormals[ i ];
  12113. normalArray[ offset_normal ] = vn.x;
  12114. normalArray[ offset_normal + 1 ] = vn.y;
  12115. normalArray[ offset_normal + 2 ] = vn.z;
  12116. offset_normal += 3;
  12117. }
  12118. } else {
  12119. for ( i = 0; i < 4; i ++ ) {
  12120. normalArray[ offset_normal ] = faceNormal.x;
  12121. normalArray[ offset_normal + 1 ] = faceNormal.y;
  12122. normalArray[ offset_normal + 2 ] = faceNormal.z;
  12123. offset_normal += 3;
  12124. }
  12125. }
  12126. }
  12127. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12128. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  12129. }
  12130. if ( dirtyUvs && obj_uvs && uvType ) {
  12131. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12132. fi = chunk_faces3[ f ];
  12133. uv = obj_uvs[ fi ];
  12134. if ( uv === undefined ) continue;
  12135. for ( i = 0; i < 3; i ++ ) {
  12136. uvi = uv[ i ];
  12137. uvArray[ offset_uv ] = uvi.x;
  12138. uvArray[ offset_uv + 1 ] = uvi.y;
  12139. offset_uv += 2;
  12140. }
  12141. }
  12142. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12143. fi = chunk_faces4[ f ];
  12144. uv = obj_uvs[ fi ];
  12145. if ( uv === undefined ) continue;
  12146. for ( i = 0; i < 4; i ++ ) {
  12147. uvi = uv[ i ];
  12148. uvArray[ offset_uv ] = uvi.x;
  12149. uvArray[ offset_uv + 1 ] = uvi.y;
  12150. offset_uv += 2;
  12151. }
  12152. }
  12153. if ( offset_uv > 0 ) {
  12154. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12155. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  12156. }
  12157. }
  12158. if ( dirtyUvs && obj_uvs2 && uvType ) {
  12159. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12160. fi = chunk_faces3[ f ];
  12161. uv2 = obj_uvs2[ fi ];
  12162. if ( uv2 === undefined ) continue;
  12163. for ( i = 0; i < 3; i ++ ) {
  12164. uv2i = uv2[ i ];
  12165. uv2Array[ offset_uv2 ] = uv2i.x;
  12166. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  12167. offset_uv2 += 2;
  12168. }
  12169. }
  12170. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12171. fi = chunk_faces4[ f ];
  12172. uv2 = obj_uvs2[ fi ];
  12173. if ( uv2 === undefined ) continue;
  12174. for ( i = 0; i < 4; i ++ ) {
  12175. uv2i = uv2[ i ];
  12176. uv2Array[ offset_uv2 ] = uv2i.x;
  12177. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  12178. offset_uv2 += 2;
  12179. }
  12180. }
  12181. if ( offset_uv2 > 0 ) {
  12182. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12183. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  12184. }
  12185. }
  12186. if ( dirtyElements ) {
  12187. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12188. faceArray[ offset_face ] = vertexIndex;
  12189. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12190. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  12191. offset_face += 3;
  12192. lineArray[ offset_line ] = vertexIndex;
  12193. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  12194. lineArray[ offset_line + 2 ] = vertexIndex;
  12195. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  12196. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  12197. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  12198. offset_line += 6;
  12199. vertexIndex += 3;
  12200. }
  12201. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12202. faceArray[ offset_face ] = vertexIndex;
  12203. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12204. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  12205. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  12206. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  12207. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  12208. offset_face += 6;
  12209. lineArray[ offset_line ] = vertexIndex;
  12210. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  12211. lineArray[ offset_line + 2 ] = vertexIndex;
  12212. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  12213. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  12214. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  12215. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  12216. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  12217. offset_line += 8;
  12218. vertexIndex += 4;
  12219. }
  12220. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12221. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  12222. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  12223. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  12224. }
  12225. if ( customAttributes ) {
  12226. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12227. customAttribute = customAttributes[ i ];
  12228. if ( ! customAttribute.__original.needsUpdate ) continue;
  12229. offset_custom = 0;
  12230. offset_customSrc = 0;
  12231. if ( customAttribute.size === 1 ) {
  12232. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12233. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12234. face = obj_faces[ chunk_faces3[ f ] ];
  12235. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  12236. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  12237. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  12238. offset_custom += 3;
  12239. }
  12240. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12241. face = obj_faces[ chunk_faces4[ f ] ];
  12242. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  12243. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  12244. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  12245. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  12246. offset_custom += 4;
  12247. }
  12248. } else if ( customAttribute.boundTo === "faces" ) {
  12249. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12250. value = customAttribute.value[ chunk_faces3[ f ] ];
  12251. customAttribute.array[ offset_custom ] = value;
  12252. customAttribute.array[ offset_custom + 1 ] = value;
  12253. customAttribute.array[ offset_custom + 2 ] = value;
  12254. offset_custom += 3;
  12255. }
  12256. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12257. value = customAttribute.value[ chunk_faces4[ f ] ];
  12258. customAttribute.array[ offset_custom ] = value;
  12259. customAttribute.array[ offset_custom + 1 ] = value;
  12260. customAttribute.array[ offset_custom + 2 ] = value;
  12261. customAttribute.array[ offset_custom + 3 ] = value;
  12262. offset_custom += 4;
  12263. }
  12264. }
  12265. } else if ( customAttribute.size === 2 ) {
  12266. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12267. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12268. face = obj_faces[ chunk_faces3[ f ] ];
  12269. v1 = customAttribute.value[ face.a ];
  12270. v2 = customAttribute.value[ face.b ];
  12271. v3 = customAttribute.value[ face.c ];
  12272. customAttribute.array[ offset_custom ] = v1.x;
  12273. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12274. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12275. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12276. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12277. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12278. offset_custom += 6;
  12279. }
  12280. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12281. face = obj_faces[ chunk_faces4[ f ] ];
  12282. v1 = customAttribute.value[ face.a ];
  12283. v2 = customAttribute.value[ face.b ];
  12284. v3 = customAttribute.value[ face.c ];
  12285. v4 = customAttribute.value[ face.d ];
  12286. customAttribute.array[ offset_custom ] = v1.x;
  12287. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12288. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12289. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12290. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12291. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12292. customAttribute.array[ offset_custom + 6 ] = v4.x;
  12293. customAttribute.array[ offset_custom + 7 ] = v4.y;
  12294. offset_custom += 8;
  12295. }
  12296. } else if ( customAttribute.boundTo === "faces" ) {
  12297. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12298. value = customAttribute.value[ chunk_faces3[ f ] ];
  12299. v1 = value;
  12300. v2 = value;
  12301. v3 = value;
  12302. customAttribute.array[ offset_custom ] = v1.x;
  12303. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12304. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12305. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12306. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12307. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12308. offset_custom += 6;
  12309. }
  12310. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12311. value = customAttribute.value[ chunk_faces4[ f ] ];
  12312. v1 = value;
  12313. v2 = value;
  12314. v3 = value;
  12315. v4 = value;
  12316. customAttribute.array[ offset_custom ] = v1.x;
  12317. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12318. customAttribute.array[ offset_custom + 2 ] = v2.x;
  12319. customAttribute.array[ offset_custom + 3 ] = v2.y;
  12320. customAttribute.array[ offset_custom + 4 ] = v3.x;
  12321. customAttribute.array[ offset_custom + 5 ] = v3.y;
  12322. customAttribute.array[ offset_custom + 6 ] = v4.x;
  12323. customAttribute.array[ offset_custom + 7 ] = v4.y;
  12324. offset_custom += 8;
  12325. }
  12326. }
  12327. } else if ( customAttribute.size === 3 ) {
  12328. var pp;
  12329. if ( customAttribute.type === "c" ) {
  12330. pp = [ "r", "g", "b" ];
  12331. } else {
  12332. pp = [ "x", "y", "z" ];
  12333. }
  12334. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12335. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12336. face = obj_faces[ chunk_faces3[ f ] ];
  12337. v1 = customAttribute.value[ face.a ];
  12338. v2 = customAttribute.value[ face.b ];
  12339. v3 = customAttribute.value[ face.c ];
  12340. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12341. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12342. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12343. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12344. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12345. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12346. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12347. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12348. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12349. offset_custom += 9;
  12350. }
  12351. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12352. face = obj_faces[ chunk_faces4[ f ] ];
  12353. v1 = customAttribute.value[ face.a ];
  12354. v2 = customAttribute.value[ face.b ];
  12355. v3 = customAttribute.value[ face.c ];
  12356. v4 = customAttribute.value[ face.d ];
  12357. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12358. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12359. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12360. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12361. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12362. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12363. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12364. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12365. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12366. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  12367. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  12368. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  12369. offset_custom += 12;
  12370. }
  12371. } else if ( customAttribute.boundTo === "faces" ) {
  12372. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12373. value = customAttribute.value[ chunk_faces3[ f ] ];
  12374. v1 = value;
  12375. v2 = value;
  12376. v3 = value;
  12377. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12378. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12379. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12380. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12381. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12382. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12383. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12384. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12385. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12386. offset_custom += 9;
  12387. }
  12388. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12389. value = customAttribute.value[ chunk_faces4[ f ] ];
  12390. v1 = value;
  12391. v2 = value;
  12392. v3 = value;
  12393. v4 = value;
  12394. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12395. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12396. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12397. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12398. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12399. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12400. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12401. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12402. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12403. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  12404. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  12405. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  12406. offset_custom += 12;
  12407. }
  12408. } else if ( customAttribute.boundTo === "faceVertices" ) {
  12409. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12410. value = customAttribute.value[ chunk_faces3[ f ] ];
  12411. v1 = value[ 0 ];
  12412. v2 = value[ 1 ];
  12413. v3 = value[ 2 ];
  12414. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12415. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12416. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12417. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12418. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12419. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12420. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12421. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12422. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12423. offset_custom += 9;
  12424. }
  12425. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12426. value = customAttribute.value[ chunk_faces4[ f ] ];
  12427. v1 = value[ 0 ];
  12428. v2 = value[ 1 ];
  12429. v3 = value[ 2 ];
  12430. v4 = value[ 3 ];
  12431. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  12432. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  12433. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  12434. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  12435. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  12436. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  12437. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  12438. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  12439. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  12440. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  12441. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  12442. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  12443. offset_custom += 12;
  12444. }
  12445. }
  12446. } else if ( customAttribute.size === 4 ) {
  12447. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12448. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12449. face = obj_faces[ chunk_faces3[ f ] ];
  12450. v1 = customAttribute.value[ face.a ];
  12451. v2 = customAttribute.value[ face.b ];
  12452. v3 = customAttribute.value[ face.c ];
  12453. customAttribute.array[ offset_custom ] = v1.x;
  12454. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12455. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12456. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12457. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12458. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12459. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12460. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12461. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12462. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12463. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12464. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12465. offset_custom += 12;
  12466. }
  12467. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12468. face = obj_faces[ chunk_faces4[ f ] ];
  12469. v1 = customAttribute.value[ face.a ];
  12470. v2 = customAttribute.value[ face.b ];
  12471. v3 = customAttribute.value[ face.c ];
  12472. v4 = customAttribute.value[ face.d ];
  12473. customAttribute.array[ offset_custom ] = v1.x;
  12474. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12475. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12476. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12477. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12478. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12479. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12480. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12481. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12482. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12483. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12484. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12485. customAttribute.array[ offset_custom + 12 ] = v4.x;
  12486. customAttribute.array[ offset_custom + 13 ] = v4.y;
  12487. customAttribute.array[ offset_custom + 14 ] = v4.z;
  12488. customAttribute.array[ offset_custom + 15 ] = v4.w;
  12489. offset_custom += 16;
  12490. }
  12491. } else if ( customAttribute.boundTo === "faces" ) {
  12492. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12493. value = customAttribute.value[ chunk_faces3[ f ] ];
  12494. v1 = value;
  12495. v2 = value;
  12496. v3 = value;
  12497. customAttribute.array[ offset_custom ] = v1.x;
  12498. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12499. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12500. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12501. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12502. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12503. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12504. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12505. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12506. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12507. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12508. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12509. offset_custom += 12;
  12510. }
  12511. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12512. value = customAttribute.value[ chunk_faces4[ f ] ];
  12513. v1 = value;
  12514. v2 = value;
  12515. v3 = value;
  12516. v4 = value;
  12517. customAttribute.array[ offset_custom ] = v1.x;
  12518. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12519. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12520. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12521. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12522. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12523. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12524. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12525. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12526. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12527. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12528. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12529. customAttribute.array[ offset_custom + 12 ] = v4.x;
  12530. customAttribute.array[ offset_custom + 13 ] = v4.y;
  12531. customAttribute.array[ offset_custom + 14 ] = v4.z;
  12532. customAttribute.array[ offset_custom + 15 ] = v4.w;
  12533. offset_custom += 16;
  12534. }
  12535. } else if ( customAttribute.boundTo === "faceVertices" ) {
  12536. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12537. value = customAttribute.value[ chunk_faces3[ f ] ];
  12538. v1 = value[ 0 ];
  12539. v2 = value[ 1 ];
  12540. v3 = value[ 2 ];
  12541. customAttribute.array[ offset_custom ] = v1.x;
  12542. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12543. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12544. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12545. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12546. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12547. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12548. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12549. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12550. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12551. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12552. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12553. offset_custom += 12;
  12554. }
  12555. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12556. value = customAttribute.value[ chunk_faces4[ f ] ];
  12557. v1 = value[ 0 ];
  12558. v2 = value[ 1 ];
  12559. v3 = value[ 2 ];
  12560. v4 = value[ 3 ];
  12561. customAttribute.array[ offset_custom ] = v1.x;
  12562. customAttribute.array[ offset_custom + 1 ] = v1.y;
  12563. customAttribute.array[ offset_custom + 2 ] = v1.z;
  12564. customAttribute.array[ offset_custom + 3 ] = v1.w;
  12565. customAttribute.array[ offset_custom + 4 ] = v2.x;
  12566. customAttribute.array[ offset_custom + 5 ] = v2.y;
  12567. customAttribute.array[ offset_custom + 6 ] = v2.z;
  12568. customAttribute.array[ offset_custom + 7 ] = v2.w;
  12569. customAttribute.array[ offset_custom + 8 ] = v3.x;
  12570. customAttribute.array[ offset_custom + 9 ] = v3.y;
  12571. customAttribute.array[ offset_custom + 10 ] = v3.z;
  12572. customAttribute.array[ offset_custom + 11 ] = v3.w;
  12573. customAttribute.array[ offset_custom + 12 ] = v4.x;
  12574. customAttribute.array[ offset_custom + 13 ] = v4.y;
  12575. customAttribute.array[ offset_custom + 14 ] = v4.z;
  12576. customAttribute.array[ offset_custom + 15 ] = v4.w;
  12577. offset_custom += 16;
  12578. }
  12579. }
  12580. }
  12581. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12582. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12583. }
  12584. }
  12585. if ( dispose ) {
  12586. delete geometryGroup.__inittedArrays;
  12587. delete geometryGroup.__colorArray;
  12588. delete geometryGroup.__normalArray;
  12589. delete geometryGroup.__tangentArray;
  12590. delete geometryGroup.__uvArray;
  12591. delete geometryGroup.__uv2Array;
  12592. delete geometryGroup.__faceArray;
  12593. delete geometryGroup.__vertexArray;
  12594. delete geometryGroup.__lineArray;
  12595. delete geometryGroup.__skinIndexArray;
  12596. delete geometryGroup.__skinWeightArray;
  12597. }
  12598. };
  12599. function setDirectBuffers ( geometry, hint, dispose ) {
  12600. var attributes = geometry.attributes;
  12601. var index = attributes[ "index" ];
  12602. var position = attributes[ "position" ];
  12603. var normal = attributes[ "normal" ];
  12604. var uv = attributes[ "uv" ];
  12605. var color = attributes[ "color" ];
  12606. var tangent = attributes[ "tangent" ];
  12607. if ( geometry.elementsNeedUpdate && index !== undefined ) {
  12608. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12609. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, index.array, hint );
  12610. }
  12611. if ( geometry.verticesNeedUpdate && position !== undefined ) {
  12612. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12613. _gl.bufferData( _gl.ARRAY_BUFFER, position.array, hint );
  12614. }
  12615. if ( geometry.normalsNeedUpdate && normal !== undefined ) {
  12616. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  12617. _gl.bufferData( _gl.ARRAY_BUFFER, normal.array, hint );
  12618. }
  12619. if ( geometry.uvsNeedUpdate && uv !== undefined ) {
  12620. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  12621. _gl.bufferData( _gl.ARRAY_BUFFER, uv.array, hint );
  12622. }
  12623. if ( geometry.colorsNeedUpdate && color !== undefined ) {
  12624. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12625. _gl.bufferData( _gl.ARRAY_BUFFER, color.array, hint );
  12626. }
  12627. if ( geometry.tangentsNeedUpdate && tangent !== undefined ) {
  12628. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  12629. _gl.bufferData( _gl.ARRAY_BUFFER, tangent.array, hint );
  12630. }
  12631. if ( dispose ) {
  12632. for ( var i in geometry.attributes ) {
  12633. delete geometry.attributes[ i ].array;
  12634. }
  12635. }
  12636. };
  12637. // Buffer rendering
  12638. this.renderBufferImmediate = function ( object, program, material ) {
  12639. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  12640. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  12641. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  12642. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  12643. if ( object.hasPositions ) {
  12644. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  12645. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  12646. _gl.enableVertexAttribArray( program.attributes.position );
  12647. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12648. }
  12649. if ( object.hasNormals ) {
  12650. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  12651. if ( material.shading === THREE.FlatShading ) {
  12652. var nx, ny, nz,
  12653. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  12654. normalArray,
  12655. i, il = object.count * 3;
  12656. for( i = 0; i < il; i += 9 ) {
  12657. normalArray = object.normalArray;
  12658. nax = normalArray[ i ];
  12659. nay = normalArray[ i + 1 ];
  12660. naz = normalArray[ i + 2 ];
  12661. nbx = normalArray[ i + 3 ];
  12662. nby = normalArray[ i + 4 ];
  12663. nbz = normalArray[ i + 5 ];
  12664. ncx = normalArray[ i + 6 ];
  12665. ncy = normalArray[ i + 7 ];
  12666. ncz = normalArray[ i + 8 ];
  12667. nx = ( nax + nbx + ncx ) / 3;
  12668. ny = ( nay + nby + ncy ) / 3;
  12669. nz = ( naz + nbz + ncz ) / 3;
  12670. normalArray[ i ] = nx;
  12671. normalArray[ i + 1 ] = ny;
  12672. normalArray[ i + 2 ] = nz;
  12673. normalArray[ i + 3 ] = nx;
  12674. normalArray[ i + 4 ] = ny;
  12675. normalArray[ i + 5 ] = nz;
  12676. normalArray[ i + 6 ] = nx;
  12677. normalArray[ i + 7 ] = ny;
  12678. normalArray[ i + 8 ] = nz;
  12679. }
  12680. }
  12681. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  12682. _gl.enableVertexAttribArray( program.attributes.normal );
  12683. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12684. }
  12685. if ( object.hasUvs && material.map ) {
  12686. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  12687. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  12688. _gl.enableVertexAttribArray( program.attributes.uv );
  12689. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12690. }
  12691. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  12692. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  12693. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  12694. _gl.enableVertexAttribArray( program.attributes.color );
  12695. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12696. }
  12697. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  12698. object.count = 0;
  12699. };
  12700. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  12701. if ( material.visible === false ) return;
  12702. var program, attributes, linewidth, primitives, a, attribute;
  12703. program = setProgram( camera, lights, fog, material, object );
  12704. attributes = program.attributes;
  12705. var updateBuffers = false,
  12706. wireframeBit = material.wireframe ? 1 : 0,
  12707. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  12708. if ( geometryHash !== _currentGeometryGroupHash ) {
  12709. _currentGeometryGroupHash = geometryHash;
  12710. updateBuffers = true;
  12711. }
  12712. if ( updateBuffers ) {
  12713. disableAttributes();
  12714. }
  12715. // render mesh
  12716. if ( object instanceof THREE.Mesh ) {
  12717. var index = geometry.attributes[ "index" ];
  12718. // indexed triangles
  12719. if ( index ) {
  12720. var offsets = geometry.offsets;
  12721. // if there is more than 1 chunk
  12722. // must set attribute pointers to use new offsets for each chunk
  12723. // even if geometry and materials didn't change
  12724. if ( offsets.length > 1 ) updateBuffers = true;
  12725. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  12726. var startIndex = offsets[ i ].index;
  12727. if ( updateBuffers ) {
  12728. // vertices
  12729. var position = geometry.attributes[ "position" ];
  12730. var positionSize = position.itemSize;
  12731. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12732. enableAttribute( attributes.position );
  12733. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, startIndex * positionSize * 4 ); // 4 bytes per Float32
  12734. // normals
  12735. var normal = geometry.attributes[ "normal" ];
  12736. if ( attributes.normal >= 0 && normal ) {
  12737. var normalSize = normal.itemSize;
  12738. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  12739. enableAttribute( attributes.normal );
  12740. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, startIndex * normalSize * 4 );
  12741. }
  12742. // uvs
  12743. var uv = geometry.attributes[ "uv" ];
  12744. if ( attributes.uv >= 0 && uv ) {
  12745. var uvSize = uv.itemSize;
  12746. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  12747. enableAttribute( attributes.uv );
  12748. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, startIndex * uvSize * 4 );
  12749. }
  12750. // colors
  12751. var color = geometry.attributes[ "color" ];
  12752. if ( attributes.color >= 0 && color ) {
  12753. var colorSize = color.itemSize;
  12754. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12755. enableAttribute( attributes.color );
  12756. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, startIndex * colorSize * 4 );
  12757. }
  12758. // tangents
  12759. var tangent = geometry.attributes[ "tangent" ];
  12760. if ( attributes.tangent >= 0 && tangent ) {
  12761. var tangentSize = tangent.itemSize;
  12762. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  12763. enableAttribute( attributes.tangent );
  12764. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, startIndex * tangentSize * 4 );
  12765. }
  12766. // indices
  12767. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12768. }
  12769. // render indexed triangles
  12770. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  12771. _this.info.render.calls ++;
  12772. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  12773. _this.info.render.faces += offsets[ i ].count / 3;
  12774. }
  12775. // non-indexed triangles
  12776. } else {
  12777. if ( updateBuffers ) {
  12778. // vertices
  12779. var position = geometry.attributes[ "position" ];
  12780. var positionSize = position.itemSize;
  12781. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12782. enableAttribute( attributes.position );
  12783. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  12784. // normals
  12785. var normal = geometry.attributes[ "normal" ];
  12786. if ( attributes.normal >= 0 && normal ) {
  12787. var normalSize = normal.itemSize;
  12788. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  12789. enableAttribute( attributes.normal );
  12790. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, 0 );
  12791. }
  12792. // uvs
  12793. var uv = geometry.attributes[ "uv" ];
  12794. if ( attributes.uv >= 0 && uv ) {
  12795. var uvSize = uv.itemSize;
  12796. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  12797. enableAttribute( attributes.uv );
  12798. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, 0 );
  12799. }
  12800. // colors
  12801. var color = geometry.attributes[ "color" ];
  12802. if ( attributes.color >= 0 && color ) {
  12803. var colorSize = color.itemSize;
  12804. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12805. enableAttribute( attributes.color );
  12806. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  12807. }
  12808. // tangents
  12809. var tangent = geometry.attributes[ "tangent" ];
  12810. if ( attributes.tangent >= 0 && tangent ) {
  12811. var tangentSize = tangent.itemSize;
  12812. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  12813. enableAttribute( attributes.tangent );
  12814. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, 0 );
  12815. }
  12816. }
  12817. // render non-indexed triangles
  12818. _gl.drawArrays( _gl.TRIANGLES, 0, position.numItems / 3 );
  12819. _this.info.render.calls ++;
  12820. _this.info.render.vertices += position.numItems / 3;
  12821. _this.info.render.faces += position.numItems / 3 / 3;
  12822. }
  12823. // render particles
  12824. } else if ( object instanceof THREE.ParticleSystem ) {
  12825. if ( updateBuffers ) {
  12826. // vertices
  12827. var position = geometry.attributes[ "position" ];
  12828. var positionSize = position.itemSize;
  12829. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12830. enableAttribute( attributes.position );
  12831. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  12832. // colors
  12833. var color = geometry.attributes[ "color" ];
  12834. if ( attributes.color >= 0 && color ) {
  12835. var colorSize = color.itemSize;
  12836. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12837. enableAttribute( attributes.color );
  12838. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  12839. }
  12840. // render particles
  12841. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  12842. _this.info.render.calls ++;
  12843. _this.info.render.points += position.numItems / 3;
  12844. }
  12845. } else if ( object instanceof THREE.Line ) {
  12846. if ( updateBuffers ) {
  12847. // vertices
  12848. var position = geometry.attributes[ "position" ];
  12849. var positionSize = position.itemSize;
  12850. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12851. enableAttribute( attributes.position );
  12852. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  12853. // colors
  12854. var color = geometry.attributes[ "color" ];
  12855. if ( attributes.color >= 0 && color ) {
  12856. var colorSize = color.itemSize;
  12857. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12858. enableAttribute( attributes.color );
  12859. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  12860. }
  12861. // render lines
  12862. _gl.drawArrays( _gl.LINE_STRIP, 0, position.numItems / 3 );
  12863. _this.info.render.calls ++;
  12864. _this.info.render.points += position.numItems;
  12865. }
  12866. }
  12867. };
  12868. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  12869. if ( material.visible === false ) return;
  12870. var program, attributes, linewidth, primitives, a, attribute, i, il;
  12871. program = setProgram( camera, lights, fog, material, object );
  12872. attributes = program.attributes;
  12873. var updateBuffers = false,
  12874. wireframeBit = material.wireframe ? 1 : 0,
  12875. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  12876. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  12877. _currentGeometryGroupHash = geometryGroupHash;
  12878. updateBuffers = true;
  12879. }
  12880. if ( updateBuffers ) {
  12881. disableAttributes();
  12882. }
  12883. // vertices
  12884. if ( !material.morphTargets && attributes.position >= 0 ) {
  12885. if ( updateBuffers ) {
  12886. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12887. enableAttribute( attributes.position );
  12888. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12889. }
  12890. } else {
  12891. if ( object.morphTargetBase ) {
  12892. setupMorphTargets( material, geometryGroup, object );
  12893. }
  12894. }
  12895. if ( updateBuffers ) {
  12896. // custom attributes
  12897. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  12898. if ( geometryGroup.__webglCustomAttributesList ) {
  12899. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  12900. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  12901. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  12902. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  12903. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  12904. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  12905. }
  12906. }
  12907. }
  12908. // colors
  12909. if ( attributes.color >= 0 ) {
  12910. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12911. enableAttribute( attributes.color );
  12912. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12913. }
  12914. // normals
  12915. if ( attributes.normal >= 0 ) {
  12916. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12917. enableAttribute( attributes.normal );
  12918. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12919. }
  12920. // tangents
  12921. if ( attributes.tangent >= 0 ) {
  12922. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12923. enableAttribute( attributes.tangent );
  12924. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  12925. }
  12926. // uvs
  12927. if ( attributes.uv >= 0 ) {
  12928. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12929. enableAttribute( attributes.uv );
  12930. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12931. }
  12932. if ( attributes.uv2 >= 0 ) {
  12933. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12934. enableAttribute( attributes.uv2 );
  12935. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  12936. }
  12937. if ( material.skinning &&
  12938. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  12939. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  12940. enableAttribute( attributes.skinIndex );
  12941. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  12942. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  12943. enableAttribute( attributes.skinWeight );
  12944. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  12945. }
  12946. // line distances
  12947. if ( attributes.lineDistance >= 0 ) {
  12948. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  12949. enableAttribute( attributes.lineDistance );
  12950. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  12951. }
  12952. }
  12953. // render mesh
  12954. if ( object instanceof THREE.Mesh ) {
  12955. // wireframe
  12956. if ( material.wireframe ) {
  12957. setLineWidth( material.wireframeLinewidth );
  12958. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  12959. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  12960. // triangles
  12961. } else {
  12962. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12963. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  12964. }
  12965. _this.info.render.calls ++;
  12966. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  12967. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  12968. // render lines
  12969. } else if ( object instanceof THREE.Line ) {
  12970. primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  12971. setLineWidth( material.linewidth );
  12972. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  12973. _this.info.render.calls ++;
  12974. // render particles
  12975. } else if ( object instanceof THREE.ParticleSystem ) {
  12976. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  12977. _this.info.render.calls ++;
  12978. _this.info.render.points += geometryGroup.__webglParticleCount;
  12979. // render ribbon
  12980. } else if ( object instanceof THREE.Ribbon ) {
  12981. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  12982. _this.info.render.calls ++;
  12983. }
  12984. };
  12985. function enableAttribute( attribute ) {
  12986. if ( ! _enabledAttributes[ attribute ] ) {
  12987. _gl.enableVertexAttribArray( attribute );
  12988. _enabledAttributes[ attribute ] = true;
  12989. }
  12990. };
  12991. function disableAttributes() {
  12992. for ( var attribute in _enabledAttributes ) {
  12993. if ( _enabledAttributes[ attribute ] ) {
  12994. _gl.disableVertexAttribArray( attribute );
  12995. _enabledAttributes[ attribute ] = false;
  12996. }
  12997. }
  12998. };
  12999. function setupMorphTargets ( material, geometryGroup, object ) {
  13000. // set base
  13001. var attributes = material.program.attributes;
  13002. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  13003. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  13004. enableAttribute( attributes.position );
  13005. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13006. } else if ( attributes.position >= 0 ) {
  13007. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13008. enableAttribute( attributes.position );
  13009. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13010. }
  13011. if ( object.morphTargetForcedOrder.length ) {
  13012. // set forced order
  13013. var m = 0;
  13014. var order = object.morphTargetForcedOrder;
  13015. var influences = object.morphTargetInfluences;
  13016. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  13017. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13018. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  13019. enableAttribute( attributes[ "morphTarget" + m ] );
  13020. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13021. }
  13022. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13023. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  13024. enableAttribute( attributes[ "morphNormal" + m ] );
  13025. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13026. }
  13027. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  13028. m ++;
  13029. }
  13030. } else {
  13031. // find the most influencing
  13032. var influence, activeInfluenceIndices = [];
  13033. var influences = object.morphTargetInfluences;
  13034. var i, il = influences.length;
  13035. for ( i = 0; i < il; i ++ ) {
  13036. influence = influences[ i ];
  13037. if ( influence > 0 ) {
  13038. activeInfluenceIndices.push( [ influence, i ] );
  13039. }
  13040. }
  13041. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  13042. activeInfluenceIndices.sort( numericalSort );
  13043. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  13044. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  13045. activeInfluenceIndices.sort( numericalSort );
  13046. } else if ( activeInfluenceIndices.length === 0 ) {
  13047. activeInfluenceIndices.push( [ 0, 0 ] );
  13048. };
  13049. var influenceIndex, m = 0;
  13050. while ( m < material.numSupportedMorphTargets ) {
  13051. if ( activeInfluenceIndices[ m ] ) {
  13052. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  13053. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13054. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  13055. enableAttribute( attributes[ "morphTarget" + m ] );
  13056. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13057. }
  13058. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13059. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  13060. enableAttribute( attributes[ "morphNormal" + m ] );
  13061. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13062. }
  13063. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  13064. } else {
  13065. /*
  13066. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13067. if ( material.morphNormals ) {
  13068. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13069. }
  13070. */
  13071. object.__webglMorphTargetInfluences[ m ] = 0;
  13072. }
  13073. m ++;
  13074. }
  13075. }
  13076. // load updated influences uniform
  13077. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  13078. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  13079. }
  13080. };
  13081. // Sorting
  13082. function painterSortStable ( a, b ) {
  13083. if ( a.z !== b.z ) {
  13084. return b.z - a.z;
  13085. } else {
  13086. return b.id - a.id;
  13087. }
  13088. };
  13089. function numericalSort ( a, b ) {
  13090. return b[ 0 ] - a[ 0 ];
  13091. };
  13092. // Rendering
  13093. this.render = function ( scene, camera, renderTarget, forceClear ) {
  13094. if ( camera instanceof THREE.Camera === false ) {
  13095. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  13096. return;
  13097. }
  13098. var i, il,
  13099. webglObject, object,
  13100. renderList,
  13101. lights = scene.__lights,
  13102. fog = scene.fog;
  13103. // reset caching for this frame
  13104. _currentMaterialId = -1;
  13105. _lightsNeedUpdate = true;
  13106. // update scene graph
  13107. if ( this.autoUpdateScene ) scene.updateMatrixWorld();
  13108. // update camera matrices and frustum
  13109. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  13110. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  13111. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  13112. _frustum.setFromMatrix( _projScreenMatrix );
  13113. // update WebGL objects
  13114. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  13115. // custom render plugins (pre pass)
  13116. renderPlugins( this.renderPluginsPre, scene, camera );
  13117. //
  13118. _this.info.render.calls = 0;
  13119. _this.info.render.vertices = 0;
  13120. _this.info.render.faces = 0;
  13121. _this.info.render.points = 0;
  13122. this.setRenderTarget( renderTarget );
  13123. if ( this.autoClear || forceClear ) {
  13124. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  13125. }
  13126. // set matrices for regular objects (frustum culled)
  13127. renderList = scene.__webglObjects;
  13128. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13129. webglObject = renderList[ i ];
  13130. object = webglObject.object;
  13131. webglObject.render = false;
  13132. if ( object.visible ) {
  13133. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  13134. setupMatrices( object, camera );
  13135. unrollBufferMaterial( webglObject );
  13136. webglObject.render = true;
  13137. if ( this.sortObjects === true ) {
  13138. if ( object.renderDepth !== null ) {
  13139. webglObject.z = object.renderDepth;
  13140. } else {
  13141. _vector3.copy( object.matrixWorld.getPosition() );
  13142. _vector3.applyProjection( _projScreenMatrix );
  13143. webglObject.z = _vector3.z;
  13144. }
  13145. webglObject.id = object.id;
  13146. }
  13147. }
  13148. }
  13149. }
  13150. if ( this.sortObjects ) {
  13151. renderList.sort( painterSortStable );
  13152. }
  13153. // set matrices for immediate objects
  13154. renderList = scene.__webglObjectsImmediate;
  13155. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13156. webglObject = renderList[ i ];
  13157. object = webglObject.object;
  13158. if ( object.visible ) {
  13159. setupMatrices( object, camera );
  13160. unrollImmediateBufferMaterial( webglObject );
  13161. }
  13162. }
  13163. if ( scene.overrideMaterial ) {
  13164. var material = scene.overrideMaterial;
  13165. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13166. this.setDepthTest( material.depthTest );
  13167. this.setDepthWrite( material.depthWrite );
  13168. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13169. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  13170. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  13171. } else {
  13172. var material = null;
  13173. // opaque pass (front-to-back order)
  13174. this.setBlending( THREE.NoBlending );
  13175. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  13176. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  13177. // transparent pass (back-to-front order)
  13178. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  13179. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  13180. }
  13181. // custom render plugins (post pass)
  13182. renderPlugins( this.renderPluginsPost, scene, camera );
  13183. // Generate mipmap if we're using any kind of mipmap filtering
  13184. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  13185. updateRenderTargetMipmap( renderTarget );
  13186. }
  13187. // Ensure depth buffer writing is enabled so it can be cleared on next render
  13188. this.setDepthTest( true );
  13189. this.setDepthWrite( true );
  13190. // _gl.finish();
  13191. };
  13192. function renderPlugins( plugins, scene, camera ) {
  13193. if ( ! plugins.length ) return;
  13194. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  13195. // reset state for plugin (to start from clean slate)
  13196. _currentProgram = null;
  13197. _currentCamera = null;
  13198. _oldBlending = -1;
  13199. _oldDepthTest = -1;
  13200. _oldDepthWrite = -1;
  13201. _oldDoubleSided = -1;
  13202. _oldFlipSided = -1;
  13203. _currentGeometryGroupHash = -1;
  13204. _currentMaterialId = -1;
  13205. _lightsNeedUpdate = true;
  13206. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  13207. // reset state after plugin (anything could have changed)
  13208. _currentProgram = null;
  13209. _currentCamera = null;
  13210. _oldBlending = -1;
  13211. _oldDepthTest = -1;
  13212. _oldDepthWrite = -1;
  13213. _oldDoubleSided = -1;
  13214. _oldFlipSided = -1;
  13215. _currentGeometryGroupHash = -1;
  13216. _currentMaterialId = -1;
  13217. _lightsNeedUpdate = true;
  13218. }
  13219. };
  13220. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13221. var webglObject, object, buffer, material, start, end, delta;
  13222. if ( reverse ) {
  13223. start = renderList.length - 1;
  13224. end = -1;
  13225. delta = -1;
  13226. } else {
  13227. start = 0;
  13228. end = renderList.length;
  13229. delta = 1;
  13230. }
  13231. for ( var i = start; i !== end; i += delta ) {
  13232. webglObject = renderList[ i ];
  13233. if ( webglObject.render ) {
  13234. object = webglObject.object;
  13235. buffer = webglObject.buffer;
  13236. if ( overrideMaterial ) {
  13237. material = overrideMaterial;
  13238. } else {
  13239. material = webglObject[ materialType ];
  13240. if ( ! material ) continue;
  13241. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13242. _this.setDepthTest( material.depthTest );
  13243. _this.setDepthWrite( material.depthWrite );
  13244. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13245. }
  13246. _this.setMaterialFaces( material );
  13247. if ( buffer instanceof THREE.BufferGeometry ) {
  13248. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  13249. } else {
  13250. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  13251. }
  13252. }
  13253. }
  13254. };
  13255. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13256. var webglObject, object, material, program;
  13257. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  13258. webglObject = renderList[ i ];
  13259. object = webglObject.object;
  13260. if ( object.visible ) {
  13261. if ( overrideMaterial ) {
  13262. material = overrideMaterial;
  13263. } else {
  13264. material = webglObject[ materialType ];
  13265. if ( ! material ) continue;
  13266. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13267. _this.setDepthTest( material.depthTest );
  13268. _this.setDepthWrite( material.depthWrite );
  13269. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13270. }
  13271. _this.renderImmediateObject( camera, lights, fog, material, object );
  13272. }
  13273. }
  13274. };
  13275. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  13276. var program = setProgram( camera, lights, fog, material, object );
  13277. _currentGeometryGroupHash = -1;
  13278. _this.setMaterialFaces( material );
  13279. if ( object.immediateRenderCallback ) {
  13280. object.immediateRenderCallback( program, _gl, _frustum );
  13281. } else {
  13282. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  13283. }
  13284. };
  13285. function unrollImmediateBufferMaterial ( globject ) {
  13286. var object = globject.object,
  13287. material = object.material;
  13288. if ( material.transparent ) {
  13289. globject.transparent = material;
  13290. globject.opaque = null;
  13291. } else {
  13292. globject.opaque = material;
  13293. globject.transparent = null;
  13294. }
  13295. };
  13296. function unrollBufferMaterial ( globject ) {
  13297. var object = globject.object,
  13298. buffer = globject.buffer,
  13299. material, materialIndex, meshMaterial;
  13300. meshMaterial = object.material;
  13301. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  13302. materialIndex = buffer.materialIndex;
  13303. material = meshMaterial.materials[ materialIndex ];
  13304. if ( material.transparent ) {
  13305. globject.transparent = material;
  13306. globject.opaque = null;
  13307. } else {
  13308. globject.opaque = material;
  13309. globject.transparent = null;
  13310. }
  13311. } else {
  13312. material = meshMaterial;
  13313. if ( material ) {
  13314. if ( material.transparent ) {
  13315. globject.transparent = material;
  13316. globject.opaque = null;
  13317. } else {
  13318. globject.opaque = material;
  13319. globject.transparent = null;
  13320. }
  13321. }
  13322. }
  13323. };
  13324. // Geometry splitting
  13325. function sortFacesByMaterial ( geometry, material ) {
  13326. var f, fl, face, materialIndex, vertices,
  13327. groupHash, hash_map = {};
  13328. var numMorphTargets = geometry.morphTargets.length;
  13329. var numMorphNormals = geometry.morphNormals.length;
  13330. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  13331. geometry.geometryGroups = {};
  13332. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  13333. face = geometry.faces[ f ];
  13334. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  13335. if ( hash_map[ materialIndex ] === undefined ) {
  13336. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  13337. }
  13338. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13339. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13340. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13341. }
  13342. vertices = face instanceof THREE.Face3 ? 3 : 4;
  13343. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  13344. hash_map[ materialIndex ].counter += 1;
  13345. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13346. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13347. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13348. }
  13349. }
  13350. if ( face instanceof THREE.Face3 ) {
  13351. geometry.geometryGroups[ groupHash ].faces3.push( f );
  13352. } else {
  13353. geometry.geometryGroups[ groupHash ].faces4.push( f );
  13354. }
  13355. geometry.geometryGroups[ groupHash ].vertices += vertices;
  13356. }
  13357. geometry.geometryGroupsList = [];
  13358. for ( var g in geometry.geometryGroups ) {
  13359. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  13360. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  13361. }
  13362. };
  13363. // Objects refresh
  13364. this.initWebGLObjects = function ( scene ) {
  13365. if ( !scene.__webglObjects ) {
  13366. scene.__webglObjects = [];
  13367. scene.__webglObjectsImmediate = [];
  13368. scene.__webglSprites = [];
  13369. scene.__webglFlares = [];
  13370. }
  13371. while ( scene.__objectsAdded.length ) {
  13372. addObject( scene.__objectsAdded[ 0 ], scene );
  13373. scene.__objectsAdded.splice( 0, 1 );
  13374. }
  13375. while ( scene.__objectsRemoved.length ) {
  13376. removeObject( scene.__objectsRemoved[ 0 ], scene );
  13377. scene.__objectsRemoved.splice( 0, 1 );
  13378. }
  13379. // update must be called after objects adding / removal
  13380. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  13381. updateObject( scene.__webglObjects[ o ].object );
  13382. }
  13383. };
  13384. // Objects adding
  13385. function addObject ( object, scene ) {
  13386. var g, geometry, material, geometryGroup;
  13387. if ( ! object.__webglInit ) {
  13388. object.__webglInit = true;
  13389. object._modelViewMatrix = new THREE.Matrix4();
  13390. object._normalMatrix = new THREE.Matrix3();
  13391. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  13392. object.geometry.__webglInit = true;
  13393. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  13394. }
  13395. if ( object instanceof THREE.Mesh ) {
  13396. geometry = object.geometry;
  13397. material = object.material;
  13398. if ( geometry instanceof THREE.Geometry ) {
  13399. if ( geometry.geometryGroups === undefined ) {
  13400. sortFacesByMaterial( geometry, material );
  13401. }
  13402. // create separate VBOs per geometry chunk
  13403. for ( g in geometry.geometryGroups ) {
  13404. geometryGroup = geometry.geometryGroups[ g ];
  13405. // initialise VBO on the first access
  13406. if ( ! geometryGroup.__webglVertexBuffer ) {
  13407. createMeshBuffers( geometryGroup );
  13408. initMeshBuffers( geometryGroup, object );
  13409. geometry.verticesNeedUpdate = true;
  13410. geometry.morphTargetsNeedUpdate = true;
  13411. geometry.elementsNeedUpdate = true;
  13412. geometry.uvsNeedUpdate = true;
  13413. geometry.normalsNeedUpdate = true;
  13414. geometry.tangentsNeedUpdate = true;
  13415. geometry.colorsNeedUpdate = true;
  13416. }
  13417. }
  13418. } else if ( geometry instanceof THREE.BufferGeometry ) {
  13419. initDirectBuffers( geometry );
  13420. }
  13421. } else if ( object instanceof THREE.Ribbon ) {
  13422. geometry = object.geometry;
  13423. if ( ! geometry.__webglVertexBuffer ) {
  13424. createRibbonBuffers( geometry );
  13425. initRibbonBuffers( geometry, object );
  13426. geometry.verticesNeedUpdate = true;
  13427. geometry.colorsNeedUpdate = true;
  13428. geometry.normalsNeedUpdate = true;
  13429. }
  13430. } else if ( object instanceof THREE.Line ) {
  13431. geometry = object.geometry;
  13432. if ( ! geometry.__webglVertexBuffer ) {
  13433. if ( geometry instanceof THREE.Geometry ) {
  13434. createLineBuffers( geometry );
  13435. initLineBuffers( geometry, object );
  13436. geometry.verticesNeedUpdate = true;
  13437. geometry.colorsNeedUpdate = true;
  13438. geometry.lineDistancesNeedUpdate = true;
  13439. } else if ( geometry instanceof THREE.BufferGeometry ) {
  13440. initDirectBuffers( geometry );
  13441. }
  13442. }
  13443. } else if ( object instanceof THREE.ParticleSystem ) {
  13444. geometry = object.geometry;
  13445. if ( ! geometry.__webglVertexBuffer ) {
  13446. if ( geometry instanceof THREE.Geometry ) {
  13447. createParticleBuffers( geometry );
  13448. initParticleBuffers( geometry, object );
  13449. geometry.verticesNeedUpdate = true;
  13450. geometry.colorsNeedUpdate = true;
  13451. } else if ( geometry instanceof THREE.BufferGeometry ) {
  13452. initDirectBuffers( geometry );
  13453. }
  13454. }
  13455. }
  13456. }
  13457. if ( ! object.__webglActive ) {
  13458. if ( object instanceof THREE.Mesh ) {
  13459. geometry = object.geometry;
  13460. if ( geometry instanceof THREE.BufferGeometry ) {
  13461. addBuffer( scene.__webglObjects, geometry, object );
  13462. } else if ( geometry instanceof THREE.Geometry ) {
  13463. for ( g in geometry.geometryGroups ) {
  13464. geometryGroup = geometry.geometryGroups[ g ];
  13465. addBuffer( scene.__webglObjects, geometryGroup, object );
  13466. }
  13467. }
  13468. } else if ( object instanceof THREE.Ribbon ||
  13469. object instanceof THREE.Line ||
  13470. object instanceof THREE.ParticleSystem ) {
  13471. geometry = object.geometry;
  13472. addBuffer( scene.__webglObjects, geometry, object );
  13473. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13474. addBufferImmediate( scene.__webglObjectsImmediate, object );
  13475. } else if ( object instanceof THREE.Sprite ) {
  13476. scene.__webglSprites.push( object );
  13477. } else if ( object instanceof THREE.LensFlare ) {
  13478. scene.__webglFlares.push( object );
  13479. }
  13480. object.__webglActive = true;
  13481. }
  13482. };
  13483. function addBuffer ( objlist, buffer, object ) {
  13484. objlist.push(
  13485. {
  13486. buffer: buffer,
  13487. object: object,
  13488. opaque: null,
  13489. transparent: null
  13490. }
  13491. );
  13492. };
  13493. function addBufferImmediate ( objlist, object ) {
  13494. objlist.push(
  13495. {
  13496. object: object,
  13497. opaque: null,
  13498. transparent: null
  13499. }
  13500. );
  13501. };
  13502. // Objects updates
  13503. function updateObject ( object ) {
  13504. var geometry = object.geometry,
  13505. geometryGroup, customAttributesDirty, material;
  13506. if ( object instanceof THREE.Mesh ) {
  13507. if ( geometry instanceof THREE.BufferGeometry ) {
  13508. if ( geometry.verticesNeedUpdate || geometry.elementsNeedUpdate ||
  13509. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  13510. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate ) {
  13511. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  13512. }
  13513. geometry.verticesNeedUpdate = false;
  13514. geometry.elementsNeedUpdate = false;
  13515. geometry.uvsNeedUpdate = false;
  13516. geometry.normalsNeedUpdate = false;
  13517. geometry.colorsNeedUpdate = false;
  13518. geometry.tangentsNeedUpdate = false;
  13519. } else {
  13520. // check all geometry groups
  13521. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  13522. geometryGroup = geometry.geometryGroupsList[ i ];
  13523. material = getBufferMaterial( object, geometryGroup );
  13524. if ( geometry.buffersNeedUpdate ) {
  13525. initMeshBuffers( geometryGroup, object );
  13526. }
  13527. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13528. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  13529. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  13530. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  13531. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  13532. }
  13533. }
  13534. geometry.verticesNeedUpdate = false;
  13535. geometry.morphTargetsNeedUpdate = false;
  13536. geometry.elementsNeedUpdate = false;
  13537. geometry.uvsNeedUpdate = false;
  13538. geometry.normalsNeedUpdate = false;
  13539. geometry.colorsNeedUpdate = false;
  13540. geometry.tangentsNeedUpdate = false;
  13541. geometry.buffersNeedUpdate = false;
  13542. material.attributes && clearCustomAttributes( material );
  13543. }
  13544. } else if ( object instanceof THREE.Ribbon ) {
  13545. material = getBufferMaterial( object, geometry );
  13546. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13547. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.normalsNeedUpdate || customAttributesDirty ) {
  13548. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  13549. }
  13550. geometry.verticesNeedUpdate = false;
  13551. geometry.colorsNeedUpdate = false;
  13552. geometry.normalsNeedUpdate = false;
  13553. material.attributes && clearCustomAttributes( material );
  13554. } else if ( object instanceof THREE.Line ) {
  13555. if ( geometry instanceof THREE.BufferGeometry ) {
  13556. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  13557. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  13558. }
  13559. geometry.verticesNeedUpdate = false;
  13560. geometry.colorsNeedUpdate = false;
  13561. } else {
  13562. material = getBufferMaterial( object, geometry );
  13563. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13564. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  13565. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  13566. }
  13567. geometry.verticesNeedUpdate = false;
  13568. geometry.colorsNeedUpdate = false;
  13569. geometry.lineDistancesNeedUpdate = false;
  13570. material.attributes && clearCustomAttributes( material );
  13571. }
  13572. } else if ( object instanceof THREE.ParticleSystem ) {
  13573. if ( geometry instanceof THREE.BufferGeometry ) {
  13574. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  13575. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  13576. }
  13577. geometry.verticesNeedUpdate = false;
  13578. geometry.colorsNeedUpdate = false;
  13579. } else {
  13580. material = getBufferMaterial( object, geometry );
  13581. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  13582. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  13583. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  13584. }
  13585. geometry.verticesNeedUpdate = false;
  13586. geometry.colorsNeedUpdate = false;
  13587. material.attributes && clearCustomAttributes( material );
  13588. }
  13589. }
  13590. };
  13591. // Objects updates - custom attributes check
  13592. function areCustomAttributesDirty ( material ) {
  13593. for ( var a in material.attributes ) {
  13594. if ( material.attributes[ a ].needsUpdate ) return true;
  13595. }
  13596. return false;
  13597. };
  13598. function clearCustomAttributes ( material ) {
  13599. for ( var a in material.attributes ) {
  13600. material.attributes[ a ].needsUpdate = false;
  13601. }
  13602. };
  13603. // Objects removal
  13604. function removeObject ( object, scene ) {
  13605. if ( object instanceof THREE.Mesh ||
  13606. object instanceof THREE.ParticleSystem ||
  13607. object instanceof THREE.Ribbon ||
  13608. object instanceof THREE.Line ) {
  13609. removeInstances( scene.__webglObjects, object );
  13610. } else if ( object instanceof THREE.Sprite ) {
  13611. removeInstancesDirect( scene.__webglSprites, object );
  13612. } else if ( object instanceof THREE.LensFlare ) {
  13613. removeInstancesDirect( scene.__webglFlares, object );
  13614. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13615. removeInstances( scene.__webglObjectsImmediate, object );
  13616. }
  13617. object.__webglActive = false;
  13618. };
  13619. function removeInstances ( objlist, object ) {
  13620. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13621. if ( objlist[ o ].object === object ) {
  13622. objlist.splice( o, 1 );
  13623. }
  13624. }
  13625. };
  13626. function removeInstancesDirect ( objlist, object ) {
  13627. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13628. if ( objlist[ o ] === object ) {
  13629. objlist.splice( o, 1 );
  13630. }
  13631. }
  13632. };
  13633. // Materials
  13634. this.initMaterial = function ( material, lights, fog, object ) {
  13635. material.addEventListener( 'dispose', onMaterialDispose );
  13636. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  13637. if ( material instanceof THREE.MeshDepthMaterial ) {
  13638. shaderID = 'depth';
  13639. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13640. shaderID = 'normal';
  13641. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  13642. shaderID = 'basic';
  13643. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13644. shaderID = 'lambert';
  13645. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13646. shaderID = 'phong';
  13647. } else if ( material instanceof THREE.LineBasicMaterial ) {
  13648. shaderID = 'basic';
  13649. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13650. shaderID = 'dashed';
  13651. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  13652. shaderID = 'particle_basic';
  13653. }
  13654. if ( shaderID ) {
  13655. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  13656. }
  13657. // heuristics to create shader parameters according to lights in the scene
  13658. // (not to blow over maxLights budget)
  13659. maxLightCount = allocateLights( lights );
  13660. maxShadows = allocateShadows( lights );
  13661. maxBones = allocateBones( object );
  13662. parameters = {
  13663. map: !!material.map,
  13664. envMap: !!material.envMap,
  13665. lightMap: !!material.lightMap,
  13666. bumpMap: !!material.bumpMap,
  13667. normalMap: !!material.normalMap,
  13668. specularMap: !!material.specularMap,
  13669. vertexColors: material.vertexColors,
  13670. fog: fog,
  13671. useFog: material.fog,
  13672. fogExp: fog instanceof THREE.FogExp2,
  13673. sizeAttenuation: material.sizeAttenuation,
  13674. skinning: material.skinning,
  13675. maxBones: maxBones,
  13676. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  13677. boneTextureWidth: object && object.boneTextureWidth,
  13678. boneTextureHeight: object && object.boneTextureHeight,
  13679. morphTargets: material.morphTargets,
  13680. morphNormals: material.morphNormals,
  13681. maxMorphTargets: this.maxMorphTargets,
  13682. maxMorphNormals: this.maxMorphNormals,
  13683. maxDirLights: maxLightCount.directional,
  13684. maxPointLights: maxLightCount.point,
  13685. maxSpotLights: maxLightCount.spot,
  13686. maxHemiLights: maxLightCount.hemi,
  13687. maxShadows: maxShadows,
  13688. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  13689. shadowMapType: this.shadowMapType,
  13690. shadowMapDebug: this.shadowMapDebug,
  13691. shadowMapCascade: this.shadowMapCascade,
  13692. alphaTest: material.alphaTest,
  13693. metal: material.metal,
  13694. perPixel: material.perPixel,
  13695. wrapAround: material.wrapAround,
  13696. doubleSided: material.side === THREE.DoubleSide,
  13697. flipSided: material.side === THREE.BackSide
  13698. };
  13699. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters );
  13700. var attributes = material.program.attributes;
  13701. if ( material.morphTargets ) {
  13702. material.numSupportedMorphTargets = 0;
  13703. var id, base = "morphTarget";
  13704. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  13705. id = base + i;
  13706. if ( attributes[ id ] >= 0 ) {
  13707. material.numSupportedMorphTargets ++;
  13708. }
  13709. }
  13710. }
  13711. if ( material.morphNormals ) {
  13712. material.numSupportedMorphNormals = 0;
  13713. var id, base = "morphNormal";
  13714. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  13715. id = base + i;
  13716. if ( attributes[ id ] >= 0 ) {
  13717. material.numSupportedMorphNormals ++;
  13718. }
  13719. }
  13720. }
  13721. material.uniformsList = [];
  13722. for ( u in material.uniforms ) {
  13723. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  13724. }
  13725. };
  13726. function setMaterialShaders( material, shaders ) {
  13727. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  13728. material.vertexShader = shaders.vertexShader;
  13729. material.fragmentShader = shaders.fragmentShader;
  13730. };
  13731. function setProgram( camera, lights, fog, material, object ) {
  13732. _usedTextureUnits = 0;
  13733. if ( material.needsUpdate ) {
  13734. if ( material.program ) deallocateMaterial( material );
  13735. _this.initMaterial( material, lights, fog, object );
  13736. material.needsUpdate = false;
  13737. }
  13738. if ( material.morphTargets ) {
  13739. if ( ! object.__webglMorphTargetInfluences ) {
  13740. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  13741. }
  13742. }
  13743. var refreshMaterial = false;
  13744. var program = material.program,
  13745. p_uniforms = program.uniforms,
  13746. m_uniforms = material.uniforms;
  13747. if ( program !== _currentProgram ) {
  13748. _gl.useProgram( program );
  13749. _currentProgram = program;
  13750. refreshMaterial = true;
  13751. }
  13752. if ( material.id !== _currentMaterialId ) {
  13753. _currentMaterialId = material.id;
  13754. refreshMaterial = true;
  13755. }
  13756. if ( refreshMaterial || camera !== _currentCamera ) {
  13757. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  13758. if ( camera !== _currentCamera ) _currentCamera = camera;
  13759. }
  13760. // skinning uniforms must be set even if material didn't change
  13761. // auto-setting of texture unit for bone texture must go before other textures
  13762. // not sure why, but otherwise weird things happen
  13763. if ( material.skinning ) {
  13764. if ( _supportsBoneTextures && object.useVertexTexture ) {
  13765. if ( p_uniforms.boneTexture !== null ) {
  13766. var textureUnit = getTextureUnit();
  13767. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  13768. _this.setTexture( object.boneTexture, textureUnit );
  13769. }
  13770. } else {
  13771. if ( p_uniforms.boneGlobalMatrices !== null ) {
  13772. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  13773. }
  13774. }
  13775. }
  13776. if ( refreshMaterial ) {
  13777. // refresh uniforms common to several materials
  13778. if ( fog && material.fog ) {
  13779. refreshUniformsFog( m_uniforms, fog );
  13780. }
  13781. if ( material instanceof THREE.MeshPhongMaterial ||
  13782. material instanceof THREE.MeshLambertMaterial ||
  13783. material.lights ) {
  13784. if ( _lightsNeedUpdate ) {
  13785. setupLights( program, lights );
  13786. _lightsNeedUpdate = false;
  13787. }
  13788. refreshUniformsLights( m_uniforms, _lights );
  13789. }
  13790. if ( material instanceof THREE.MeshBasicMaterial ||
  13791. material instanceof THREE.MeshLambertMaterial ||
  13792. material instanceof THREE.MeshPhongMaterial ) {
  13793. refreshUniformsCommon( m_uniforms, material );
  13794. }
  13795. // refresh single material specific uniforms
  13796. if ( material instanceof THREE.LineBasicMaterial ) {
  13797. refreshUniformsLine( m_uniforms, material );
  13798. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13799. refreshUniformsLine( m_uniforms, material );
  13800. refreshUniformsDash( m_uniforms, material );
  13801. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  13802. refreshUniformsParticle( m_uniforms, material );
  13803. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13804. refreshUniformsPhong( m_uniforms, material );
  13805. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13806. refreshUniformsLambert( m_uniforms, material );
  13807. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  13808. m_uniforms.mNear.value = camera.near;
  13809. m_uniforms.mFar.value = camera.far;
  13810. m_uniforms.opacity.value = material.opacity;
  13811. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13812. m_uniforms.opacity.value = material.opacity;
  13813. }
  13814. if ( object.receiveShadow && ! material._shadowPass ) {
  13815. refreshUniformsShadow( m_uniforms, lights );
  13816. }
  13817. // load common uniforms
  13818. loadUniformsGeneric( program, material.uniformsList );
  13819. // load material specific uniforms
  13820. // (shader material also gets them for the sake of genericity)
  13821. if ( material instanceof THREE.ShaderMaterial ||
  13822. material instanceof THREE.MeshPhongMaterial ||
  13823. material.envMap ) {
  13824. if ( p_uniforms.cameraPosition !== null ) {
  13825. var position = camera.matrixWorld.getPosition();
  13826. _gl.uniform3f( p_uniforms.cameraPosition, position.x, position.y, position.z );
  13827. }
  13828. }
  13829. if ( material instanceof THREE.MeshPhongMaterial ||
  13830. material instanceof THREE.MeshLambertMaterial ||
  13831. material instanceof THREE.ShaderMaterial ||
  13832. material.skinning ) {
  13833. if ( p_uniforms.viewMatrix !== null ) {
  13834. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  13835. }
  13836. }
  13837. }
  13838. loadUniformsMatrices( p_uniforms, object );
  13839. if ( p_uniforms.modelMatrix !== null ) {
  13840. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  13841. }
  13842. return program;
  13843. };
  13844. // Uniforms (refresh uniforms objects)
  13845. function refreshUniformsCommon ( uniforms, material ) {
  13846. uniforms.opacity.value = material.opacity;
  13847. if ( _this.gammaInput ) {
  13848. uniforms.diffuse.value.copyGammaToLinear( material.color );
  13849. } else {
  13850. uniforms.diffuse.value = material.color;
  13851. }
  13852. uniforms.map.value = material.map;
  13853. uniforms.lightMap.value = material.lightMap;
  13854. uniforms.specularMap.value = material.specularMap;
  13855. if ( material.bumpMap ) {
  13856. uniforms.bumpMap.value = material.bumpMap;
  13857. uniforms.bumpScale.value = material.bumpScale;
  13858. }
  13859. if ( material.normalMap ) {
  13860. uniforms.normalMap.value = material.normalMap;
  13861. uniforms.normalScale.value.copy( material.normalScale );
  13862. }
  13863. // uv repeat and offset setting priorities
  13864. // 1. color map
  13865. // 2. specular map
  13866. // 3. normal map
  13867. // 4. bump map
  13868. var uvScaleMap;
  13869. if ( material.map ) {
  13870. uvScaleMap = material.map;
  13871. } else if ( material.specularMap ) {
  13872. uvScaleMap = material.specularMap;
  13873. } else if ( material.normalMap ) {
  13874. uvScaleMap = material.normalMap;
  13875. } else if ( material.bumpMap ) {
  13876. uvScaleMap = material.bumpMap;
  13877. }
  13878. if ( uvScaleMap !== undefined ) {
  13879. var offset = uvScaleMap.offset;
  13880. var repeat = uvScaleMap.repeat;
  13881. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  13882. }
  13883. uniforms.envMap.value = material.envMap;
  13884. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  13885. if ( _this.gammaInput ) {
  13886. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  13887. uniforms.reflectivity.value = material.reflectivity;
  13888. } else {
  13889. uniforms.reflectivity.value = material.reflectivity;
  13890. }
  13891. uniforms.refractionRatio.value = material.refractionRatio;
  13892. uniforms.combine.value = material.combine;
  13893. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  13894. };
  13895. function refreshUniformsLine ( uniforms, material ) {
  13896. uniforms.diffuse.value = material.color;
  13897. uniforms.opacity.value = material.opacity;
  13898. };
  13899. function refreshUniformsDash ( uniforms, material ) {
  13900. uniforms.dashSize.value = material.dashSize;
  13901. uniforms.totalSize.value = material.dashSize + material.gapSize;
  13902. uniforms.scale.value = material.scale;
  13903. };
  13904. function refreshUniformsParticle ( uniforms, material ) {
  13905. uniforms.psColor.value = material.color;
  13906. uniforms.opacity.value = material.opacity;
  13907. uniforms.size.value = material.size;
  13908. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  13909. uniforms.map.value = material.map;
  13910. };
  13911. function refreshUniformsFog ( uniforms, fog ) {
  13912. uniforms.fogColor.value = fog.color;
  13913. if ( fog instanceof THREE.Fog ) {
  13914. uniforms.fogNear.value = fog.near;
  13915. uniforms.fogFar.value = fog.far;
  13916. } else if ( fog instanceof THREE.FogExp2 ) {
  13917. uniforms.fogDensity.value = fog.density;
  13918. }
  13919. };
  13920. function refreshUniformsPhong ( uniforms, material ) {
  13921. uniforms.shininess.value = material.shininess;
  13922. if ( _this.gammaInput ) {
  13923. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  13924. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  13925. uniforms.specular.value.copyGammaToLinear( material.specular );
  13926. } else {
  13927. uniforms.ambient.value = material.ambient;
  13928. uniforms.emissive.value = material.emissive;
  13929. uniforms.specular.value = material.specular;
  13930. }
  13931. if ( material.wrapAround ) {
  13932. uniforms.wrapRGB.value.copy( material.wrapRGB );
  13933. }
  13934. };
  13935. function refreshUniformsLambert ( uniforms, material ) {
  13936. if ( _this.gammaInput ) {
  13937. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  13938. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  13939. } else {
  13940. uniforms.ambient.value = material.ambient;
  13941. uniforms.emissive.value = material.emissive;
  13942. }
  13943. if ( material.wrapAround ) {
  13944. uniforms.wrapRGB.value.copy( material.wrapRGB );
  13945. }
  13946. };
  13947. function refreshUniformsLights ( uniforms, lights ) {
  13948. uniforms.ambientLightColor.value = lights.ambient;
  13949. uniforms.directionalLightColor.value = lights.directional.colors;
  13950. uniforms.directionalLightDirection.value = lights.directional.positions;
  13951. uniforms.pointLightColor.value = lights.point.colors;
  13952. uniforms.pointLightPosition.value = lights.point.positions;
  13953. uniforms.pointLightDistance.value = lights.point.distances;
  13954. uniforms.spotLightColor.value = lights.spot.colors;
  13955. uniforms.spotLightPosition.value = lights.spot.positions;
  13956. uniforms.spotLightDistance.value = lights.spot.distances;
  13957. uniforms.spotLightDirection.value = lights.spot.directions;
  13958. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  13959. uniforms.spotLightExponent.value = lights.spot.exponents;
  13960. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  13961. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  13962. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  13963. };
  13964. function refreshUniformsShadow ( uniforms, lights ) {
  13965. if ( uniforms.shadowMatrix ) {
  13966. var j = 0;
  13967. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  13968. var light = lights[ i ];
  13969. if ( ! light.castShadow ) continue;
  13970. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  13971. uniforms.shadowMap.value[ j ] = light.shadowMap;
  13972. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  13973. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  13974. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  13975. uniforms.shadowBias.value[ j ] = light.shadowBias;
  13976. j ++;
  13977. }
  13978. }
  13979. }
  13980. };
  13981. // Uniforms (load to GPU)
  13982. function loadUniformsMatrices ( uniforms, object ) {
  13983. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  13984. if ( uniforms.normalMatrix ) {
  13985. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  13986. }
  13987. };
  13988. function getTextureUnit() {
  13989. var textureUnit = _usedTextureUnits;
  13990. if ( textureUnit >= _maxTextures ) {
  13991. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  13992. }
  13993. _usedTextureUnits += 1;
  13994. return textureUnit;
  13995. };
  13996. function loadUniformsGeneric ( program, uniforms ) {
  13997. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  13998. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  13999. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  14000. if ( !location ) continue;
  14001. uniform = uniforms[ j ][ 0 ];
  14002. type = uniform.type;
  14003. value = uniform.value;
  14004. if ( type === "i" ) { // single integer
  14005. _gl.uniform1i( location, value );
  14006. } else if ( type === "f" ) { // single float
  14007. _gl.uniform1f( location, value );
  14008. } else if ( type === "v2" ) { // single THREE.Vector2
  14009. _gl.uniform2f( location, value.x, value.y );
  14010. } else if ( type === "v3" ) { // single THREE.Vector3
  14011. _gl.uniform3f( location, value.x, value.y, value.z );
  14012. } else if ( type === "v4" ) { // single THREE.Vector4
  14013. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  14014. } else if ( type === "c" ) { // single THREE.Color
  14015. _gl.uniform3f( location, value.r, value.g, value.b );
  14016. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  14017. _gl.uniform1iv( location, value );
  14018. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  14019. _gl.uniform3iv( location, value );
  14020. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  14021. _gl.uniform1fv( location, value );
  14022. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  14023. _gl.uniform3fv( location, value );
  14024. } else if ( type === "v2v" ) { // array of THREE.Vector2
  14025. if ( uniform._array === undefined ) {
  14026. uniform._array = new Float32Array( 2 * value.length );
  14027. }
  14028. for ( i = 0, il = value.length; i < il; i ++ ) {
  14029. offset = i * 2;
  14030. uniform._array[ offset ] = value[ i ].x;
  14031. uniform._array[ offset + 1 ] = value[ i ].y;
  14032. }
  14033. _gl.uniform2fv( location, uniform._array );
  14034. } else if ( type === "v3v" ) { // array of THREE.Vector3
  14035. if ( uniform._array === undefined ) {
  14036. uniform._array = new Float32Array( 3 * value.length );
  14037. }
  14038. for ( i = 0, il = value.length; i < il; i ++ ) {
  14039. offset = i * 3;
  14040. uniform._array[ offset ] = value[ i ].x;
  14041. uniform._array[ offset + 1 ] = value[ i ].y;
  14042. uniform._array[ offset + 2 ] = value[ i ].z;
  14043. }
  14044. _gl.uniform3fv( location, uniform._array );
  14045. } else if ( type === "v4v" ) { // array of THREE.Vector4
  14046. if ( uniform._array === undefined ) {
  14047. uniform._array = new Float32Array( 4 * value.length );
  14048. }
  14049. for ( i = 0, il = value.length; i < il; i ++ ) {
  14050. offset = i * 4;
  14051. uniform._array[ offset ] = value[ i ].x;
  14052. uniform._array[ offset + 1 ] = value[ i ].y;
  14053. uniform._array[ offset + 2 ] = value[ i ].z;
  14054. uniform._array[ offset + 3 ] = value[ i ].w;
  14055. }
  14056. _gl.uniform4fv( location, uniform._array );
  14057. } else if ( type === "m4") { // single THREE.Matrix4
  14058. if ( uniform._array === undefined ) {
  14059. uniform._array = new Float32Array( 16 );
  14060. }
  14061. value.flattenToArray( uniform._array );
  14062. _gl.uniformMatrix4fv( location, false, uniform._array );
  14063. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  14064. if ( uniform._array === undefined ) {
  14065. uniform._array = new Float32Array( 16 * value.length );
  14066. }
  14067. for ( i = 0, il = value.length; i < il; i ++ ) {
  14068. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  14069. }
  14070. _gl.uniformMatrix4fv( location, false, uniform._array );
  14071. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  14072. texture = value;
  14073. textureUnit = getTextureUnit();
  14074. _gl.uniform1i( location, textureUnit );
  14075. if ( !texture ) continue;
  14076. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  14077. setCubeTexture( texture, textureUnit );
  14078. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  14079. setCubeTextureDynamic( texture, textureUnit );
  14080. } else {
  14081. _this.setTexture( texture, textureUnit );
  14082. }
  14083. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  14084. if ( uniform._array === undefined ) {
  14085. uniform._array = [];
  14086. }
  14087. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14088. uniform._array[ i ] = getTextureUnit();
  14089. }
  14090. _gl.uniform1iv( location, uniform._array );
  14091. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14092. texture = uniform.value[ i ];
  14093. textureUnit = uniform._array[ i ];
  14094. if ( !texture ) continue;
  14095. _this.setTexture( texture, textureUnit );
  14096. }
  14097. }
  14098. }
  14099. };
  14100. function setupMatrices ( object, camera ) {
  14101. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  14102. object._normalMatrix.getInverse( object._modelViewMatrix );
  14103. object._normalMatrix.transpose();
  14104. };
  14105. //
  14106. function setColorGamma( array, offset, color, intensitySq ) {
  14107. array[ offset ] = color.r * color.r * intensitySq;
  14108. array[ offset + 1 ] = color.g * color.g * intensitySq;
  14109. array[ offset + 2 ] = color.b * color.b * intensitySq;
  14110. };
  14111. function setColorLinear( array, offset, color, intensity ) {
  14112. array[ offset ] = color.r * intensity;
  14113. array[ offset + 1 ] = color.g * intensity;
  14114. array[ offset + 2 ] = color.b * intensity;
  14115. };
  14116. function setupLights ( program, lights ) {
  14117. var l, ll, light, n,
  14118. r = 0, g = 0, b = 0,
  14119. color, skyColor, groundColor,
  14120. intensity, intensitySq,
  14121. position,
  14122. distance,
  14123. zlights = _lights,
  14124. dirColors = zlights.directional.colors,
  14125. dirPositions = zlights.directional.positions,
  14126. pointColors = zlights.point.colors,
  14127. pointPositions = zlights.point.positions,
  14128. pointDistances = zlights.point.distances,
  14129. spotColors = zlights.spot.colors,
  14130. spotPositions = zlights.spot.positions,
  14131. spotDistances = zlights.spot.distances,
  14132. spotDirections = zlights.spot.directions,
  14133. spotAnglesCos = zlights.spot.anglesCos,
  14134. spotExponents = zlights.spot.exponents,
  14135. hemiSkyColors = zlights.hemi.skyColors,
  14136. hemiGroundColors = zlights.hemi.groundColors,
  14137. hemiPositions = zlights.hemi.positions,
  14138. dirLength = 0,
  14139. pointLength = 0,
  14140. spotLength = 0,
  14141. hemiLength = 0,
  14142. dirCount = 0,
  14143. pointCount = 0,
  14144. spotCount = 0,
  14145. hemiCount = 0,
  14146. dirOffset = 0,
  14147. pointOffset = 0,
  14148. spotOffset = 0,
  14149. hemiOffset = 0;
  14150. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14151. light = lights[ l ];
  14152. if ( light.onlyShadow ) continue;
  14153. color = light.color;
  14154. intensity = light.intensity;
  14155. distance = light.distance;
  14156. if ( light instanceof THREE.AmbientLight ) {
  14157. if ( ! light.visible ) continue;
  14158. if ( _this.gammaInput ) {
  14159. r += color.r * color.r;
  14160. g += color.g * color.g;
  14161. b += color.b * color.b;
  14162. } else {
  14163. r += color.r;
  14164. g += color.g;
  14165. b += color.b;
  14166. }
  14167. } else if ( light instanceof THREE.DirectionalLight ) {
  14168. dirCount += 1;
  14169. if ( ! light.visible ) continue;
  14170. _direction.copy( light.matrixWorld.getPosition() );
  14171. _direction.sub( light.target.matrixWorld.getPosition() );
  14172. _direction.normalize();
  14173. // skip lights with undefined direction
  14174. // these create troubles in OpenGL (making pixel black)
  14175. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14176. dirOffset = dirLength * 3;
  14177. dirPositions[ dirOffset ] = _direction.x;
  14178. dirPositions[ dirOffset + 1 ] = _direction.y;
  14179. dirPositions[ dirOffset + 2 ] = _direction.z;
  14180. if ( _this.gammaInput ) {
  14181. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  14182. } else {
  14183. setColorLinear( dirColors, dirOffset, color, intensity );
  14184. }
  14185. dirLength += 1;
  14186. } else if ( light instanceof THREE.PointLight ) {
  14187. pointCount += 1;
  14188. if ( ! light.visible ) continue;
  14189. pointOffset = pointLength * 3;
  14190. if ( _this.gammaInput ) {
  14191. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  14192. } else {
  14193. setColorLinear( pointColors, pointOffset, color, intensity );
  14194. }
  14195. position = light.matrixWorld.getPosition();
  14196. pointPositions[ pointOffset ] = position.x;
  14197. pointPositions[ pointOffset + 1 ] = position.y;
  14198. pointPositions[ pointOffset + 2 ] = position.z;
  14199. pointDistances[ pointLength ] = distance;
  14200. pointLength += 1;
  14201. } else if ( light instanceof THREE.SpotLight ) {
  14202. spotCount += 1;
  14203. if ( ! light.visible ) continue;
  14204. spotOffset = spotLength * 3;
  14205. if ( _this.gammaInput ) {
  14206. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  14207. } else {
  14208. setColorLinear( spotColors, spotOffset, color, intensity );
  14209. }
  14210. position = light.matrixWorld.getPosition();
  14211. spotPositions[ spotOffset ] = position.x;
  14212. spotPositions[ spotOffset + 1 ] = position.y;
  14213. spotPositions[ spotOffset + 2 ] = position.z;
  14214. spotDistances[ spotLength ] = distance;
  14215. _direction.copy( position );
  14216. _direction.sub( light.target.matrixWorld.getPosition() );
  14217. _direction.normalize();
  14218. spotDirections[ spotOffset ] = _direction.x;
  14219. spotDirections[ spotOffset + 1 ] = _direction.y;
  14220. spotDirections[ spotOffset + 2 ] = _direction.z;
  14221. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  14222. spotExponents[ spotLength ] = light.exponent;
  14223. spotLength += 1;
  14224. } else if ( light instanceof THREE.HemisphereLight ) {
  14225. hemiCount += 1;
  14226. if ( ! light.visible ) continue;
  14227. _direction.copy( light.matrixWorld.getPosition() );
  14228. _direction.normalize();
  14229. // skip lights with undefined direction
  14230. // these create troubles in OpenGL (making pixel black)
  14231. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14232. hemiOffset = hemiLength * 3;
  14233. hemiPositions[ hemiOffset ] = _direction.x;
  14234. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  14235. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  14236. skyColor = light.color;
  14237. groundColor = light.groundColor;
  14238. if ( _this.gammaInput ) {
  14239. intensitySq = intensity * intensity;
  14240. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  14241. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  14242. } else {
  14243. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  14244. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  14245. }
  14246. hemiLength += 1;
  14247. }
  14248. }
  14249. // null eventual remains from removed lights
  14250. // (this is to avoid if in shader)
  14251. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  14252. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  14253. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  14254. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  14255. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  14256. zlights.directional.length = dirLength;
  14257. zlights.point.length = pointLength;
  14258. zlights.spot.length = spotLength;
  14259. zlights.hemi.length = hemiLength;
  14260. zlights.ambient[ 0 ] = r;
  14261. zlights.ambient[ 1 ] = g;
  14262. zlights.ambient[ 2 ] = b;
  14263. };
  14264. // GL state setting
  14265. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  14266. if ( cullFace === THREE.CullFaceNone ) {
  14267. _gl.disable( _gl.CULL_FACE );
  14268. } else {
  14269. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  14270. _gl.frontFace( _gl.CW );
  14271. } else {
  14272. _gl.frontFace( _gl.CCW );
  14273. }
  14274. if ( cullFace === THREE.CullFaceBack ) {
  14275. _gl.cullFace( _gl.BACK );
  14276. } else if ( cullFace === THREE.CullFaceFront ) {
  14277. _gl.cullFace( _gl.FRONT );
  14278. } else {
  14279. _gl.cullFace( _gl.FRONT_AND_BACK );
  14280. }
  14281. _gl.enable( _gl.CULL_FACE );
  14282. }
  14283. };
  14284. this.setMaterialFaces = function ( material ) {
  14285. var doubleSided = material.side === THREE.DoubleSide;
  14286. var flipSided = material.side === THREE.BackSide;
  14287. if ( _oldDoubleSided !== doubleSided ) {
  14288. if ( doubleSided ) {
  14289. _gl.disable( _gl.CULL_FACE );
  14290. } else {
  14291. _gl.enable( _gl.CULL_FACE );
  14292. }
  14293. _oldDoubleSided = doubleSided;
  14294. }
  14295. if ( _oldFlipSided !== flipSided ) {
  14296. if ( flipSided ) {
  14297. _gl.frontFace( _gl.CW );
  14298. } else {
  14299. _gl.frontFace( _gl.CCW );
  14300. }
  14301. _oldFlipSided = flipSided;
  14302. }
  14303. };
  14304. this.setDepthTest = function ( depthTest ) {
  14305. if ( _oldDepthTest !== depthTest ) {
  14306. if ( depthTest ) {
  14307. _gl.enable( _gl.DEPTH_TEST );
  14308. } else {
  14309. _gl.disable( _gl.DEPTH_TEST );
  14310. }
  14311. _oldDepthTest = depthTest;
  14312. }
  14313. };
  14314. this.setDepthWrite = function ( depthWrite ) {
  14315. if ( _oldDepthWrite !== depthWrite ) {
  14316. _gl.depthMask( depthWrite );
  14317. _oldDepthWrite = depthWrite;
  14318. }
  14319. };
  14320. function setLineWidth ( width ) {
  14321. if ( width !== _oldLineWidth ) {
  14322. _gl.lineWidth( width );
  14323. _oldLineWidth = width;
  14324. }
  14325. };
  14326. function setPolygonOffset ( polygonoffset, factor, units ) {
  14327. if ( _oldPolygonOffset !== polygonoffset ) {
  14328. if ( polygonoffset ) {
  14329. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  14330. } else {
  14331. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  14332. }
  14333. _oldPolygonOffset = polygonoffset;
  14334. }
  14335. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  14336. _gl.polygonOffset( factor, units );
  14337. _oldPolygonOffsetFactor = factor;
  14338. _oldPolygonOffsetUnits = units;
  14339. }
  14340. };
  14341. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  14342. if ( blending !== _oldBlending ) {
  14343. if ( blending === THREE.NoBlending ) {
  14344. _gl.disable( _gl.BLEND );
  14345. } else if ( blending === THREE.AdditiveBlending ) {
  14346. _gl.enable( _gl.BLEND );
  14347. _gl.blendEquation( _gl.FUNC_ADD );
  14348. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  14349. } else if ( blending === THREE.SubtractiveBlending ) {
  14350. // TODO: Find blendFuncSeparate() combination
  14351. _gl.enable( _gl.BLEND );
  14352. _gl.blendEquation( _gl.FUNC_ADD );
  14353. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  14354. } else if ( blending === THREE.MultiplyBlending ) {
  14355. // TODO: Find blendFuncSeparate() combination
  14356. _gl.enable( _gl.BLEND );
  14357. _gl.blendEquation( _gl.FUNC_ADD );
  14358. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  14359. } else if ( blending === THREE.CustomBlending ) {
  14360. _gl.enable( _gl.BLEND );
  14361. } else {
  14362. _gl.enable( _gl.BLEND );
  14363. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  14364. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  14365. }
  14366. _oldBlending = blending;
  14367. }
  14368. if ( blending === THREE.CustomBlending ) {
  14369. if ( blendEquation !== _oldBlendEquation ) {
  14370. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  14371. _oldBlendEquation = blendEquation;
  14372. }
  14373. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  14374. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  14375. _oldBlendSrc = blendSrc;
  14376. _oldBlendDst = blendDst;
  14377. }
  14378. } else {
  14379. _oldBlendEquation = null;
  14380. _oldBlendSrc = null;
  14381. _oldBlendDst = null;
  14382. }
  14383. };
  14384. // Defines
  14385. function generateDefines ( defines ) {
  14386. var value, chunk, chunks = [];
  14387. for ( var d in defines ) {
  14388. value = defines[ d ];
  14389. if ( value === false ) continue;
  14390. chunk = "#define " + d + " " + value;
  14391. chunks.push( chunk );
  14392. }
  14393. return chunks.join( "\n" );
  14394. };
  14395. // Shaders
  14396. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters ) {
  14397. var p, pl, d, program, code;
  14398. var chunks = [];
  14399. // Generate code
  14400. if ( shaderID ) {
  14401. chunks.push( shaderID );
  14402. } else {
  14403. chunks.push( fragmentShader );
  14404. chunks.push( vertexShader );
  14405. }
  14406. for ( d in defines ) {
  14407. chunks.push( d );
  14408. chunks.push( defines[ d ] );
  14409. }
  14410. for ( p in parameters ) {
  14411. chunks.push( p );
  14412. chunks.push( parameters[ p ] );
  14413. }
  14414. code = chunks.join();
  14415. // Check if code has been already compiled
  14416. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  14417. var programInfo = _programs[ p ];
  14418. if ( programInfo.code === code ) {
  14419. //console.log( "Code already compiled." /*: \n\n" + code*/ );
  14420. programInfo.usedTimes ++;
  14421. return programInfo.program;
  14422. }
  14423. }
  14424. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  14425. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  14426. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  14427. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  14428. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  14429. }
  14430. //console.log( "building new program " );
  14431. //
  14432. var customDefines = generateDefines( defines );
  14433. //
  14434. program = _gl.createProgram();
  14435. var prefix_vertex = [
  14436. "precision " + _precision + " float;",
  14437. customDefines,
  14438. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  14439. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  14440. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  14441. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  14442. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  14443. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  14444. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  14445. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  14446. "#define MAX_SHADOWS " + parameters.maxShadows,
  14447. "#define MAX_BONES " + parameters.maxBones,
  14448. parameters.map ? "#define USE_MAP" : "",
  14449. parameters.envMap ? "#define USE_ENVMAP" : "",
  14450. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  14451. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  14452. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  14453. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  14454. parameters.vertexColors ? "#define USE_COLOR" : "",
  14455. parameters.skinning ? "#define USE_SKINNING" : "",
  14456. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  14457. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  14458. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  14459. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  14460. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  14461. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  14462. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  14463. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  14464. parameters.flipSided ? "#define FLIP_SIDED" : "",
  14465. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  14466. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  14467. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  14468. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  14469. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  14470. "uniform mat4 modelMatrix;",
  14471. "uniform mat4 modelViewMatrix;",
  14472. "uniform mat4 projectionMatrix;",
  14473. "uniform mat4 viewMatrix;",
  14474. "uniform mat3 normalMatrix;",
  14475. "uniform vec3 cameraPosition;",
  14476. "attribute vec3 position;",
  14477. "attribute vec3 normal;",
  14478. "attribute vec2 uv;",
  14479. "attribute vec2 uv2;",
  14480. "#ifdef USE_COLOR",
  14481. "attribute vec3 color;",
  14482. "#endif",
  14483. "#ifdef USE_MORPHTARGETS",
  14484. "attribute vec3 morphTarget0;",
  14485. "attribute vec3 morphTarget1;",
  14486. "attribute vec3 morphTarget2;",
  14487. "attribute vec3 morphTarget3;",
  14488. "#ifdef USE_MORPHNORMALS",
  14489. "attribute vec3 morphNormal0;",
  14490. "attribute vec3 morphNormal1;",
  14491. "attribute vec3 morphNormal2;",
  14492. "attribute vec3 morphNormal3;",
  14493. "#else",
  14494. "attribute vec3 morphTarget4;",
  14495. "attribute vec3 morphTarget5;",
  14496. "attribute vec3 morphTarget6;",
  14497. "attribute vec3 morphTarget7;",
  14498. "#endif",
  14499. "#endif",
  14500. "#ifdef USE_SKINNING",
  14501. "attribute vec4 skinIndex;",
  14502. "attribute vec4 skinWeight;",
  14503. "#endif",
  14504. ""
  14505. ].join("\n");
  14506. var prefix_fragment = [
  14507. "precision " + _precision + " float;",
  14508. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  14509. customDefines,
  14510. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  14511. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  14512. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  14513. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  14514. "#define MAX_SHADOWS " + parameters.maxShadows,
  14515. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  14516. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  14517. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  14518. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  14519. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  14520. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  14521. parameters.map ? "#define USE_MAP" : "",
  14522. parameters.envMap ? "#define USE_ENVMAP" : "",
  14523. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  14524. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  14525. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  14526. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  14527. parameters.vertexColors ? "#define USE_COLOR" : "",
  14528. parameters.metal ? "#define METAL" : "",
  14529. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  14530. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  14531. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  14532. parameters.flipSided ? "#define FLIP_SIDED" : "",
  14533. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  14534. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  14535. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  14536. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  14537. "uniform mat4 viewMatrix;",
  14538. "uniform vec3 cameraPosition;",
  14539. ""
  14540. ].join("\n");
  14541. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  14542. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  14543. _gl.attachShader( program, glVertexShader );
  14544. _gl.attachShader( program, glFragmentShader );
  14545. _gl.linkProgram( program );
  14546. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  14547. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  14548. }
  14549. // clean up
  14550. _gl.deleteShader( glFragmentShader );
  14551. _gl.deleteShader( glVertexShader );
  14552. //console.log( prefix_fragment + fragmentShader );
  14553. //console.log( prefix_vertex + vertexShader );
  14554. program.uniforms = {};
  14555. program.attributes = {};
  14556. var identifiers, u, a, i;
  14557. // cache uniform locations
  14558. identifiers = [
  14559. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  14560. 'morphTargetInfluences'
  14561. ];
  14562. if ( parameters.useVertexTexture ) {
  14563. identifiers.push( 'boneTexture' );
  14564. } else {
  14565. identifiers.push( 'boneGlobalMatrices' );
  14566. }
  14567. for ( u in uniforms ) {
  14568. identifiers.push( u );
  14569. }
  14570. cacheUniformLocations( program, identifiers );
  14571. // cache attributes locations
  14572. identifiers = [
  14573. "position", "normal", "uv", "uv2", "tangent", "color",
  14574. "skinIndex", "skinWeight", "lineDistance"
  14575. ];
  14576. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  14577. identifiers.push( "morphTarget" + i );
  14578. }
  14579. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  14580. identifiers.push( "morphNormal" + i );
  14581. }
  14582. for ( a in attributes ) {
  14583. identifiers.push( a );
  14584. }
  14585. cacheAttributeLocations( program, identifiers );
  14586. program.id = _programs_counter ++;
  14587. _programs.push( { program: program, code: code, usedTimes: 1 } );
  14588. _this.info.memory.programs = _programs.length;
  14589. return program;
  14590. };
  14591. // Shader parameters cache
  14592. function cacheUniformLocations ( program, identifiers ) {
  14593. var i, l, id;
  14594. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14595. id = identifiers[ i ];
  14596. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  14597. }
  14598. };
  14599. function cacheAttributeLocations ( program, identifiers ) {
  14600. var i, l, id;
  14601. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14602. id = identifiers[ i ];
  14603. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  14604. }
  14605. };
  14606. function addLineNumbers ( string ) {
  14607. var chunks = string.split( "\n" );
  14608. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  14609. // Chrome reports shader errors on lines
  14610. // starting counting from 1
  14611. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  14612. }
  14613. return chunks.join( "\n" );
  14614. };
  14615. function getShader ( type, string ) {
  14616. var shader;
  14617. if ( type === "fragment" ) {
  14618. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  14619. } else if ( type === "vertex" ) {
  14620. shader = _gl.createShader( _gl.VERTEX_SHADER );
  14621. }
  14622. _gl.shaderSource( shader, string );
  14623. _gl.compileShader( shader );
  14624. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  14625. console.error( _gl.getShaderInfoLog( shader ) );
  14626. console.error( addLineNumbers( string ) );
  14627. return null;
  14628. }
  14629. return shader;
  14630. };
  14631. // Textures
  14632. function isPowerOfTwo ( value ) {
  14633. return ( value & ( value - 1 ) ) === 0;
  14634. };
  14635. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  14636. if ( isImagePowerOfTwo ) {
  14637. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  14638. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  14639. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  14640. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  14641. } else {
  14642. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  14643. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  14644. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  14645. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  14646. }
  14647. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  14648. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  14649. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  14650. texture.__oldAnisotropy = texture.anisotropy;
  14651. }
  14652. }
  14653. };
  14654. this.setTexture = function ( texture, slot ) {
  14655. if ( texture.needsUpdate ) {
  14656. if ( ! texture.__webglInit ) {
  14657. texture.__webglInit = true;
  14658. texture.addEventListener( 'dispose', onTextureDispose );
  14659. texture.__webglTexture = _gl.createTexture();
  14660. _this.info.memory.textures ++;
  14661. }
  14662. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14663. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14664. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14665. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14666. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14667. var image = texture.image,
  14668. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  14669. glFormat = paramThreeToGL( texture.format ),
  14670. glType = paramThreeToGL( texture.type );
  14671. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  14672. var mipmap, mipmaps = texture.mipmaps;
  14673. if ( texture instanceof THREE.DataTexture ) {
  14674. // use manually created mipmaps if available
  14675. // if there are no manual mipmaps
  14676. // set 0 level mipmap and then use GL to generate other mipmap levels
  14677. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14678. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14679. mipmap = mipmaps[ i ];
  14680. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14681. }
  14682. texture.generateMipmaps = false;
  14683. } else {
  14684. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14685. }
  14686. } else if ( texture instanceof THREE.CompressedTexture ) {
  14687. // compressed textures can only use manually created mipmaps
  14688. // WebGL can't generate mipmaps for DDS textures
  14689. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14690. mipmap = mipmaps[ i ];
  14691. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14692. }
  14693. } else { // regular Texture (image, video, canvas)
  14694. // use manually created mipmaps if available
  14695. // if there are no manual mipmaps
  14696. // set 0 level mipmap and then use GL to generate other mipmap levels
  14697. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14698. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14699. mipmap = mipmaps[ i ];
  14700. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  14701. }
  14702. texture.generateMipmaps = false;
  14703. } else {
  14704. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  14705. }
  14706. }
  14707. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14708. texture.needsUpdate = false;
  14709. if ( texture.onUpdate ) texture.onUpdate();
  14710. } else {
  14711. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14712. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14713. }
  14714. };
  14715. function clampToMaxSize ( image, maxSize ) {
  14716. if ( image.width <= maxSize && image.height <= maxSize ) {
  14717. return image;
  14718. }
  14719. // Warning: Scaling through the canvas will only work with images that use
  14720. // premultiplied alpha.
  14721. var maxDimension = Math.max( image.width, image.height );
  14722. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  14723. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  14724. var canvas = document.createElement( 'canvas' );
  14725. canvas.width = newWidth;
  14726. canvas.height = newHeight;
  14727. var ctx = canvas.getContext( "2d" );
  14728. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  14729. return canvas;
  14730. }
  14731. function setCubeTexture ( texture, slot ) {
  14732. if ( texture.image.length === 6 ) {
  14733. if ( texture.needsUpdate ) {
  14734. if ( ! texture.image.__webglTextureCube ) {
  14735. texture.image.__webglTextureCube = _gl.createTexture();
  14736. _this.info.memory.textures ++;
  14737. }
  14738. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14739. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  14740. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14741. var isCompressed = texture instanceof THREE.CompressedTexture;
  14742. var cubeImage = [];
  14743. for ( var i = 0; i < 6; i ++ ) {
  14744. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  14745. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  14746. } else {
  14747. cubeImage[ i ] = texture.image[ i ];
  14748. }
  14749. }
  14750. var image = cubeImage[ 0 ],
  14751. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  14752. glFormat = paramThreeToGL( texture.format ),
  14753. glType = paramThreeToGL( texture.type );
  14754. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  14755. for ( var i = 0; i < 6; i ++ ) {
  14756. if ( isCompressed ) {
  14757. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  14758. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  14759. mipmap = mipmaps[ j ];
  14760. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14761. }
  14762. } else {
  14763. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  14764. }
  14765. }
  14766. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  14767. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14768. }
  14769. texture.needsUpdate = false;
  14770. if ( texture.onUpdate ) texture.onUpdate();
  14771. } else {
  14772. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14773. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  14774. }
  14775. }
  14776. };
  14777. function setCubeTextureDynamic ( texture, slot ) {
  14778. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14779. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  14780. };
  14781. // Render targets
  14782. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  14783. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14784. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  14785. };
  14786. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  14787. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  14788. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14789. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  14790. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14791. /* For some reason this is not working. Defaulting to RGBA4.
  14792. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14793. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  14794. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14795. */
  14796. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14797. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  14798. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14799. } else {
  14800. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  14801. }
  14802. };
  14803. this.setRenderTarget = function ( renderTarget ) {
  14804. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  14805. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  14806. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  14807. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  14808. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  14809. renderTarget.__webglTexture = _gl.createTexture();
  14810. _this.info.memory.textures ++;
  14811. // Setup texture, create render and frame buffers
  14812. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  14813. glFormat = paramThreeToGL( renderTarget.format ),
  14814. glType = paramThreeToGL( renderTarget.type );
  14815. if ( isCube ) {
  14816. renderTarget.__webglFramebuffer = [];
  14817. renderTarget.__webglRenderbuffer = [];
  14818. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  14819. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  14820. for ( var i = 0; i < 6; i ++ ) {
  14821. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  14822. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  14823. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14824. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  14825. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  14826. }
  14827. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14828. } else {
  14829. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  14830. if ( renderTarget.shareDepthFrom ) {
  14831. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  14832. } else {
  14833. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  14834. }
  14835. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  14836. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  14837. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14838. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  14839. if ( renderTarget.shareDepthFrom ) {
  14840. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14841. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  14842. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14843. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  14844. }
  14845. } else {
  14846. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  14847. }
  14848. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14849. }
  14850. // Release everything
  14851. if ( isCube ) {
  14852. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  14853. } else {
  14854. _gl.bindTexture( _gl.TEXTURE_2D, null );
  14855. }
  14856. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  14857. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14858. }
  14859. var framebuffer, width, height, vx, vy;
  14860. if ( renderTarget ) {
  14861. if ( isCube ) {
  14862. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  14863. } else {
  14864. framebuffer = renderTarget.__webglFramebuffer;
  14865. }
  14866. width = renderTarget.width;
  14867. height = renderTarget.height;
  14868. vx = 0;
  14869. vy = 0;
  14870. } else {
  14871. framebuffer = null;
  14872. width = _viewportWidth;
  14873. height = _viewportHeight;
  14874. vx = _viewportX;
  14875. vy = _viewportY;
  14876. }
  14877. if ( framebuffer !== _currentFramebuffer ) {
  14878. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14879. _gl.viewport( vx, vy, width, height );
  14880. _currentFramebuffer = framebuffer;
  14881. }
  14882. _currentWidth = width;
  14883. _currentHeight = height;
  14884. };
  14885. function updateRenderTargetMipmap ( renderTarget ) {
  14886. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  14887. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  14888. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14889. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  14890. } else {
  14891. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  14892. _gl.generateMipmap( _gl.TEXTURE_2D );
  14893. _gl.bindTexture( _gl.TEXTURE_2D, null );
  14894. }
  14895. };
  14896. // Fallback filters for non-power-of-2 textures
  14897. function filterFallback ( f ) {
  14898. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  14899. return _gl.NEAREST;
  14900. }
  14901. return _gl.LINEAR;
  14902. };
  14903. // Map three.js constants to WebGL constants
  14904. function paramThreeToGL ( p ) {
  14905. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  14906. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  14907. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  14908. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  14909. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  14910. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  14911. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  14912. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  14913. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  14914. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  14915. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  14916. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  14917. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  14918. if ( p === THREE.ByteType ) return _gl.BYTE;
  14919. if ( p === THREE.ShortType ) return _gl.SHORT;
  14920. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  14921. if ( p === THREE.IntType ) return _gl.INT;
  14922. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  14923. if ( p === THREE.FloatType ) return _gl.FLOAT;
  14924. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  14925. if ( p === THREE.RGBFormat ) return _gl.RGB;
  14926. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  14927. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  14928. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  14929. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  14930. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  14931. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  14932. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  14933. if ( p === THREE.OneFactor ) return _gl.ONE;
  14934. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  14935. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  14936. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  14937. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  14938. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  14939. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  14940. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  14941. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  14942. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  14943. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  14944. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14945. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14946. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14947. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14948. }
  14949. return 0;
  14950. };
  14951. // Allocations
  14952. function allocateBones ( object ) {
  14953. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  14954. return 1024;
  14955. } else {
  14956. // default for when object is not specified
  14957. // ( for example when prebuilding shader
  14958. // to be used with multiple objects )
  14959. //
  14960. // - leave some extra space for other uniforms
  14961. // - limit here is ANGLE's 254 max uniform vectors
  14962. // (up to 54 should be safe)
  14963. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  14964. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  14965. var maxBones = nVertexMatrices;
  14966. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  14967. maxBones = Math.min( object.bones.length, maxBones );
  14968. if ( maxBones < object.bones.length ) {
  14969. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  14970. }
  14971. }
  14972. return maxBones;
  14973. }
  14974. };
  14975. function allocateLights ( lights ) {
  14976. var l, ll, light, dirLights, pointLights, spotLights, hemiLights;
  14977. dirLights = pointLights = spotLights = hemiLights = 0;
  14978. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14979. light = lights[ l ];
  14980. if ( light.onlyShadow ) continue;
  14981. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  14982. if ( light instanceof THREE.PointLight ) pointLights ++;
  14983. if ( light instanceof THREE.SpotLight ) spotLights ++;
  14984. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  14985. }
  14986. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  14987. };
  14988. function allocateShadows ( lights ) {
  14989. var l, ll, light, maxShadows = 0;
  14990. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  14991. light = lights[ l ];
  14992. if ( ! light.castShadow ) continue;
  14993. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  14994. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  14995. }
  14996. return maxShadows;
  14997. };
  14998. // Initialization
  14999. function initGL () {
  15000. try {
  15001. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  15002. throw 'Error creating WebGL context.';
  15003. }
  15004. } catch ( error ) {
  15005. console.error( error );
  15006. }
  15007. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  15008. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  15009. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) ||
  15010. _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) ||
  15011. _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15012. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) ||
  15013. _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) ||
  15014. _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15015. if ( ! _glExtensionTextureFloat ) {
  15016. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  15017. }
  15018. if ( ! _glExtensionStandardDerivatives ) {
  15019. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  15020. }
  15021. if ( ! _glExtensionTextureFilterAnisotropic ) {
  15022. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  15023. }
  15024. if ( ! _glExtensionCompressedTextureS3TC ) {
  15025. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  15026. }
  15027. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15028. _gl.getShaderPrecisionFormat = function() {
  15029. return {
  15030. "rangeMin" : 1,
  15031. "rangeMax" : 1,
  15032. "precision" : 1
  15033. };
  15034. }
  15035. }
  15036. };
  15037. function setDefaultGLState () {
  15038. _gl.clearColor( 0, 0, 0, 1 );
  15039. _gl.clearDepth( 1 );
  15040. _gl.clearStencil( 0 );
  15041. _gl.enable( _gl.DEPTH_TEST );
  15042. _gl.depthFunc( _gl.LEQUAL );
  15043. _gl.frontFace( _gl.CCW );
  15044. _gl.cullFace( _gl.BACK );
  15045. _gl.enable( _gl.CULL_FACE );
  15046. _gl.enable( _gl.BLEND );
  15047. _gl.blendEquation( _gl.FUNC_ADD );
  15048. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  15049. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  15050. };
  15051. // default plugins (order is important)
  15052. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  15053. this.addPrePlugin( this.shadowMapPlugin );
  15054. this.addPostPlugin( new THREE.SpritePlugin() );
  15055. this.addPostPlugin( new THREE.LensFlarePlugin() );
  15056. };
  15057. /**
  15058. * @author szimek / https://github.com/szimek/
  15059. * @author alteredq / http://alteredqualia.com/
  15060. */
  15061. THREE.WebGLRenderTarget = function ( width, height, options ) {
  15062. THREE.EventDispatcher.call( this );
  15063. this.width = width;
  15064. this.height = height;
  15065. options = options || {};
  15066. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  15067. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  15068. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  15069. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  15070. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  15071. this.offset = new THREE.Vector2( 0, 0 );
  15072. this.repeat = new THREE.Vector2( 1, 1 );
  15073. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  15074. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  15075. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  15076. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  15077. this.generateMipmaps = true;
  15078. this.shareDepthFrom = null;
  15079. };
  15080. THREE.WebGLRenderTarget.prototype.clone = function() {
  15081. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  15082. tmp.wrapS = this.wrapS;
  15083. tmp.wrapT = this.wrapT;
  15084. tmp.magFilter = this.magFilter;
  15085. tmp.minFilter = this.minFilter;
  15086. tmp.anisotropy = this.anisotropy;
  15087. tmp.offset.copy( this.offset );
  15088. tmp.repeat.copy( this.repeat );
  15089. tmp.format = this.format;
  15090. tmp.type = this.type;
  15091. tmp.depthBuffer = this.depthBuffer;
  15092. tmp.stencilBuffer = this.stencilBuffer;
  15093. tmp.generateMipmaps = this.generateMipmaps;
  15094. tmp.shareDepthFrom = this.shareDepthFrom;
  15095. return tmp;
  15096. };
  15097. THREE.WebGLRenderTarget.prototype.dispose = function () {
  15098. this.dispatchEvent( { type: 'dispose' } );
  15099. };
  15100. /**
  15101. * @author alteredq / http://alteredqualia.com
  15102. */
  15103. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  15104. THREE.WebGLRenderTarget.call( this, width, height, options );
  15105. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  15106. };
  15107. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  15108. /**
  15109. * @author mrdoob / http://mrdoob.com/
  15110. */
  15111. THREE.RenderableVertex = function () {
  15112. this.positionWorld = new THREE.Vector3();
  15113. this.positionScreen = new THREE.Vector4();
  15114. this.visible = true;
  15115. };
  15116. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  15117. this.positionWorld.copy( vertex.positionWorld );
  15118. this.positionScreen.copy( vertex.positionScreen );
  15119. };
  15120. /**
  15121. * @author mrdoob / http://mrdoob.com/
  15122. */
  15123. THREE.RenderableFace3 = function () {
  15124. this.v1 = new THREE.RenderableVertex();
  15125. this.v2 = new THREE.RenderableVertex();
  15126. this.v3 = new THREE.RenderableVertex();
  15127. this.centroidModel = new THREE.Vector3();
  15128. this.normalModel = new THREE.Vector3();
  15129. this.normalModelView = new THREE.Vector3();
  15130. this.vertexNormalsLength = 0;
  15131. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15132. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15133. this.color = null;
  15134. this.material = null;
  15135. this.uvs = [[]];
  15136. this.z = null;
  15137. };
  15138. /**
  15139. * @author mrdoob / http://mrdoob.com/
  15140. */
  15141. THREE.RenderableFace4 = function () {
  15142. this.v1 = new THREE.RenderableVertex();
  15143. this.v2 = new THREE.RenderableVertex();
  15144. this.v3 = new THREE.RenderableVertex();
  15145. this.v4 = new THREE.RenderableVertex();
  15146. this.centroidModel = new THREE.Vector3();
  15147. this.normalModel = new THREE.Vector3();
  15148. this.normalModelView = new THREE.Vector3();
  15149. this.vertexNormalsLength = 0;
  15150. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15151. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15152. this.color = null;
  15153. this.material = null;
  15154. this.uvs = [[]];
  15155. this.z = null;
  15156. };
  15157. /**
  15158. * @author mrdoob / http://mrdoob.com/
  15159. */
  15160. THREE.RenderableObject = function () {
  15161. this.object = null;
  15162. this.z = null;
  15163. };
  15164. /**
  15165. * @author mrdoob / http://mrdoob.com/
  15166. */
  15167. THREE.RenderableParticle = function () {
  15168. this.object = null;
  15169. this.x = null;
  15170. this.y = null;
  15171. this.z = null;
  15172. this.rotation = null;
  15173. this.scale = new THREE.Vector2();
  15174. this.material = null;
  15175. };
  15176. /**
  15177. * @author mrdoob / http://mrdoob.com/
  15178. */
  15179. THREE.RenderableLine = function () {
  15180. this.z = null;
  15181. this.v1 = new THREE.RenderableVertex();
  15182. this.v2 = new THREE.RenderableVertex();
  15183. this.material = null;
  15184. };
  15185. /**
  15186. * @author alteredq / http://alteredqualia.com/
  15187. */
  15188. THREE.ColorUtils = {
  15189. adjustHSV : function ( color, h, s, v ) {
  15190. var hsv = THREE.ColorUtils.__hsv;
  15191. color.getHSV( hsv );
  15192. hsv.h = THREE.Math.clamp( hsv.h + h, 0, 1 );
  15193. hsv.s = THREE.Math.clamp( hsv.s + s, 0, 1 );
  15194. hsv.v = THREE.Math.clamp( hsv.v + v, 0, 1 );
  15195. color.setHSV( hsv.h, hsv.s, hsv.v );
  15196. }
  15197. };
  15198. THREE.ColorUtils.__hsv = { h: 0, s: 0, v: 0 };/**
  15199. * @author mrdoob / http://mrdoob.com/
  15200. * @author alteredq / http://alteredqualia.com/
  15201. */
  15202. THREE.GeometryUtils = {
  15203. // Merge two geometries or geometry and geometry from object (using object's transform)
  15204. merge: function ( geometry1, object2 /* mesh | geometry */ ) {
  15205. var matrix, normalMatrix,
  15206. vertexOffset = geometry1.vertices.length,
  15207. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  15208. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  15209. vertices1 = geometry1.vertices,
  15210. vertices2 = geometry2.vertices,
  15211. faces1 = geometry1.faces,
  15212. faces2 = geometry2.faces,
  15213. uvs1 = geometry1.faceVertexUvs[ 0 ],
  15214. uvs2 = geometry2.faceVertexUvs[ 0 ];
  15215. if ( object2 instanceof THREE.Mesh ) {
  15216. object2.matrixAutoUpdate && object2.updateMatrix();
  15217. matrix = object2.matrix;
  15218. normalMatrix = new THREE.Matrix3();
  15219. normalMatrix.getInverse( matrix );
  15220. normalMatrix.transpose();
  15221. }
  15222. // vertices
  15223. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  15224. var vertex = vertices2[ i ];
  15225. var vertexCopy = vertex.clone();
  15226. if ( matrix ) vertexCopy.applyMatrix4( matrix );
  15227. vertices1.push( vertexCopy );
  15228. }
  15229. // faces
  15230. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  15231. var face = faces2[ i ], faceCopy, normal, color,
  15232. faceVertexNormals = face.vertexNormals,
  15233. faceVertexColors = face.vertexColors;
  15234. if ( face instanceof THREE.Face3 ) {
  15235. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  15236. } else if ( face instanceof THREE.Face4 ) {
  15237. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  15238. }
  15239. faceCopy.normal.copy( face.normal );
  15240. if ( normalMatrix ) {
  15241. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  15242. }
  15243. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  15244. normal = faceVertexNormals[ j ].clone();
  15245. if ( normalMatrix ) {
  15246. normal.applyMatrix3( normalMatrix ).normalize();
  15247. }
  15248. faceCopy.vertexNormals.push( normal );
  15249. }
  15250. faceCopy.color.copy( face.color );
  15251. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  15252. color = faceVertexColors[ j ];
  15253. faceCopy.vertexColors.push( color.clone() );
  15254. }
  15255. faceCopy.materialIndex = face.materialIndex;
  15256. faceCopy.centroid.copy( face.centroid );
  15257. if ( matrix ) {
  15258. faceCopy.centroid.applyMatrix4( matrix );
  15259. }
  15260. faces1.push( faceCopy );
  15261. }
  15262. // uvs
  15263. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  15264. var uv = uvs2[ i ], uvCopy = [];
  15265. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  15266. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  15267. }
  15268. uvs1.push( uvCopy );
  15269. }
  15270. },
  15271. removeMaterials: function ( geometry, materialIndexArray ) {
  15272. var materialIndexMap = {};
  15273. for ( var i = 0, il = materialIndexArray.length; i < il; i ++ ) {
  15274. materialIndexMap[ materialIndexArray[i] ] = true;
  15275. }
  15276. var face, newFaces = [];
  15277. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15278. face = geometry.faces[ i ];
  15279. if ( ! ( face.materialIndex in materialIndexMap ) ) newFaces.push( face );
  15280. }
  15281. geometry.faces = newFaces;
  15282. },
  15283. // Get random point in triangle (via barycentric coordinates)
  15284. // (uniform distribution)
  15285. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  15286. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  15287. var a, b, c,
  15288. point = new THREE.Vector3(),
  15289. tmp = THREE.GeometryUtils.__v1;
  15290. a = THREE.GeometryUtils.random();
  15291. b = THREE.GeometryUtils.random();
  15292. if ( ( a + b ) > 1 ) {
  15293. a = 1 - a;
  15294. b = 1 - b;
  15295. }
  15296. c = 1 - a - b;
  15297. point.copy( vectorA );
  15298. point.multiplyScalar( a );
  15299. tmp.copy( vectorB );
  15300. tmp.multiplyScalar( b );
  15301. point.add( tmp );
  15302. tmp.copy( vectorC );
  15303. tmp.multiplyScalar( c );
  15304. point.add( tmp );
  15305. return point;
  15306. },
  15307. // Get random point in face (triangle / quad)
  15308. // (uniform distribution)
  15309. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  15310. var vA, vB, vC, vD;
  15311. if ( face instanceof THREE.Face3 ) {
  15312. vA = geometry.vertices[ face.a ];
  15313. vB = geometry.vertices[ face.b ];
  15314. vC = geometry.vertices[ face.c ];
  15315. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  15316. } else if ( face instanceof THREE.Face4 ) {
  15317. vA = geometry.vertices[ face.a ];
  15318. vB = geometry.vertices[ face.b ];
  15319. vC = geometry.vertices[ face.c ];
  15320. vD = geometry.vertices[ face.d ];
  15321. var area1, area2;
  15322. if ( useCachedAreas ) {
  15323. if ( face._area1 && face._area2 ) {
  15324. area1 = face._area1;
  15325. area2 = face._area2;
  15326. } else {
  15327. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  15328. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15329. face._area1 = area1;
  15330. face._area2 = area2;
  15331. }
  15332. } else {
  15333. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  15334. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15335. }
  15336. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  15337. if ( r < area1 ) {
  15338. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  15339. } else {
  15340. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  15341. }
  15342. }
  15343. },
  15344. // Get uniformly distributed random points in mesh
  15345. // - create array with cumulative sums of face areas
  15346. // - pick random number from 0 to total area
  15347. // - find corresponding place in area array by binary search
  15348. // - get random point in face
  15349. randomPointsInGeometry: function ( geometry, n ) {
  15350. var face, i,
  15351. faces = geometry.faces,
  15352. vertices = geometry.vertices,
  15353. il = faces.length,
  15354. totalArea = 0,
  15355. cumulativeAreas = [],
  15356. vA, vB, vC, vD;
  15357. // precompute face areas
  15358. for ( i = 0; i < il; i ++ ) {
  15359. face = faces[ i ];
  15360. if ( face instanceof THREE.Face3 ) {
  15361. vA = vertices[ face.a ];
  15362. vB = vertices[ face.b ];
  15363. vC = vertices[ face.c ];
  15364. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  15365. } else if ( face instanceof THREE.Face4 ) {
  15366. vA = vertices[ face.a ];
  15367. vB = vertices[ face.b ];
  15368. vC = vertices[ face.c ];
  15369. vD = vertices[ face.d ];
  15370. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  15371. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15372. face._area = face._area1 + face._area2;
  15373. }
  15374. totalArea += face._area;
  15375. cumulativeAreas[ i ] = totalArea;
  15376. }
  15377. // binary search cumulative areas array
  15378. function binarySearchIndices( value ) {
  15379. function binarySearch( start, end ) {
  15380. // return closest larger index
  15381. // if exact number is not found
  15382. if ( end < start )
  15383. return start;
  15384. var mid = start + Math.floor( ( end - start ) / 2 );
  15385. if ( cumulativeAreas[ mid ] > value ) {
  15386. return binarySearch( start, mid - 1 );
  15387. } else if ( cumulativeAreas[ mid ] < value ) {
  15388. return binarySearch( mid + 1, end );
  15389. } else {
  15390. return mid;
  15391. }
  15392. }
  15393. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  15394. return result;
  15395. }
  15396. // pick random face weighted by face area
  15397. var r, index,
  15398. result = [];
  15399. var stats = {};
  15400. for ( i = 0; i < n; i ++ ) {
  15401. r = THREE.GeometryUtils.random() * totalArea;
  15402. index = binarySearchIndices( r );
  15403. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  15404. if ( ! stats[ index ] ) {
  15405. stats[ index ] = 1;
  15406. } else {
  15407. stats[ index ] += 1;
  15408. }
  15409. }
  15410. return result;
  15411. },
  15412. // Get triangle area (half of parallelogram)
  15413. // http://mathworld.wolfram.com/TriangleArea.html
  15414. triangleArea: function ( vectorA, vectorB, vectorC ) {
  15415. var tmp1 = THREE.GeometryUtils.__v1,
  15416. tmp2 = THREE.GeometryUtils.__v2;
  15417. tmp1.subVectors( vectorB, vectorA );
  15418. tmp2.subVectors( vectorC, vectorA );
  15419. tmp1.cross( tmp2 );
  15420. return 0.5 * tmp1.length();
  15421. },
  15422. // Center geometry so that 0,0,0 is in center of bounding box
  15423. center: function ( geometry ) {
  15424. geometry.computeBoundingBox();
  15425. var bb = geometry.boundingBox;
  15426. var offset = new THREE.Vector3();
  15427. offset.addVectors( bb.min, bb.max );
  15428. offset.multiplyScalar( -0.5 );
  15429. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  15430. geometry.computeBoundingBox();
  15431. return offset;
  15432. },
  15433. // Normalize UVs to be from <0,1>
  15434. // (for now just the first set of UVs)
  15435. normalizeUVs: function ( geometry ) {
  15436. var uvSet = geometry.faceVertexUvs[ 0 ];
  15437. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  15438. var uvs = uvSet[ i ];
  15439. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  15440. // texture repeat
  15441. if( uvs[ j ].x !== 1.0 ) uvs[ j ].x = uvs[ j ].x - Math.floor( uvs[ j ].x );
  15442. if( uvs[ j ].y !== 1.0 ) uvs[ j ].y = uvs[ j ].y - Math.floor( uvs[ j ].y );
  15443. }
  15444. }
  15445. },
  15446. triangulateQuads: function ( geometry ) {
  15447. var i, il, j, jl;
  15448. var faces = [];
  15449. var faceUvs = [];
  15450. var faceVertexUvs = [];
  15451. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  15452. faceUvs[ i ] = [];
  15453. }
  15454. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  15455. faceVertexUvs[ i ] = [];
  15456. }
  15457. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15458. var face = geometry.faces[ i ];
  15459. if ( face instanceof THREE.Face4 ) {
  15460. var a = face.a;
  15461. var b = face.b;
  15462. var c = face.c;
  15463. var d = face.d;
  15464. var triA = new THREE.Face3();
  15465. var triB = new THREE.Face3();
  15466. triA.color.copy( face.color );
  15467. triB.color.copy( face.color );
  15468. triA.materialIndex = face.materialIndex;
  15469. triB.materialIndex = face.materialIndex;
  15470. triA.a = a;
  15471. triA.b = b;
  15472. triA.c = d;
  15473. triB.a = b;
  15474. triB.b = c;
  15475. triB.c = d;
  15476. if ( face.vertexColors.length === 4 ) {
  15477. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  15478. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  15479. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  15480. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  15481. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  15482. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  15483. }
  15484. faces.push( triA, triB );
  15485. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15486. if ( geometry.faceVertexUvs[ j ].length ) {
  15487. var uvs = geometry.faceVertexUvs[ j ][ i ];
  15488. var uvA = uvs[ 0 ];
  15489. var uvB = uvs[ 1 ];
  15490. var uvC = uvs[ 2 ];
  15491. var uvD = uvs[ 3 ];
  15492. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  15493. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  15494. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  15495. }
  15496. }
  15497. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  15498. if ( geometry.faceUvs[ j ].length ) {
  15499. var faceUv = geometry.faceUvs[ j ][ i ];
  15500. faceUvs[ j ].push( faceUv, faceUv );
  15501. }
  15502. }
  15503. } else {
  15504. faces.push( face );
  15505. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  15506. faceUvs[ j ].push( geometry.faceUvs[ j ][ i ] );
  15507. }
  15508. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15509. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  15510. }
  15511. }
  15512. }
  15513. geometry.faces = faces;
  15514. geometry.faceUvs = faceUvs;
  15515. geometry.faceVertexUvs = faceVertexUvs;
  15516. geometry.computeCentroids();
  15517. geometry.computeFaceNormals();
  15518. geometry.computeVertexNormals();
  15519. if ( geometry.hasTangents ) geometry.computeTangents();
  15520. },
  15521. setMaterialIndex: function ( geometry, index, startFace, endFace ){
  15522. var faces = geometry.faces;
  15523. var start = startFace || 0;
  15524. var end = endFace || faces.length - 1;
  15525. for ( var i = start; i <= end; i ++ ) {
  15526. faces[i].materialIndex = index;
  15527. }
  15528. }
  15529. };
  15530. THREE.GeometryUtils.random = THREE.Math.random16;
  15531. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  15532. THREE.GeometryUtils.__v2 = new THREE.Vector3();
  15533. /**
  15534. * @author alteredq / http://alteredqualia.com/
  15535. * @author mrdoob / http://mrdoob.com/
  15536. */
  15537. THREE.ImageUtils = {
  15538. crossOrigin: 'anonymous',
  15539. loadTexture: function ( url, mapping, onLoad, onError ) {
  15540. var image = new Image();
  15541. var texture = new THREE.Texture( image, mapping );
  15542. var loader = new THREE.ImageLoader();
  15543. loader.addEventListener( 'load', function ( event ) {
  15544. texture.image = event.content;
  15545. texture.needsUpdate = true;
  15546. if ( onLoad ) onLoad( texture );
  15547. } );
  15548. loader.addEventListener( 'error', function ( event ) {
  15549. if ( onError ) onError( event.message );
  15550. } );
  15551. loader.crossOrigin = this.crossOrigin;
  15552. loader.load( url, image );
  15553. texture.sourceFile = url;
  15554. return texture;
  15555. },
  15556. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  15557. var texture = new THREE.CompressedTexture();
  15558. texture.mapping = mapping;
  15559. var request = new XMLHttpRequest();
  15560. request.onload = function () {
  15561. var buffer = request.response;
  15562. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15563. texture.format = dds.format;
  15564. texture.mipmaps = dds.mipmaps;
  15565. texture.image.width = dds.width;
  15566. texture.image.height = dds.height;
  15567. // gl.generateMipmap fails for compressed textures
  15568. // mipmaps must be embedded in the DDS file
  15569. // or texture filters must not use mipmapping
  15570. texture.generateMipmaps = false;
  15571. texture.needsUpdate = true;
  15572. if ( onLoad ) onLoad( texture );
  15573. }
  15574. request.onerror = onError;
  15575. request.open( 'GET', url, true );
  15576. request.responseType = "arraybuffer";
  15577. request.send( null );
  15578. return texture;
  15579. },
  15580. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  15581. var images = [];
  15582. images.loadCount = 0;
  15583. var texture = new THREE.Texture();
  15584. texture.image = images;
  15585. if ( mapping !== undefined ) texture.mapping = mapping;
  15586. // no flipping needed for cube textures
  15587. texture.flipY = false;
  15588. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15589. var cubeImage = new Image();
  15590. images[ i ] = cubeImage;
  15591. cubeImage.onload = function () {
  15592. images.loadCount += 1;
  15593. if ( images.loadCount === 6 ) {
  15594. texture.needsUpdate = true;
  15595. if ( onLoad ) onLoad( texture );
  15596. }
  15597. };
  15598. cubeImage.onerror = onError;
  15599. cubeImage.crossOrigin = this.crossOrigin;
  15600. cubeImage.src = array[ i ];
  15601. }
  15602. return texture;
  15603. },
  15604. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  15605. var images = [];
  15606. images.loadCount = 0;
  15607. var texture = new THREE.CompressedTexture();
  15608. texture.image = images;
  15609. if ( mapping !== undefined ) texture.mapping = mapping;
  15610. // no flipping for cube textures
  15611. // (also flipping doesn't work for compressed textures )
  15612. texture.flipY = false;
  15613. // can't generate mipmaps for compressed textures
  15614. // mips must be embedded in DDS files
  15615. texture.generateMipmaps = false;
  15616. var generateCubeFaceCallback = function ( rq, img ) {
  15617. return function () {
  15618. var buffer = rq.response;
  15619. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15620. img.format = dds.format;
  15621. img.mipmaps = dds.mipmaps;
  15622. img.width = dds.width;
  15623. img.height = dds.height;
  15624. images.loadCount += 1;
  15625. if ( images.loadCount === 6 ) {
  15626. texture.format = dds.format;
  15627. texture.needsUpdate = true;
  15628. if ( onLoad ) onLoad( texture );
  15629. }
  15630. }
  15631. }
  15632. // compressed cubemap textures as 6 separate DDS files
  15633. if ( array instanceof Array ) {
  15634. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15635. var cubeImage = {};
  15636. images[ i ] = cubeImage;
  15637. var request = new XMLHttpRequest();
  15638. request.onload = generateCubeFaceCallback( request, cubeImage );
  15639. request.onerror = onError;
  15640. var url = array[ i ];
  15641. request.open( 'GET', url, true );
  15642. request.responseType = "arraybuffer";
  15643. request.send( null );
  15644. }
  15645. // compressed cubemap texture stored in a single DDS file
  15646. } else {
  15647. var url = array;
  15648. var request = new XMLHttpRequest();
  15649. request.onload = function( ) {
  15650. var buffer = request.response;
  15651. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15652. if ( dds.isCubemap ) {
  15653. var faces = dds.mipmaps.length / dds.mipmapCount;
  15654. for ( var f = 0; f < faces; f ++ ) {
  15655. images[ f ] = { mipmaps : [] };
  15656. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15657. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  15658. images[ f ].format = dds.format;
  15659. images[ f ].width = dds.width;
  15660. images[ f ].height = dds.height;
  15661. }
  15662. }
  15663. texture.format = dds.format;
  15664. texture.needsUpdate = true;
  15665. if ( onLoad ) onLoad( texture );
  15666. }
  15667. }
  15668. request.onerror = onError;
  15669. request.open( 'GET', url, true );
  15670. request.responseType = "arraybuffer";
  15671. request.send( null );
  15672. }
  15673. return texture;
  15674. },
  15675. parseDDS: function ( buffer, loadMipmaps ) {
  15676. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  15677. // Adapted from @toji's DDS utils
  15678. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  15679. // All values and structures referenced from:
  15680. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  15681. var DDS_MAGIC = 0x20534444;
  15682. var DDSD_CAPS = 0x1,
  15683. DDSD_HEIGHT = 0x2,
  15684. DDSD_WIDTH = 0x4,
  15685. DDSD_PITCH = 0x8,
  15686. DDSD_PIXELFORMAT = 0x1000,
  15687. DDSD_MIPMAPCOUNT = 0x20000,
  15688. DDSD_LINEARSIZE = 0x80000,
  15689. DDSD_DEPTH = 0x800000;
  15690. var DDSCAPS_COMPLEX = 0x8,
  15691. DDSCAPS_MIPMAP = 0x400000,
  15692. DDSCAPS_TEXTURE = 0x1000;
  15693. var DDSCAPS2_CUBEMAP = 0x200,
  15694. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  15695. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  15696. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  15697. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  15698. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  15699. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  15700. DDSCAPS2_VOLUME = 0x200000;
  15701. var DDPF_ALPHAPIXELS = 0x1,
  15702. DDPF_ALPHA = 0x2,
  15703. DDPF_FOURCC = 0x4,
  15704. DDPF_RGB = 0x40,
  15705. DDPF_YUV = 0x200,
  15706. DDPF_LUMINANCE = 0x20000;
  15707. function fourCCToInt32( value ) {
  15708. return value.charCodeAt(0) +
  15709. (value.charCodeAt(1) << 8) +
  15710. (value.charCodeAt(2) << 16) +
  15711. (value.charCodeAt(3) << 24);
  15712. }
  15713. function int32ToFourCC( value ) {
  15714. return String.fromCharCode(
  15715. value & 0xff,
  15716. (value >> 8) & 0xff,
  15717. (value >> 16) & 0xff,
  15718. (value >> 24) & 0xff
  15719. );
  15720. }
  15721. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  15722. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  15723. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  15724. var headerLengthInt = 31; // The header length in 32 bit ints
  15725. // Offsets into the header array
  15726. var off_magic = 0;
  15727. var off_size = 1;
  15728. var off_flags = 2;
  15729. var off_height = 3;
  15730. var off_width = 4;
  15731. var off_mipmapCount = 7;
  15732. var off_pfFlags = 20;
  15733. var off_pfFourCC = 21;
  15734. var off_caps = 27;
  15735. var off_caps2 = 28;
  15736. var off_caps3 = 29;
  15737. var off_caps4 = 30;
  15738. // Parse header
  15739. var header = new Int32Array( buffer, 0, headerLengthInt );
  15740. if ( header[ off_magic ] !== DDS_MAGIC ) {
  15741. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  15742. return dds;
  15743. }
  15744. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  15745. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  15746. return dds;
  15747. }
  15748. var blockBytes;
  15749. var fourCC = header[ off_pfFourCC ];
  15750. switch ( fourCC ) {
  15751. case FOURCC_DXT1:
  15752. blockBytes = 8;
  15753. dds.format = THREE.RGB_S3TC_DXT1_Format;
  15754. break;
  15755. case FOURCC_DXT3:
  15756. blockBytes = 16;
  15757. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  15758. break;
  15759. case FOURCC_DXT5:
  15760. blockBytes = 16;
  15761. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  15762. break;
  15763. default:
  15764. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  15765. return dds;
  15766. }
  15767. dds.mipmapCount = 1;
  15768. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  15769. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  15770. }
  15771. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  15772. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  15773. dds.width = header[ off_width ];
  15774. dds.height = header[ off_height ];
  15775. var dataOffset = header[ off_size ] + 4;
  15776. // Extract mipmaps buffers
  15777. var width = dds.width;
  15778. var height = dds.height;
  15779. var faces = dds.isCubemap ? 6 : 1;
  15780. for ( var face = 0; face < faces; face ++ ) {
  15781. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15782. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  15783. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  15784. var mipmap = { "data": byteArray, "width": width, "height": height };
  15785. dds.mipmaps.push( mipmap );
  15786. dataOffset += dataLength;
  15787. width = Math.max( width * 0.5, 1 );
  15788. height = Math.max( height * 0.5, 1 );
  15789. }
  15790. width = dds.width;
  15791. height = dds.height;
  15792. }
  15793. return dds;
  15794. },
  15795. getNormalMap: function ( image, depth ) {
  15796. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  15797. var cross = function ( a, b ) {
  15798. 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 ] ];
  15799. }
  15800. var subtract = function ( a, b ) {
  15801. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  15802. }
  15803. var normalize = function ( a ) {
  15804. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  15805. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  15806. }
  15807. depth = depth | 1;
  15808. var width = image.width;
  15809. var height = image.height;
  15810. var canvas = document.createElement( 'canvas' );
  15811. canvas.width = width;
  15812. canvas.height = height;
  15813. var context = canvas.getContext( '2d' );
  15814. context.drawImage( image, 0, 0 );
  15815. var data = context.getImageData( 0, 0, width, height ).data;
  15816. var imageData = context.createImageData( width, height );
  15817. var output = imageData.data;
  15818. for ( var x = 0; x < width; x ++ ) {
  15819. for ( var y = 0; y < height; y ++ ) {
  15820. var ly = y - 1 < 0 ? 0 : y - 1;
  15821. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  15822. var lx = x - 1 < 0 ? 0 : x - 1;
  15823. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  15824. var points = [];
  15825. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  15826. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  15827. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  15828. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  15829. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  15830. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  15831. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  15832. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  15833. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  15834. var normals = [];
  15835. var num_points = points.length;
  15836. for ( var i = 0; i < num_points; i ++ ) {
  15837. var v1 = points[ i ];
  15838. var v2 = points[ ( i + 1 ) % num_points ];
  15839. v1 = subtract( v1, origin );
  15840. v2 = subtract( v2, origin );
  15841. normals.push( normalize( cross( v1, v2 ) ) );
  15842. }
  15843. var normal = [ 0, 0, 0 ];
  15844. for ( var i = 0; i < normals.length; i ++ ) {
  15845. normal[ 0 ] += normals[ i ][ 0 ];
  15846. normal[ 1 ] += normals[ i ][ 1 ];
  15847. normal[ 2 ] += normals[ i ][ 2 ];
  15848. }
  15849. normal[ 0 ] /= normals.length;
  15850. normal[ 1 ] /= normals.length;
  15851. normal[ 2 ] /= normals.length;
  15852. var idx = ( y * width + x ) * 4;
  15853. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15854. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15855. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  15856. output[ idx + 3 ] = 255;
  15857. }
  15858. }
  15859. context.putImageData( imageData, 0, 0 );
  15860. return canvas;
  15861. },
  15862. generateDataTexture: function ( width, height, color ) {
  15863. var size = width * height;
  15864. var data = new Uint8Array( 3 * size );
  15865. var r = Math.floor( color.r * 255 );
  15866. var g = Math.floor( color.g * 255 );
  15867. var b = Math.floor( color.b * 255 );
  15868. for ( var i = 0; i < size; i ++ ) {
  15869. data[ i * 3 ] = r;
  15870. data[ i * 3 + 1 ] = g;
  15871. data[ i * 3 + 2 ] = b;
  15872. }
  15873. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  15874. texture.needsUpdate = true;
  15875. return texture;
  15876. }
  15877. };
  15878. /**
  15879. * @author alteredq / http://alteredqualia.com/
  15880. */
  15881. THREE.SceneUtils = {
  15882. createMultiMaterialObject: function ( geometry, materials ) {
  15883. var group = new THREE.Object3D();
  15884. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  15885. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  15886. }
  15887. return group;
  15888. },
  15889. detach : function ( child, parent, scene ) {
  15890. child.applyMatrix( parent.matrixWorld );
  15891. parent.remove( child );
  15892. scene.add( child );
  15893. },
  15894. attach: function ( child, scene, parent ) {
  15895. var matrixWorldInverse = new THREE.Matrix4();
  15896. matrixWorldInverse.getInverse( parent.matrixWorld );
  15897. child.applyMatrix( matrixWorldInverse );
  15898. scene.remove( child );
  15899. parent.add( child );
  15900. }
  15901. };
  15902. /**
  15903. * @author zz85 / http://www.lab4games.net/zz85/blog
  15904. * @author alteredq / http://alteredqualia.com/
  15905. *
  15906. * For Text operations in three.js (See TextGeometry)
  15907. *
  15908. * It uses techniques used in:
  15909. *
  15910. * typeface.js and canvastext
  15911. * For converting fonts and rendering with javascript
  15912. * http://typeface.neocracy.org
  15913. *
  15914. * Triangulation ported from AS3
  15915. * Simple Polygon Triangulation
  15916. * http://actionsnippet.com/?p=1462
  15917. *
  15918. * A Method to triangulate shapes with holes
  15919. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  15920. *
  15921. */
  15922. THREE.FontUtils = {
  15923. faces : {},
  15924. // Just for now. face[weight][style]
  15925. face : "helvetiker",
  15926. weight: "normal",
  15927. style : "normal",
  15928. size : 150,
  15929. divisions : 10,
  15930. getFace : function() {
  15931. return this.faces[ this.face ][ this.weight ][ this.style ];
  15932. },
  15933. loadFace : function( data ) {
  15934. var family = data.familyName.toLowerCase();
  15935. var ThreeFont = this;
  15936. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  15937. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  15938. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15939. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15940. return data;
  15941. },
  15942. drawText : function( text ) {
  15943. var characterPts = [], allPts = [];
  15944. // RenderText
  15945. var i, p,
  15946. face = this.getFace(),
  15947. scale = this.size / face.resolution,
  15948. offset = 0,
  15949. chars = String( text ).split( '' ),
  15950. length = chars.length;
  15951. var fontPaths = [];
  15952. for ( i = 0; i < length; i ++ ) {
  15953. var path = new THREE.Path();
  15954. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  15955. offset += ret.offset;
  15956. fontPaths.push( ret.path );
  15957. }
  15958. // get the width
  15959. var width = offset / 2;
  15960. //
  15961. // for ( p = 0; p < allPts.length; p++ ) {
  15962. //
  15963. // allPts[ p ].x -= width;
  15964. //
  15965. // }
  15966. //var extract = this.extractPoints( allPts, characterPts );
  15967. //extract.contour = allPts;
  15968. //extract.paths = fontPaths;
  15969. //extract.offset = width;
  15970. return { paths : fontPaths, offset : width };
  15971. },
  15972. extractGlyphPoints : function( c, face, scale, offset, path ) {
  15973. var pts = [];
  15974. var i, i2, divisions,
  15975. outline, action, length,
  15976. scaleX, scaleY,
  15977. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  15978. laste,
  15979. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  15980. if ( !glyph ) return;
  15981. if ( glyph.o ) {
  15982. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  15983. length = outline.length;
  15984. scaleX = scale;
  15985. scaleY = scale;
  15986. for ( i = 0; i < length; ) {
  15987. action = outline[ i ++ ];
  15988. //console.log( action );
  15989. switch( action ) {
  15990. case 'm':
  15991. // Move To
  15992. x = outline[ i++ ] * scaleX + offset;
  15993. y = outline[ i++ ] * scaleY;
  15994. path.moveTo( x, y );
  15995. break;
  15996. case 'l':
  15997. // Line To
  15998. x = outline[ i++ ] * scaleX + offset;
  15999. y = outline[ i++ ] * scaleY;
  16000. path.lineTo(x,y);
  16001. break;
  16002. case 'q':
  16003. // QuadraticCurveTo
  16004. cpx = outline[ i++ ] * scaleX + offset;
  16005. cpy = outline[ i++ ] * scaleY;
  16006. cpx1 = outline[ i++ ] * scaleX + offset;
  16007. cpy1 = outline[ i++ ] * scaleY;
  16008. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  16009. laste = pts[ pts.length - 1 ];
  16010. if ( laste ) {
  16011. cpx0 = laste.x;
  16012. cpy0 = laste.y;
  16013. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16014. var t = i2 / divisions;
  16015. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16016. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16017. }
  16018. }
  16019. break;
  16020. case 'b':
  16021. // Cubic Bezier Curve
  16022. cpx = outline[ i++ ] * scaleX + offset;
  16023. cpy = outline[ i++ ] * scaleY;
  16024. cpx1 = outline[ i++ ] * scaleX + offset;
  16025. cpy1 = outline[ i++ ] * -scaleY;
  16026. cpx2 = outline[ i++ ] * scaleX + offset;
  16027. cpy2 = outline[ i++ ] * -scaleY;
  16028. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  16029. laste = pts[ pts.length - 1 ];
  16030. if ( laste ) {
  16031. cpx0 = laste.x;
  16032. cpy0 = laste.y;
  16033. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16034. var t = i2 / divisions;
  16035. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16036. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16037. }
  16038. }
  16039. break;
  16040. }
  16041. }
  16042. }
  16043. return { offset: glyph.ha*scale, path:path};
  16044. }
  16045. };
  16046. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16047. // Parameters
  16048. parameters = parameters || {};
  16049. var size = parameters.size !== undefined ? parameters.size : 100;
  16050. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16051. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16052. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16053. var style = parameters.style !== undefined ? parameters.style : "normal";
  16054. THREE.FontUtils.size = size;
  16055. THREE.FontUtils.divisions = curveSegments;
  16056. THREE.FontUtils.face = font;
  16057. THREE.FontUtils.weight = weight;
  16058. THREE.FontUtils.style = style;
  16059. // Get a Font data json object
  16060. var data = THREE.FontUtils.drawText( text );
  16061. var paths = data.paths;
  16062. var shapes = [];
  16063. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16064. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16065. }
  16066. return shapes;
  16067. };
  16068. /**
  16069. * This code is a quick port of code written in C++ which was submitted to
  16070. * flipcode.com by John W. Ratcliff // July 22, 2000
  16071. * See original code and more information here:
  16072. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16073. *
  16074. * ported to actionscript by Zevan Rosser
  16075. * www.actionsnippet.com
  16076. *
  16077. * ported to javascript by Joshua Koo
  16078. * http://www.lab4games.net/zz85/blog
  16079. *
  16080. */
  16081. ( function( namespace ) {
  16082. var EPSILON = 0.0000000001;
  16083. // takes in an contour array and returns
  16084. var process = function( contour, indices ) {
  16085. var n = contour.length;
  16086. if ( n < 3 ) return null;
  16087. var result = [],
  16088. verts = [],
  16089. vertIndices = [];
  16090. /* we want a counter-clockwise polygon in verts */
  16091. var u, v, w;
  16092. if ( area( contour ) > 0.0 ) {
  16093. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16094. } else {
  16095. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16096. }
  16097. var nv = n;
  16098. /* remove nv - 2 vertices, creating 1 triangle every time */
  16099. var count = 2 * nv; /* error detection */
  16100. for( v = nv - 1; nv > 2; ) {
  16101. /* if we loop, it is probably a non-simple polygon */
  16102. if ( ( count-- ) <= 0 ) {
  16103. //** Triangulate: ERROR - probable bad polygon!
  16104. //throw ( "Warning, unable to triangulate polygon!" );
  16105. //return null;
  16106. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16107. console.log( "Warning, unable to triangulate polygon!" );
  16108. if ( indices ) return vertIndices;
  16109. return result;
  16110. }
  16111. /* three consecutive vertices in current polygon, <u,v,w> */
  16112. u = v; if ( nv <= u ) u = 0; /* previous */
  16113. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16114. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16115. if ( snip( contour, u, v, w, nv, verts ) ) {
  16116. var a, b, c, s, t;
  16117. /* true names of the vertices */
  16118. a = verts[ u ];
  16119. b = verts[ v ];
  16120. c = verts[ w ];
  16121. /* output Triangle */
  16122. result.push( [ contour[ a ],
  16123. contour[ b ],
  16124. contour[ c ] ] );
  16125. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16126. /* remove v from the remaining polygon */
  16127. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  16128. verts[ s ] = verts[ t ];
  16129. }
  16130. nv--;
  16131. /* reset error detection counter */
  16132. count = 2 * nv;
  16133. }
  16134. }
  16135. if ( indices ) return vertIndices;
  16136. return result;
  16137. };
  16138. // calculate area of the contour polygon
  16139. var area = function ( contour ) {
  16140. var n = contour.length;
  16141. var a = 0.0;
  16142. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16143. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16144. }
  16145. return a * 0.5;
  16146. };
  16147. var snip = function ( contour, u, v, w, n, verts ) {
  16148. var p;
  16149. var ax, ay, bx, by;
  16150. var cx, cy, px, py;
  16151. ax = contour[ verts[ u ] ].x;
  16152. ay = contour[ verts[ u ] ].y;
  16153. bx = contour[ verts[ v ] ].x;
  16154. by = contour[ verts[ v ] ].y;
  16155. cx = contour[ verts[ w ] ].x;
  16156. cy = contour[ verts[ w ] ].y;
  16157. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16158. var aX, aY, bX, bY, cX, cY;
  16159. var apx, apy, bpx, bpy, cpx, cpy;
  16160. var cCROSSap, bCROSScp, aCROSSbp;
  16161. aX = cx - bx; aY = cy - by;
  16162. bX = ax - cx; bY = ay - cy;
  16163. cX = bx - ax; cY = by - ay;
  16164. for ( p = 0; p < n; p++ ) {
  16165. if( (p === u) || (p === v) || (p === w) ) continue;
  16166. px = contour[ verts[ p ] ].x
  16167. py = contour[ verts[ p ] ].y
  16168. apx = px - ax; apy = py - ay;
  16169. bpx = px - bx; bpy = py - by;
  16170. cpx = px - cx; cpy = py - cy;
  16171. // see if p is inside triangle abc
  16172. aCROSSbp = aX*bpy - aY*bpx;
  16173. cCROSSap = cX*apy - cY*apx;
  16174. bCROSScp = bX*cpy - bY*cpx;
  16175. if ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) ) return false;
  16176. }
  16177. return true;
  16178. };
  16179. namespace.Triangulate = process;
  16180. namespace.Triangulate.area = area;
  16181. return namespace;
  16182. })(THREE.FontUtils);
  16183. // To use the typeface.js face files, hook up the API
  16184. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };/**
  16185. * @author zz85 / http://www.lab4games.net/zz85/blog
  16186. * Extensible curve object
  16187. *
  16188. * Some common of Curve methods
  16189. * .getPoint(t), getTangent(t)
  16190. * .getPointAt(u), getTagentAt(u)
  16191. * .getPoints(), .getSpacedPoints()
  16192. * .getLength()
  16193. * .updateArcLengths()
  16194. *
  16195. * This file contains following classes:
  16196. *
  16197. * -- 2d classes --
  16198. * THREE.Curve
  16199. * THREE.LineCurve
  16200. * THREE.QuadraticBezierCurve
  16201. * THREE.CubicBezierCurve
  16202. * THREE.SplineCurve
  16203. * THREE.ArcCurve
  16204. * THREE.EllipseCurve
  16205. *
  16206. * -- 3d classes --
  16207. * THREE.LineCurve3
  16208. * THREE.QuadraticBezierCurve3
  16209. * THREE.CubicBezierCurve3
  16210. * THREE.SplineCurve3
  16211. * THREE.ClosedSplineCurve3
  16212. *
  16213. * A series of curves can be represented as a THREE.CurvePath
  16214. *
  16215. **/
  16216. /**************************************************************
  16217. * Abstract Curve base class
  16218. **************************************************************/
  16219. THREE.Curve = function () {
  16220. };
  16221. // Virtual base class method to overwrite and implement in subclasses
  16222. // - t [0 .. 1]
  16223. THREE.Curve.prototype.getPoint = function ( t ) {
  16224. console.log( "Warning, getPoint() not implemented!" );
  16225. return null;
  16226. };
  16227. // Get point at relative position in curve according to arc length
  16228. // - u [0 .. 1]
  16229. THREE.Curve.prototype.getPointAt = function ( u ) {
  16230. var t = this.getUtoTmapping( u );
  16231. return this.getPoint( t );
  16232. };
  16233. // Get sequence of points using getPoint( t )
  16234. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16235. if ( !divisions ) divisions = 5;
  16236. var d, pts = [];
  16237. for ( d = 0; d <= divisions; d ++ ) {
  16238. pts.push( this.getPoint( d / divisions ) );
  16239. }
  16240. return pts;
  16241. };
  16242. // Get sequence of points using getPointAt( u )
  16243. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16244. if ( !divisions ) divisions = 5;
  16245. var d, pts = [];
  16246. for ( d = 0; d <= divisions; d ++ ) {
  16247. pts.push( this.getPointAt( d / divisions ) );
  16248. }
  16249. return pts;
  16250. };
  16251. // Get total curve arc length
  16252. THREE.Curve.prototype.getLength = function () {
  16253. var lengths = this.getLengths();
  16254. return lengths[ lengths.length - 1 ];
  16255. };
  16256. // Get list of cumulative segment lengths
  16257. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16258. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16259. if ( this.cacheArcLengths
  16260. && ( this.cacheArcLengths.length == divisions + 1 )
  16261. && !this.needsUpdate) {
  16262. //console.log( "cached", this.cacheArcLengths );
  16263. return this.cacheArcLengths;
  16264. }
  16265. this.needsUpdate = false;
  16266. var cache = [];
  16267. var current, last = this.getPoint( 0 );
  16268. var p, sum = 0;
  16269. cache.push( 0 );
  16270. for ( p = 1; p <= divisions; p ++ ) {
  16271. current = this.getPoint ( p / divisions );
  16272. sum += current.distanceTo( last );
  16273. cache.push( sum );
  16274. last = current;
  16275. }
  16276. this.cacheArcLengths = cache;
  16277. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16278. };
  16279. THREE.Curve.prototype.updateArcLengths = function() {
  16280. this.needsUpdate = true;
  16281. this.getLengths();
  16282. };
  16283. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16284. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16285. var arcLengths = this.getLengths();
  16286. var i = 0, il = arcLengths.length;
  16287. var targetArcLength; // The targeted u distance value to get
  16288. if ( distance ) {
  16289. targetArcLength = distance;
  16290. } else {
  16291. targetArcLength = u * arcLengths[ il - 1 ];
  16292. }
  16293. //var time = Date.now();
  16294. // binary search for the index with largest value smaller than target u distance
  16295. var low = 0, high = il - 1, comparison;
  16296. while ( low <= high ) {
  16297. 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
  16298. comparison = arcLengths[ i ] - targetArcLength;
  16299. if ( comparison < 0 ) {
  16300. low = i + 1;
  16301. continue;
  16302. } else if ( comparison > 0 ) {
  16303. high = i - 1;
  16304. continue;
  16305. } else {
  16306. high = i;
  16307. break;
  16308. // DONE
  16309. }
  16310. }
  16311. i = high;
  16312. //console.log('b' , i, low, high, Date.now()- time);
  16313. if ( arcLengths[ i ] == targetArcLength ) {
  16314. var t = i / ( il - 1 );
  16315. return t;
  16316. }
  16317. // we could get finer grain at lengths, or use simple interpolatation between two points
  16318. var lengthBefore = arcLengths[ i ];
  16319. var lengthAfter = arcLengths[ i + 1 ];
  16320. var segmentLength = lengthAfter - lengthBefore;
  16321. // determine where we are between the 'before' and 'after' points
  16322. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16323. // add that fractional amount to t
  16324. var t = ( i + segmentFraction ) / ( il -1 );
  16325. return t;
  16326. };
  16327. // Returns a unit vector tangent at t
  16328. // In case any sub curve does not implement its tangent derivation,
  16329. // 2 points a small delta apart will be used to find its gradient
  16330. // which seems to give a reasonable approximation
  16331. THREE.Curve.prototype.getTangent = function( t ) {
  16332. var delta = 0.0001;
  16333. var t1 = t - delta;
  16334. var t2 = t + delta;
  16335. // Capping in case of danger
  16336. if ( t1 < 0 ) t1 = 0;
  16337. if ( t2 > 1 ) t2 = 1;
  16338. var pt1 = this.getPoint( t1 );
  16339. var pt2 = this.getPoint( t2 );
  16340. var vec = pt2.clone().sub(pt1);
  16341. return vec.normalize();
  16342. };
  16343. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16344. var t = this.getUtoTmapping( u );
  16345. return this.getTangent( t );
  16346. };
  16347. /**************************************************************
  16348. * Line
  16349. **************************************************************/
  16350. THREE.LineCurve = function ( v1, v2 ) {
  16351. this.v1 = v1;
  16352. this.v2 = v2;
  16353. };
  16354. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  16355. THREE.LineCurve.prototype.getPoint = function ( t ) {
  16356. var point = this.v2.clone().sub(this.v1);
  16357. point.multiplyScalar( t ).add( this.v1 );
  16358. return point;
  16359. };
  16360. // Line curve is linear, so we can overwrite default getPointAt
  16361. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  16362. return this.getPoint( u );
  16363. };
  16364. THREE.LineCurve.prototype.getTangent = function( t ) {
  16365. var tangent = this.v2.clone().sub(this.v1);
  16366. return tangent.normalize();
  16367. };
  16368. /**************************************************************
  16369. * Quadratic Bezier curve
  16370. **************************************************************/
  16371. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  16372. this.v0 = v0;
  16373. this.v1 = v1;
  16374. this.v2 = v2;
  16375. };
  16376. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  16377. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  16378. var tx, ty;
  16379. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  16380. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  16381. return new THREE.Vector2( tx, ty );
  16382. };
  16383. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  16384. var tx, ty;
  16385. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  16386. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  16387. // returns unit vector
  16388. var tangent = new THREE.Vector2( tx, ty );
  16389. tangent.normalize();
  16390. return tangent;
  16391. };
  16392. /**************************************************************
  16393. * Cubic Bezier curve
  16394. **************************************************************/
  16395. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  16396. this.v0 = v0;
  16397. this.v1 = v1;
  16398. this.v2 = v2;
  16399. this.v3 = v3;
  16400. };
  16401. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  16402. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  16403. var tx, ty;
  16404. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16405. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16406. return new THREE.Vector2( tx, ty );
  16407. };
  16408. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  16409. var tx, ty;
  16410. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16411. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16412. var tangent = new THREE.Vector2( tx, ty );
  16413. tangent.normalize();
  16414. return tangent;
  16415. };
  16416. /**************************************************************
  16417. * Spline curve
  16418. **************************************************************/
  16419. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  16420. this.points = (points == undefined) ? [] : points;
  16421. };
  16422. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  16423. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  16424. var v = new THREE.Vector2();
  16425. var c = [];
  16426. var points = this.points, point, intPoint, weight;
  16427. point = ( points.length - 1 ) * t;
  16428. intPoint = Math.floor( point );
  16429. weight = point - intPoint;
  16430. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16431. c[ 1 ] = intPoint;
  16432. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  16433. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  16434. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16435. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16436. return v;
  16437. };
  16438. /**************************************************************
  16439. * Ellipse curve
  16440. **************************************************************/
  16441. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  16442. aStartAngle, aEndAngle,
  16443. aClockwise ) {
  16444. this.aX = aX;
  16445. this.aY = aY;
  16446. this.xRadius = xRadius;
  16447. this.yRadius = yRadius;
  16448. this.aStartAngle = aStartAngle;
  16449. this.aEndAngle = aEndAngle;
  16450. this.aClockwise = aClockwise;
  16451. };
  16452. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  16453. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  16454. var deltaAngle = this.aEndAngle - this.aStartAngle;
  16455. if ( !this.aClockwise ) {
  16456. t = 1 - t;
  16457. }
  16458. var angle = this.aStartAngle + t * deltaAngle;
  16459. var tx = this.aX + this.xRadius * Math.cos( angle );
  16460. var ty = this.aY + this.yRadius * Math.sin( angle );
  16461. return new THREE.Vector2( tx, ty );
  16462. };
  16463. /**************************************************************
  16464. * Arc curve
  16465. **************************************************************/
  16466. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  16467. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  16468. };
  16469. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  16470. /**************************************************************
  16471. * Utils
  16472. **************************************************************/
  16473. THREE.Curve.Utils = {
  16474. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16475. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16476. },
  16477. // Puay Bing, thanks for helping with this derivative!
  16478. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16479. return -3 * p0 * (1 - t) * (1 - t) +
  16480. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  16481. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  16482. 3 * t * t * p3;
  16483. },
  16484. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16485. // To check if my formulas are correct
  16486. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16487. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16488. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  16489. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16490. return h00 + h10 + h01 + h11;
  16491. },
  16492. // Catmull-Rom
  16493. interpolate: function( p0, p1, p2, p3, t ) {
  16494. var v0 = ( p2 - p0 ) * 0.5;
  16495. var v1 = ( p3 - p1 ) * 0.5;
  16496. var t2 = t * t;
  16497. var t3 = t * t2;
  16498. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16499. }
  16500. };
  16501. // TODO: Transformation for Curves?
  16502. /**************************************************************
  16503. * 3D Curves
  16504. **************************************************************/
  16505. // A Factory method for creating new curve subclasses
  16506. THREE.Curve.create = function ( constructor, getPointFunc ) {
  16507. constructor.prototype = Object.create( THREE.Curve.prototype );
  16508. constructor.prototype.getPoint = getPointFunc;
  16509. return constructor;
  16510. };
  16511. /**************************************************************
  16512. * Line3D
  16513. **************************************************************/
  16514. THREE.LineCurve3 = THREE.Curve.create(
  16515. function ( v1, v2 ) {
  16516. this.v1 = v1;
  16517. this.v2 = v2;
  16518. },
  16519. function ( t ) {
  16520. var r = new THREE.Vector3();
  16521. r.subVectors( this.v2, this.v1 ); // diff
  16522. r.multiplyScalar( t );
  16523. r.add( this.v1 );
  16524. return r;
  16525. }
  16526. );
  16527. /**************************************************************
  16528. * Quadratic Bezier 3D curve
  16529. **************************************************************/
  16530. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  16531. function ( v0, v1, v2 ) {
  16532. this.v0 = v0;
  16533. this.v1 = v1;
  16534. this.v2 = v2;
  16535. },
  16536. function ( t ) {
  16537. var tx, ty, tz;
  16538. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  16539. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  16540. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  16541. return new THREE.Vector3( tx, ty, tz );
  16542. }
  16543. );
  16544. /**************************************************************
  16545. * Cubic Bezier 3D curve
  16546. **************************************************************/
  16547. THREE.CubicBezierCurve3 = THREE.Curve.create(
  16548. function ( v0, v1, v2, v3 ) {
  16549. this.v0 = v0;
  16550. this.v1 = v1;
  16551. this.v2 = v2;
  16552. this.v3 = v3;
  16553. },
  16554. function ( t ) {
  16555. var tx, ty, tz;
  16556. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16557. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16558. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  16559. return new THREE.Vector3( tx, ty, tz );
  16560. }
  16561. );
  16562. /**************************************************************
  16563. * Spline 3D curve
  16564. **************************************************************/
  16565. THREE.SplineCurve3 = THREE.Curve.create(
  16566. function ( points /* array of Vector3 */) {
  16567. this.points = (points == undefined) ? [] : points;
  16568. },
  16569. function ( t ) {
  16570. var v = new THREE.Vector3();
  16571. var c = [];
  16572. var points = this.points, point, intPoint, weight;
  16573. point = ( points.length - 1 ) * t;
  16574. intPoint = Math.floor( point );
  16575. weight = point - intPoint;
  16576. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16577. c[ 1 ] = intPoint;
  16578. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16579. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16580. var pt0 = points[ c[0] ],
  16581. pt1 = points[ c[1] ],
  16582. pt2 = points[ c[2] ],
  16583. pt3 = points[ c[3] ];
  16584. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  16585. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  16586. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  16587. return v;
  16588. }
  16589. );
  16590. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  16591. // var v = new THREE.Vector3();
  16592. // var c = [];
  16593. // var points = this.points, point, intPoint, weight;
  16594. // point = ( points.length - 1 ) * t;
  16595. // intPoint = Math.floor( point );
  16596. // weight = point - intPoint;
  16597. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16598. // c[ 1 ] = intPoint;
  16599. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16600. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16601. // var pt0 = points[ c[0] ],
  16602. // pt1 = points[ c[1] ],
  16603. // pt2 = points[ c[2] ],
  16604. // pt3 = points[ c[3] ];
  16605. // // t = weight;
  16606. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  16607. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  16608. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  16609. // return v;
  16610. // }
  16611. /**************************************************************
  16612. * Closed Spline 3D curve
  16613. **************************************************************/
  16614. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  16615. function ( points /* array of Vector3 */) {
  16616. this.points = (points == undefined) ? [] : points;
  16617. },
  16618. function ( t ) {
  16619. var v = new THREE.Vector3();
  16620. var c = [];
  16621. var points = this.points, point, intPoint, weight;
  16622. point = ( points.length - 0 ) * t;
  16623. // This needs to be from 0-length +1
  16624. intPoint = Math.floor( point );
  16625. weight = point - intPoint;
  16626. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  16627. c[ 0 ] = ( intPoint - 1 ) % points.length;
  16628. c[ 1 ] = ( intPoint ) % points.length;
  16629. c[ 2 ] = ( intPoint + 1 ) % points.length;
  16630. c[ 3 ] = ( intPoint + 2 ) % points.length;
  16631. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16632. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16633. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  16634. return v;
  16635. }
  16636. );
  16637. /**
  16638. * @author zz85 / http://www.lab4games.net/zz85/blog
  16639. *
  16640. **/
  16641. /**************************************************************
  16642. * Curved Path - a curve path is simply a array of connected
  16643. * curves, but retains the api of a curve
  16644. **************************************************************/
  16645. THREE.CurvePath = function () {
  16646. this.curves = [];
  16647. this.bends = [];
  16648. this.autoClose = false; // Automatically closes the path
  16649. };
  16650. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16651. THREE.CurvePath.prototype.add = function ( curve ) {
  16652. this.curves.push( curve );
  16653. };
  16654. THREE.CurvePath.prototype.checkConnection = function() {
  16655. // TODO
  16656. // If the ending of curve is not connected to the starting
  16657. // or the next curve, then, this is not a real path
  16658. };
  16659. THREE.CurvePath.prototype.closePath = function() {
  16660. // TODO Test
  16661. // and verify for vector3 (needs to implement equals)
  16662. // Add a line curve if start and end of lines are not connected
  16663. var startPoint = this.curves[0].getPoint(0);
  16664. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  16665. if (!startPoint.equals(endPoint)) {
  16666. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16667. }
  16668. };
  16669. // To get accurate point with reference to
  16670. // entire path distance at time t,
  16671. // following has to be done:
  16672. // 1. Length of each sub path have to be known
  16673. // 2. Locate and identify type of curve
  16674. // 3. Get t for the curve
  16675. // 4. Return curve.getPointAt(t')
  16676. THREE.CurvePath.prototype.getPoint = function( t ) {
  16677. var d = t * this.getLength();
  16678. var curveLengths = this.getCurveLengths();
  16679. var i = 0, diff, curve;
  16680. // To think about boundaries points.
  16681. while ( i < curveLengths.length ) {
  16682. if ( curveLengths[ i ] >= d ) {
  16683. diff = curveLengths[ i ] - d;
  16684. curve = this.curves[ i ];
  16685. var u = 1 - diff / curve.getLength();
  16686. return curve.getPointAt( u );
  16687. break;
  16688. }
  16689. i ++;
  16690. }
  16691. return null;
  16692. // loop where sum != 0, sum > d , sum+1 <d
  16693. };
  16694. /*
  16695. THREE.CurvePath.prototype.getTangent = function( t ) {
  16696. };*/
  16697. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16698. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16699. // getPoint() depends on getLength
  16700. THREE.CurvePath.prototype.getLength = function() {
  16701. var lens = this.getCurveLengths();
  16702. return lens[ lens.length - 1 ];
  16703. };
  16704. // Compute lengths and cache them
  16705. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16706. THREE.CurvePath.prototype.getCurveLengths = function() {
  16707. // We use cache values if curves and cache array are same length
  16708. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16709. return this.cacheLengths;
  16710. };
  16711. // Get length of subsurve
  16712. // Push sums into cached array
  16713. var lengths = [], sums = 0;
  16714. var i, il = this.curves.length;
  16715. for ( i = 0; i < il; i ++ ) {
  16716. sums += this.curves[ i ].getLength();
  16717. lengths.push( sums );
  16718. }
  16719. this.cacheLengths = lengths;
  16720. return lengths;
  16721. };
  16722. // Returns min and max coordinates, as well as centroid
  16723. THREE.CurvePath.prototype.getBoundingBox = function () {
  16724. var points = this.getPoints();
  16725. var maxX, maxY, maxZ;
  16726. var minX, minY, minZ;
  16727. maxX = maxY = Number.NEGATIVE_INFINITY;
  16728. minX = minY = Number.POSITIVE_INFINITY;
  16729. var p, i, il, sum;
  16730. var v3 = points[0] instanceof THREE.Vector3;
  16731. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16732. for ( i = 0, il = points.length; i < il; i ++ ) {
  16733. p = points[ i ];
  16734. if ( p.x > maxX ) maxX = p.x;
  16735. else if ( p.x < minX ) minX = p.x;
  16736. if ( p.y > maxY ) maxY = p.y;
  16737. else if ( p.y < minY ) minY = p.y;
  16738. if ( v3 ) {
  16739. if ( p.z > maxZ ) maxZ = p.z;
  16740. else if ( p.z < minZ ) minZ = p.z;
  16741. }
  16742. sum.add( p );
  16743. }
  16744. var ret = {
  16745. minX: minX,
  16746. minY: minY,
  16747. maxX: maxX,
  16748. maxY: maxY,
  16749. centroid: sum.divideScalar( il )
  16750. };
  16751. if ( v3 ) {
  16752. ret.maxZ = maxZ;
  16753. ret.minZ = minZ;
  16754. }
  16755. return ret;
  16756. };
  16757. /**************************************************************
  16758. * Create Geometries Helpers
  16759. **************************************************************/
  16760. /// Generate geometry from path points (for Line or ParticleSystem objects)
  16761. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16762. var pts = this.getPoints( divisions, true );
  16763. return this.createGeometry( pts );
  16764. };
  16765. // Generate geometry from equidistance sampling along the path
  16766. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16767. var pts = this.getSpacedPoints( divisions, true );
  16768. return this.createGeometry( pts );
  16769. };
  16770. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16771. var geometry = new THREE.Geometry();
  16772. for ( var i = 0; i < points.length; i ++ ) {
  16773. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16774. }
  16775. return geometry;
  16776. };
  16777. /**************************************************************
  16778. * Bend / Wrap Helper Methods
  16779. **************************************************************/
  16780. // Wrap path / Bend modifiers?
  16781. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16782. this.bends.push( bendpath );
  16783. };
  16784. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  16785. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  16786. var i, il;
  16787. if ( !bends ) {
  16788. bends = this.bends;
  16789. }
  16790. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16791. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16792. }
  16793. return oldPts;
  16794. };
  16795. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  16796. var oldPts = this.getSpacedPoints( segments );
  16797. var i, il;
  16798. if ( !bends ) {
  16799. bends = this.bends;
  16800. }
  16801. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16802. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16803. }
  16804. return oldPts;
  16805. };
  16806. // This returns getPoints() bend/wrapped around the contour of a path.
  16807. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  16808. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  16809. var bounds = this.getBoundingBox();
  16810. var i, il, p, oldX, oldY, xNorm;
  16811. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  16812. p = oldPts[ i ];
  16813. oldX = p.x;
  16814. oldY = p.y;
  16815. xNorm = oldX / bounds.maxX;
  16816. // If using actual distance, for length > path, requires line extrusions
  16817. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  16818. xNorm = path.getUtoTmapping( xNorm, oldX );
  16819. // check for out of bounds?
  16820. var pathPt = path.getPoint( xNorm );
  16821. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  16822. p.x = pathPt.x + normal.x;
  16823. p.y = pathPt.y + normal.y;
  16824. }
  16825. return oldPts;
  16826. };
  16827. /**
  16828. * @author alteredq / http://alteredqualia.com/
  16829. */
  16830. THREE.Gyroscope = function () {
  16831. THREE.Object3D.call( this );
  16832. };
  16833. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  16834. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  16835. this.matrixAutoUpdate && this.updateMatrix();
  16836. // update matrixWorld
  16837. if ( this.matrixWorldNeedsUpdate || force ) {
  16838. if ( this.parent ) {
  16839. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  16840. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  16841. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  16842. this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
  16843. } else {
  16844. this.matrixWorld.copy( this.matrix );
  16845. }
  16846. this.matrixWorldNeedsUpdate = false;
  16847. force = true;
  16848. }
  16849. // update children
  16850. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  16851. this.children[ i ].updateMatrixWorld( force );
  16852. }
  16853. };
  16854. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  16855. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  16856. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  16857. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  16858. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  16859. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  16860. /**
  16861. * @author zz85 / http://www.lab4games.net/zz85/blog
  16862. * Creates free form 2d path using series of points, lines or curves.
  16863. *
  16864. **/
  16865. THREE.Path = function ( points ) {
  16866. THREE.CurvePath.call(this);
  16867. this.actions = [];
  16868. if ( points ) {
  16869. this.fromPoints( points );
  16870. }
  16871. };
  16872. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16873. THREE.PathActions = {
  16874. MOVE_TO: 'moveTo',
  16875. LINE_TO: 'lineTo',
  16876. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  16877. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  16878. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  16879. ARC: 'arc', // Circle
  16880. ELLIPSE: 'ellipse'
  16881. };
  16882. // TODO Clean up PATH API
  16883. // Create path using straight lines to connect all points
  16884. // - vectors: array of Vector2
  16885. THREE.Path.prototype.fromPoints = function ( vectors ) {
  16886. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  16887. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  16888. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  16889. };
  16890. };
  16891. // startPath() endPath()?
  16892. THREE.Path.prototype.moveTo = function ( x, y ) {
  16893. var args = Array.prototype.slice.call( arguments );
  16894. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  16895. };
  16896. THREE.Path.prototype.lineTo = function ( x, y ) {
  16897. var args = Array.prototype.slice.call( arguments );
  16898. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16899. var x0 = lastargs[ lastargs.length - 2 ];
  16900. var y0 = lastargs[ lastargs.length - 1 ];
  16901. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  16902. this.curves.push( curve );
  16903. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  16904. };
  16905. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  16906. var args = Array.prototype.slice.call( arguments );
  16907. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16908. var x0 = lastargs[ lastargs.length - 2 ];
  16909. var y0 = lastargs[ lastargs.length - 1 ];
  16910. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  16911. new THREE.Vector2( aCPx, aCPy ),
  16912. new THREE.Vector2( aX, aY ) );
  16913. this.curves.push( curve );
  16914. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  16915. };
  16916. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  16917. aCP2x, aCP2y,
  16918. aX, aY ) {
  16919. var args = Array.prototype.slice.call( arguments );
  16920. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16921. var x0 = lastargs[ lastargs.length - 2 ];
  16922. var y0 = lastargs[ lastargs.length - 1 ];
  16923. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  16924. new THREE.Vector2( aCP1x, aCP1y ),
  16925. new THREE.Vector2( aCP2x, aCP2y ),
  16926. new THREE.Vector2( aX, aY ) );
  16927. this.curves.push( curve );
  16928. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  16929. };
  16930. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  16931. var args = Array.prototype.slice.call( arguments );
  16932. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16933. var x0 = lastargs[ lastargs.length - 2 ];
  16934. var y0 = lastargs[ lastargs.length - 1 ];
  16935. //---
  16936. var npts = [ new THREE.Vector2( x0, y0 ) ];
  16937. Array.prototype.push.apply( npts, pts );
  16938. var curve = new THREE.SplineCurve( npts );
  16939. this.curves.push( curve );
  16940. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  16941. };
  16942. // FUTURE: Change the API or follow canvas API?
  16943. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  16944. aStartAngle, aEndAngle, aClockwise ) {
  16945. var lastargs = this.actions[ this.actions.length - 1].args;
  16946. var x0 = lastargs[ lastargs.length - 2 ];
  16947. var y0 = lastargs[ lastargs.length - 1 ];
  16948. this.absarc(aX + x0, aY + y0, aRadius,
  16949. aStartAngle, aEndAngle, aClockwise );
  16950. };
  16951. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  16952. aStartAngle, aEndAngle, aClockwise ) {
  16953. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  16954. };
  16955. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  16956. aStartAngle, aEndAngle, aClockwise ) {
  16957. var lastargs = this.actions[ this.actions.length - 1].args;
  16958. var x0 = lastargs[ lastargs.length - 2 ];
  16959. var y0 = lastargs[ lastargs.length - 1 ];
  16960. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  16961. aStartAngle, aEndAngle, aClockwise );
  16962. };
  16963. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  16964. aStartAngle, aEndAngle, aClockwise ) {
  16965. var args = Array.prototype.slice.call( arguments );
  16966. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  16967. aStartAngle, aEndAngle, aClockwise );
  16968. this.curves.push( curve );
  16969. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  16970. args.push(lastPoint.x);
  16971. args.push(lastPoint.y);
  16972. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  16973. };
  16974. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  16975. if ( ! divisions ) divisions = 40;
  16976. var points = [];
  16977. for ( var i = 0; i < divisions; i ++ ) {
  16978. points.push( this.getPoint( i / divisions ) );
  16979. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  16980. }
  16981. // if ( closedPath ) {
  16982. //
  16983. // points.push( points[ 0 ] );
  16984. //
  16985. // }
  16986. return points;
  16987. };
  16988. /* Return an array of vectors based on contour of the path */
  16989. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  16990. if (this.useSpacedPoints) {
  16991. console.log('tata');
  16992. return this.getSpacedPoints( divisions, closedPath );
  16993. }
  16994. divisions = divisions || 12;
  16995. var points = [];
  16996. var i, il, item, action, args;
  16997. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  16998. laste, j,
  16999. t, tx, ty;
  17000. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17001. item = this.actions[ i ];
  17002. action = item.action;
  17003. args = item.args;
  17004. switch( action ) {
  17005. case THREE.PathActions.MOVE_TO:
  17006. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17007. break;
  17008. case THREE.PathActions.LINE_TO:
  17009. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17010. break;
  17011. case THREE.PathActions.QUADRATIC_CURVE_TO:
  17012. cpx = args[ 2 ];
  17013. cpy = args[ 3 ];
  17014. cpx1 = args[ 0 ];
  17015. cpy1 = args[ 1 ];
  17016. if ( points.length > 0 ) {
  17017. laste = points[ points.length - 1 ];
  17018. cpx0 = laste.x;
  17019. cpy0 = laste.y;
  17020. } else {
  17021. laste = this.actions[ i - 1 ].args;
  17022. cpx0 = laste[ laste.length - 2 ];
  17023. cpy0 = laste[ laste.length - 1 ];
  17024. }
  17025. for ( j = 1; j <= divisions; j ++ ) {
  17026. t = j / divisions;
  17027. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17028. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17029. points.push( new THREE.Vector2( tx, ty ) );
  17030. }
  17031. break;
  17032. case THREE.PathActions.BEZIER_CURVE_TO:
  17033. cpx = args[ 4 ];
  17034. cpy = args[ 5 ];
  17035. cpx1 = args[ 0 ];
  17036. cpy1 = args[ 1 ];
  17037. cpx2 = args[ 2 ];
  17038. cpy2 = args[ 3 ];
  17039. if ( points.length > 0 ) {
  17040. laste = points[ points.length - 1 ];
  17041. cpx0 = laste.x;
  17042. cpy0 = laste.y;
  17043. } else {
  17044. laste = this.actions[ i - 1 ].args;
  17045. cpx0 = laste[ laste.length - 2 ];
  17046. cpy0 = laste[ laste.length - 1 ];
  17047. }
  17048. for ( j = 1; j <= divisions; j ++ ) {
  17049. t = j / divisions;
  17050. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17051. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17052. points.push( new THREE.Vector2( tx, ty ) );
  17053. }
  17054. break;
  17055. case THREE.PathActions.CSPLINE_THRU:
  17056. laste = this.actions[ i - 1 ].args;
  17057. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17058. var spts = [ last ];
  17059. var n = divisions * args[ 0 ].length;
  17060. spts = spts.concat( args[ 0 ] );
  17061. var spline = new THREE.SplineCurve( spts );
  17062. for ( j = 1; j <= n; j ++ ) {
  17063. points.push( spline.getPointAt( j / n ) ) ;
  17064. }
  17065. break;
  17066. case THREE.PathActions.ARC:
  17067. var aX = args[ 0 ], aY = args[ 1 ],
  17068. aRadius = args[ 2 ],
  17069. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17070. aClockwise = !!args[ 5 ];
  17071. var deltaAngle = aEndAngle - aStartAngle;
  17072. var angle;
  17073. var tdivisions = divisions * 2;
  17074. for ( j = 1; j <= tdivisions; j ++ ) {
  17075. t = j / tdivisions;
  17076. if ( ! aClockwise ) {
  17077. t = 1 - t;
  17078. }
  17079. angle = aStartAngle + t * deltaAngle;
  17080. tx = aX + aRadius * Math.cos( angle );
  17081. ty = aY + aRadius * Math.sin( angle );
  17082. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17083. points.push( new THREE.Vector2( tx, ty ) );
  17084. }
  17085. //console.log(points);
  17086. break;
  17087. case THREE.PathActions.ELLIPSE:
  17088. var aX = args[ 0 ], aY = args[ 1 ],
  17089. xRadius = args[ 2 ],
  17090. yRadius = args[ 3 ],
  17091. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17092. aClockwise = !!args[ 6 ];
  17093. var deltaAngle = aEndAngle - aStartAngle;
  17094. var angle;
  17095. var tdivisions = divisions * 2;
  17096. for ( j = 1; j <= tdivisions; j ++ ) {
  17097. t = j / tdivisions;
  17098. if ( ! aClockwise ) {
  17099. t = 1 - t;
  17100. }
  17101. angle = aStartAngle + t * deltaAngle;
  17102. tx = aX + xRadius * Math.cos( angle );
  17103. ty = aY + yRadius * Math.sin( angle );
  17104. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17105. points.push( new THREE.Vector2( tx, ty ) );
  17106. }
  17107. //console.log(points);
  17108. break;
  17109. } // end switch
  17110. }
  17111. // Normalize to remove the closing point by default.
  17112. var lastPoint = points[ points.length - 1];
  17113. var EPSILON = 0.0000000001;
  17114. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17115. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17116. points.splice( points.length - 1, 1);
  17117. if ( closedPath ) {
  17118. points.push( points[ 0 ] );
  17119. }
  17120. return points;
  17121. };
  17122. // Breaks path into shapes
  17123. THREE.Path.prototype.toShapes = function() {
  17124. var i, il, item, action, args;
  17125. var subPaths = [], lastPath = new THREE.Path();
  17126. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17127. item = this.actions[ i ];
  17128. args = item.args;
  17129. action = item.action;
  17130. if ( action == THREE.PathActions.MOVE_TO ) {
  17131. if ( lastPath.actions.length != 0 ) {
  17132. subPaths.push( lastPath );
  17133. lastPath = new THREE.Path();
  17134. }
  17135. }
  17136. lastPath[ action ].apply( lastPath, args );
  17137. }
  17138. if ( lastPath.actions.length != 0 ) {
  17139. subPaths.push( lastPath );
  17140. }
  17141. // console.log(subPaths);
  17142. if ( subPaths.length == 0 ) return [];
  17143. var tmpPath, tmpShape, shapes = [];
  17144. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17145. // console.log("Holes first", holesFirst);
  17146. if ( subPaths.length == 1) {
  17147. tmpPath = subPaths[0];
  17148. tmpShape = new THREE.Shape();
  17149. tmpShape.actions = tmpPath.actions;
  17150. tmpShape.curves = tmpPath.curves;
  17151. shapes.push( tmpShape );
  17152. return shapes;
  17153. };
  17154. if ( holesFirst ) {
  17155. tmpShape = new THREE.Shape();
  17156. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17157. tmpPath = subPaths[ i ];
  17158. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17159. tmpShape.actions = tmpPath.actions;
  17160. tmpShape.curves = tmpPath.curves;
  17161. shapes.push( tmpShape );
  17162. tmpShape = new THREE.Shape();
  17163. //console.log('cw', i);
  17164. } else {
  17165. tmpShape.holes.push( tmpPath );
  17166. //console.log('ccw', i);
  17167. }
  17168. }
  17169. } else {
  17170. // Shapes first
  17171. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17172. tmpPath = subPaths[ i ];
  17173. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17174. if ( tmpShape ) shapes.push( tmpShape );
  17175. tmpShape = new THREE.Shape();
  17176. tmpShape.actions = tmpPath.actions;
  17177. tmpShape.curves = tmpPath.curves;
  17178. } else {
  17179. tmpShape.holes.push( tmpPath );
  17180. }
  17181. }
  17182. shapes.push( tmpShape );
  17183. }
  17184. //console.log("shape", shapes);
  17185. return shapes;
  17186. };
  17187. /**
  17188. * @author zz85 / http://www.lab4games.net/zz85/blog
  17189. * Defines a 2d shape plane using paths.
  17190. **/
  17191. // STEP 1 Create a path.
  17192. // STEP 2 Turn path into shape.
  17193. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17194. // STEP 3a - Extract points from each shape, turn to vertices
  17195. // STEP 3b - Triangulate each shape, add faces.
  17196. THREE.Shape = function () {
  17197. THREE.Path.apply( this, arguments );
  17198. this.holes = [];
  17199. };
  17200. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17201. // Convenience method to return ExtrudeGeometry
  17202. THREE.Shape.prototype.extrude = function ( options ) {
  17203. var extruded = new THREE.ExtrudeGeometry( this, options );
  17204. return extruded;
  17205. };
  17206. // Convenience method to return ShapeGeometry
  17207. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17208. var geometry = new THREE.ShapeGeometry( this, options );
  17209. return geometry;
  17210. };
  17211. // Get points of holes
  17212. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17213. var i, il = this.holes.length, holesPts = [];
  17214. for ( i = 0; i < il; i ++ ) {
  17215. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17216. }
  17217. return holesPts;
  17218. };
  17219. // Get points of holes (spaced by regular distance)
  17220. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17221. var i, il = this.holes.length, holesPts = [];
  17222. for ( i = 0; i < il; i ++ ) {
  17223. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17224. }
  17225. return holesPts;
  17226. };
  17227. // Get points of shape and holes (keypoints based on segments parameter)
  17228. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17229. return {
  17230. shape: this.getTransformedPoints( divisions ),
  17231. holes: this.getPointsHoles( divisions )
  17232. };
  17233. };
  17234. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17235. if (this.useSpacedPoints) {
  17236. return this.extractAllSpacedPoints(divisions);
  17237. }
  17238. return this.extractAllPoints(divisions);
  17239. };
  17240. //
  17241. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17242. //
  17243. // return {
  17244. //
  17245. // shape: this.transform( bend, divisions ),
  17246. // holes: this.getPointsHoles( divisions, bend )
  17247. //
  17248. // };
  17249. //
  17250. // };
  17251. // Get points of shape and holes (spaced by regular distance)
  17252. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17253. return {
  17254. shape: this.getTransformedSpacedPoints( divisions ),
  17255. holes: this.getSpacedPointsHoles( divisions )
  17256. };
  17257. };
  17258. /**************************************************************
  17259. * Utils
  17260. **************************************************************/
  17261. THREE.Shape.Utils = {
  17262. /*
  17263. contour - array of vector2 for contour
  17264. holes - array of array of vector2
  17265. */
  17266. removeHoles: function ( contour, holes ) {
  17267. var shape = contour.concat(); // work on this shape
  17268. var allpoints = shape.concat();
  17269. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  17270. var prevShapeVert, nextShapeVert,
  17271. prevHoleVert, nextHoleVert,
  17272. holeIndex, shapeIndex,
  17273. shapeId, shapeGroup,
  17274. h, h2,
  17275. hole, shortest, d,
  17276. p, pts1, pts2,
  17277. tmpShape1, tmpShape2,
  17278. tmpHole1, tmpHole2,
  17279. verts = [];
  17280. for ( h = 0; h < holes.length; h ++ ) {
  17281. hole = holes[ h ];
  17282. /*
  17283. shapeholes[ h ].concat(); // preserves original
  17284. holes.push( hole );
  17285. */
  17286. Array.prototype.push.apply( allpoints, hole );
  17287. shortest = Number.POSITIVE_INFINITY;
  17288. // Find the shortest pair of pts between shape and hole
  17289. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  17290. // Using distanceToSquared() intead of distanceTo() should speed a little
  17291. // since running square roots operations are reduced.
  17292. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  17293. pts1 = hole[ h2 ];
  17294. var dist = [];
  17295. for ( p = 0; p < shape.length; p++ ) {
  17296. pts2 = shape[ p ];
  17297. d = pts1.distanceToSquared( pts2 );
  17298. dist.push( d );
  17299. if ( d < shortest ) {
  17300. shortest = d;
  17301. holeIndex = h2;
  17302. shapeIndex = p;
  17303. }
  17304. }
  17305. }
  17306. //console.log("shortest", shortest, dist);
  17307. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17308. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17309. var areaapts = [
  17310. hole[ holeIndex ],
  17311. shape[ shapeIndex ],
  17312. shape[ prevShapeVert ]
  17313. ];
  17314. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  17315. var areabpts = [
  17316. hole[ holeIndex ],
  17317. hole[ prevHoleVert ],
  17318. shape[ shapeIndex ]
  17319. ];
  17320. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  17321. var shapeOffset = 1;
  17322. var holeOffset = -1;
  17323. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  17324. shapeIndex += shapeOffset;
  17325. holeIndex += holeOffset;
  17326. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17327. shapeIndex %= shape.length;
  17328. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17329. holeIndex %= hole.length;
  17330. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17331. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17332. areaapts = [
  17333. hole[ holeIndex ],
  17334. shape[ shapeIndex ],
  17335. shape[ prevShapeVert ]
  17336. ];
  17337. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  17338. areabpts = [
  17339. hole[ holeIndex ],
  17340. hole[ prevHoleVert ],
  17341. shape[ shapeIndex ]
  17342. ];
  17343. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  17344. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  17345. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  17346. // In case areas are not correct.
  17347. //console.log("USE THIS");
  17348. shapeIndex = oldShapeIndex;
  17349. holeIndex = oldHoleIndex ;
  17350. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17351. shapeIndex %= shape.length;
  17352. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17353. holeIndex %= hole.length;
  17354. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17355. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17356. } else {
  17357. //console.log("USE THAT ")
  17358. }
  17359. tmpShape1 = shape.slice( 0, shapeIndex );
  17360. tmpShape2 = shape.slice( shapeIndex );
  17361. tmpHole1 = hole.slice( holeIndex );
  17362. tmpHole2 = hole.slice( 0, holeIndex );
  17363. // Should check orders here again?
  17364. var trianglea = [
  17365. hole[ holeIndex ],
  17366. shape[ shapeIndex ],
  17367. shape[ prevShapeVert ]
  17368. ];
  17369. var triangleb = [
  17370. hole[ holeIndex ] ,
  17371. hole[ prevHoleVert ],
  17372. shape[ shapeIndex ]
  17373. ];
  17374. verts.push( trianglea );
  17375. verts.push( triangleb );
  17376. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17377. }
  17378. return {
  17379. shape:shape, /* shape with no holes */
  17380. isolatedPts: verts, /* isolated faces */
  17381. allpoints: allpoints
  17382. }
  17383. },
  17384. triangulateShape: function ( contour, holes ) {
  17385. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  17386. var shape = shapeWithoutHoles.shape,
  17387. allpoints = shapeWithoutHoles.allpoints,
  17388. isolatedPts = shapeWithoutHoles.isolatedPts;
  17389. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  17390. // 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.
  17391. //console.log( "triangles",triangles, triangles.length );
  17392. //console.log( "allpoints",allpoints, allpoints.length );
  17393. var i, il, f, face,
  17394. key, index,
  17395. allPointsMap = {},
  17396. isolatedPointsMap = {};
  17397. // prepare all points map
  17398. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17399. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17400. if ( allPointsMap[ key ] !== undefined ) {
  17401. console.log( "Duplicate point", key );
  17402. }
  17403. allPointsMap[ key ] = i;
  17404. }
  17405. // check all face vertices against all points map
  17406. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17407. face = triangles[ i ];
  17408. for ( f = 0; f < 3; f ++ ) {
  17409. key = face[ f ].x + ":" + face[ f ].y;
  17410. index = allPointsMap[ key ];
  17411. if ( index !== undefined ) {
  17412. face[ f ] = index;
  17413. }
  17414. }
  17415. }
  17416. // check isolated points vertices against all points map
  17417. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  17418. face = isolatedPts[ i ];
  17419. for ( f = 0; f < 3; f ++ ) {
  17420. key = face[ f ].x + ":" + face[ f ].y;
  17421. index = allPointsMap[ key ];
  17422. if ( index !== undefined ) {
  17423. face[ f ] = index;
  17424. }
  17425. }
  17426. }
  17427. return triangles.concat( isolatedPts );
  17428. }, // end triangulate shapes
  17429. /*
  17430. triangulate2 : function( pts, holes ) {
  17431. // For use with Poly2Tri.js
  17432. var allpts = pts.concat();
  17433. var shape = [];
  17434. for (var p in pts) {
  17435. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  17436. }
  17437. var swctx = new js.poly2tri.SweepContext(shape);
  17438. for (var h in holes) {
  17439. var aHole = holes[h];
  17440. var newHole = []
  17441. for (i in aHole) {
  17442. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  17443. allpts.push(aHole[i]);
  17444. }
  17445. swctx.AddHole(newHole);
  17446. }
  17447. var find;
  17448. var findIndexForPt = function (pt) {
  17449. find = new THREE.Vector2(pt.x, pt.y);
  17450. var p;
  17451. for (p=0, pl = allpts.length; p<pl; p++) {
  17452. if (allpts[p].equals(find)) return p;
  17453. }
  17454. return -1;
  17455. };
  17456. // triangulate
  17457. js.poly2tri.sweep.Triangulate(swctx);
  17458. var triangles = swctx.GetTriangles();
  17459. var tr ;
  17460. var facesPts = [];
  17461. for (var t in triangles) {
  17462. tr = triangles[t];
  17463. facesPts.push([
  17464. findIndexForPt(tr.GetPoint(0)),
  17465. findIndexForPt(tr.GetPoint(1)),
  17466. findIndexForPt(tr.GetPoint(2))
  17467. ]);
  17468. }
  17469. // console.log(facesPts);
  17470. // console.log("triangles", triangles.length, triangles);
  17471. // Returns array of faces with 3 element each
  17472. return facesPts;
  17473. },
  17474. */
  17475. isClockWise: function ( pts ) {
  17476. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17477. },
  17478. // Bezier Curves formulas obtained from
  17479. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17480. // Quad Bezier Functions
  17481. b2p0: function ( t, p ) {
  17482. var k = 1 - t;
  17483. return k * k * p;
  17484. },
  17485. b2p1: function ( t, p ) {
  17486. return 2 * ( 1 - t ) * t * p;
  17487. },
  17488. b2p2: function ( t, p ) {
  17489. return t * t * p;
  17490. },
  17491. b2: function ( t, p0, p1, p2 ) {
  17492. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17493. },
  17494. // Cubic Bezier Functions
  17495. b3p0: function ( t, p ) {
  17496. var k = 1 - t;
  17497. return k * k * k * p;
  17498. },
  17499. b3p1: function ( t, p ) {
  17500. var k = 1 - t;
  17501. return 3 * k * k * t * p;
  17502. },
  17503. b3p2: function ( t, p ) {
  17504. var k = 1 - t;
  17505. return 3 * k * t * t * p;
  17506. },
  17507. b3p3: function ( t, p ) {
  17508. return t * t * t * p;
  17509. },
  17510. b3: function ( t, p0, p1, p2, p3 ) {
  17511. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17512. }
  17513. };
  17514. /**
  17515. * @author mikael emtinger / http://gomo.se/
  17516. */
  17517. THREE.AnimationHandler = (function() {
  17518. var playing = [];
  17519. var library = {};
  17520. var that = {};
  17521. //--- update ---
  17522. that.update = function( deltaTimeMS ) {
  17523. for( var i = 0; i < playing.length; i ++ )
  17524. playing[ i ].update( deltaTimeMS );
  17525. };
  17526. //--- add ---
  17527. that.addToUpdate = function( animation ) {
  17528. if ( playing.indexOf( animation ) === -1 )
  17529. playing.push( animation );
  17530. };
  17531. //--- remove ---
  17532. that.removeFromUpdate = function( animation ) {
  17533. var index = playing.indexOf( animation );
  17534. if( index !== -1 )
  17535. playing.splice( index, 1 );
  17536. };
  17537. //--- add ---
  17538. that.add = function( data ) {
  17539. if ( library[ data.name ] !== undefined )
  17540. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  17541. library[ data.name ] = data;
  17542. initData( data );
  17543. };
  17544. //--- get ---
  17545. that.get = function( name ) {
  17546. if ( typeof name === "string" ) {
  17547. if ( library[ name ] ) {
  17548. return library[ name ];
  17549. } else {
  17550. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  17551. return null;
  17552. }
  17553. } else {
  17554. // todo: add simple tween library
  17555. }
  17556. };
  17557. //--- parse ---
  17558. that.parse = function( root ) {
  17559. // setup hierarchy
  17560. var hierarchy = [];
  17561. if ( root instanceof THREE.SkinnedMesh ) {
  17562. for( var b = 0; b < root.bones.length; b++ ) {
  17563. hierarchy.push( root.bones[ b ] );
  17564. }
  17565. } else {
  17566. parseRecurseHierarchy( root, hierarchy );
  17567. }
  17568. return hierarchy;
  17569. };
  17570. var parseRecurseHierarchy = function( root, hierarchy ) {
  17571. hierarchy.push( root );
  17572. for( var c = 0; c < root.children.length; c++ )
  17573. parseRecurseHierarchy( root.children[ c ], hierarchy );
  17574. }
  17575. //--- init data ---
  17576. var initData = function( data ) {
  17577. if( data.initialized === true )
  17578. return;
  17579. // loop through all keys
  17580. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  17581. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17582. // remove minus times
  17583. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  17584. data.hierarchy[ h ].keys[ k ].time = 0;
  17585. // create quaternions
  17586. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  17587. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  17588. var quat = data.hierarchy[ h ].keys[ k ].rot;
  17589. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  17590. }
  17591. }
  17592. // prepare morph target keys
  17593. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  17594. // get all used
  17595. var usedMorphTargets = {};
  17596. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17597. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17598. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  17599. usedMorphTargets[ morphTargetName ] = -1;
  17600. }
  17601. }
  17602. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  17603. // set all used on all frames
  17604. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17605. var influences = {};
  17606. for ( var morphTargetName in usedMorphTargets ) {
  17607. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17608. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  17609. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  17610. break;
  17611. }
  17612. }
  17613. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  17614. influences[ morphTargetName ] = 0;
  17615. }
  17616. }
  17617. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  17618. }
  17619. }
  17620. // remove all keys that are on the same time
  17621. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17622. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  17623. data.hierarchy[ h ].keys.splice( k, 1 );
  17624. k --;
  17625. }
  17626. }
  17627. // set index
  17628. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17629. data.hierarchy[ h ].keys[ k ].index = k;
  17630. }
  17631. }
  17632. // JIT
  17633. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  17634. data.JIT = {};
  17635. data.JIT.hierarchy = [];
  17636. for( var h = 0; h < data.hierarchy.length; h ++ )
  17637. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  17638. // done
  17639. data.initialized = true;
  17640. };
  17641. // interpolation types
  17642. that.LINEAR = 0;
  17643. that.CATMULLROM = 1;
  17644. that.CATMULLROM_FORWARD = 2;
  17645. return that;
  17646. }());
  17647. /**
  17648. * @author mikael emtinger / http://gomo.se/
  17649. * @author mrdoob / http://mrdoob.com/
  17650. * @author alteredq / http://alteredqualia.com/
  17651. */
  17652. THREE.Animation = function ( root, name, interpolationType ) {
  17653. this.root = root;
  17654. this.data = THREE.AnimationHandler.get( name );
  17655. this.hierarchy = THREE.AnimationHandler.parse( root );
  17656. this.currentTime = 0;
  17657. this.timeScale = 1;
  17658. this.isPlaying = false;
  17659. this.isPaused = true;
  17660. this.loop = true;
  17661. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  17662. this.points = [];
  17663. this.target = new THREE.Vector3();
  17664. };
  17665. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  17666. if ( this.isPlaying === false ) {
  17667. this.isPlaying = true;
  17668. this.loop = loop !== undefined ? loop : true;
  17669. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17670. // reset key cache
  17671. var h, hl = this.hierarchy.length,
  17672. object;
  17673. for ( h = 0; h < hl; h ++ ) {
  17674. object = this.hierarchy[ h ];
  17675. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17676. object.useQuaternion = true;
  17677. }
  17678. object.matrixAutoUpdate = true;
  17679. if ( object.animationCache === undefined ) {
  17680. object.animationCache = {};
  17681. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  17682. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  17683. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17684. }
  17685. var prevKey = object.animationCache.prevKey;
  17686. var nextKey = object.animationCache.nextKey;
  17687. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  17688. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  17689. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  17690. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  17691. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  17692. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  17693. }
  17694. this.update( 0 );
  17695. }
  17696. this.isPaused = false;
  17697. THREE.AnimationHandler.addToUpdate( this );
  17698. };
  17699. THREE.Animation.prototype.pause = function() {
  17700. if ( this.isPaused === true ) {
  17701. THREE.AnimationHandler.addToUpdate( this );
  17702. } else {
  17703. THREE.AnimationHandler.removeFromUpdate( this );
  17704. }
  17705. this.isPaused = !this.isPaused;
  17706. };
  17707. THREE.Animation.prototype.stop = function() {
  17708. this.isPlaying = false;
  17709. this.isPaused = false;
  17710. THREE.AnimationHandler.removeFromUpdate( this );
  17711. };
  17712. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  17713. // early out
  17714. if ( this.isPlaying === false ) return;
  17715. // vars
  17716. var types = [ "pos", "rot", "scl" ];
  17717. var type;
  17718. var scale;
  17719. var vector;
  17720. var prevXYZ, nextXYZ;
  17721. var prevKey, nextKey;
  17722. var object;
  17723. var animationCache;
  17724. var frame;
  17725. var JIThierarchy = this.data.JIT.hierarchy;
  17726. var currentTime, unloopedCurrentTime;
  17727. var currentPoint, forwardPoint, angle;
  17728. this.currentTime += deltaTimeMS * this.timeScale;
  17729. unloopedCurrentTime = this.currentTime;
  17730. currentTime = this.currentTime = this.currentTime % this.data.length;
  17731. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17732. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17733. object = this.hierarchy[ h ];
  17734. animationCache = object.animationCache;
  17735. // loop through pos/rot/scl
  17736. for ( var t = 0; t < 3; t ++ ) {
  17737. // get keys
  17738. type = types[ t ];
  17739. prevKey = animationCache.prevKey[ type ];
  17740. nextKey = animationCache.nextKey[ type ];
  17741. // switch keys?
  17742. if ( nextKey.time <= unloopedCurrentTime ) {
  17743. // did we loop?
  17744. if ( currentTime < unloopedCurrentTime ) {
  17745. if ( this.loop ) {
  17746. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  17747. nextKey = this.getNextKeyWith( type, h, 1 );
  17748. while( nextKey.time < currentTime ) {
  17749. prevKey = nextKey;
  17750. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17751. }
  17752. } else {
  17753. this.stop();
  17754. return;
  17755. }
  17756. } else {
  17757. do {
  17758. prevKey = nextKey;
  17759. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17760. } while( nextKey.time < currentTime )
  17761. }
  17762. animationCache.prevKey[ type ] = prevKey;
  17763. animationCache.nextKey[ type ] = nextKey;
  17764. }
  17765. object.matrixAutoUpdate = true;
  17766. object.matrixWorldNeedsUpdate = true;
  17767. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  17768. prevXYZ = prevKey[ type ];
  17769. nextXYZ = nextKey[ type ];
  17770. // check scale error
  17771. if ( scale < 0 || scale > 1 ) {
  17772. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  17773. scale = scale < 0 ? 0 : 1;
  17774. }
  17775. // interpolate
  17776. if ( type === "pos" ) {
  17777. vector = object.position;
  17778. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  17779. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17780. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17781. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17782. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17783. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17784. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  17785. this.points[ 1 ] = prevXYZ;
  17786. this.points[ 2 ] = nextXYZ;
  17787. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  17788. scale = scale * 0.33 + 0.33;
  17789. currentPoint = this.interpolateCatmullRom( this.points, scale );
  17790. vector.x = currentPoint[ 0 ];
  17791. vector.y = currentPoint[ 1 ];
  17792. vector.z = currentPoint[ 2 ];
  17793. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17794. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  17795. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  17796. this.target.sub( vector );
  17797. this.target.y = 0;
  17798. this.target.normalize();
  17799. angle = Math.atan2( this.target.x, this.target.z );
  17800. object.rotation.set( 0, angle, 0 );
  17801. }
  17802. }
  17803. } else if ( type === "rot" ) {
  17804. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  17805. } else if ( type === "scl" ) {
  17806. vector = object.scale;
  17807. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17808. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17809. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17810. }
  17811. }
  17812. }
  17813. };
  17814. // Catmull-Rom spline
  17815. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  17816. var c = [], v3 = [],
  17817. point, intPoint, weight, w2, w3,
  17818. pa, pb, pc, pd;
  17819. point = ( points.length - 1 ) * scale;
  17820. intPoint = Math.floor( point );
  17821. weight = point - intPoint;
  17822. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  17823. c[ 1 ] = intPoint;
  17824. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  17825. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  17826. pa = points[ c[ 0 ] ];
  17827. pb = points[ c[ 1 ] ];
  17828. pc = points[ c[ 2 ] ];
  17829. pd = points[ c[ 3 ] ];
  17830. w2 = weight * weight;
  17831. w3 = weight * w2;
  17832. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  17833. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  17834. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  17835. return v3;
  17836. };
  17837. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  17838. var v0 = ( p2 - p0 ) * 0.5,
  17839. v1 = ( p3 - p1 ) * 0.5;
  17840. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17841. };
  17842. // Get next key with
  17843. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  17844. var keys = this.data.hierarchy[ h ].keys;
  17845. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17846. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17847. key = key < keys.length - 1 ? key : keys.length - 1;
  17848. } else {
  17849. key = key % keys.length;
  17850. }
  17851. for ( ; key < keys.length; key++ ) {
  17852. if ( keys[ key ][ type ] !== undefined ) {
  17853. return keys[ key ];
  17854. }
  17855. }
  17856. return this.data.hierarchy[ h ].keys[ 0 ];
  17857. };
  17858. // Get previous key with
  17859. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  17860. var keys = this.data.hierarchy[ h ].keys;
  17861. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17862. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17863. key = key > 0 ? key : 0;
  17864. } else {
  17865. key = key >= 0 ? key : key + keys.length;
  17866. }
  17867. for ( ; key >= 0; key -- ) {
  17868. if ( keys[ key ][ type ] !== undefined ) {
  17869. return keys[ key ];
  17870. }
  17871. }
  17872. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  17873. };
  17874. /**
  17875. * @author mikael emtinger / http://gomo.se/
  17876. * @author mrdoob / http://mrdoob.com/
  17877. * @author alteredq / http://alteredqualia.com/
  17878. * @author khang duong
  17879. * @author erik kitson
  17880. */
  17881. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  17882. this.root = root;
  17883. this.data = THREE.AnimationHandler.get( data );
  17884. this.hierarchy = THREE.AnimationHandler.parse( root );
  17885. this.currentTime = 0;
  17886. this.timeScale = 0.001;
  17887. this.isPlaying = false;
  17888. this.isPaused = true;
  17889. this.loop = true;
  17890. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  17891. // initialize to first keyframes
  17892. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17893. var keys = this.data.hierarchy[h].keys,
  17894. sids = this.data.hierarchy[h].sids,
  17895. obj = this.hierarchy[h];
  17896. if ( keys.length && sids ) {
  17897. for ( var s = 0; s < sids.length; s++ ) {
  17898. var sid = sids[ s ],
  17899. next = this.getNextKeyWith( sid, h, 0 );
  17900. if ( next ) {
  17901. next.apply( sid );
  17902. }
  17903. }
  17904. obj.matrixAutoUpdate = false;
  17905. this.data.hierarchy[h].node.updateMatrix();
  17906. obj.matrixWorldNeedsUpdate = true;
  17907. }
  17908. }
  17909. };
  17910. // Play
  17911. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  17912. if( !this.isPlaying ) {
  17913. this.isPlaying = true;
  17914. this.loop = loop !== undefined ? loop : true;
  17915. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17916. this.startTimeMs = startTimeMS;
  17917. this.startTime = 10000000;
  17918. this.endTime = -this.startTime;
  17919. // reset key cache
  17920. var h, hl = this.hierarchy.length,
  17921. object,
  17922. node;
  17923. for ( h = 0; h < hl; h++ ) {
  17924. object = this.hierarchy[ h ];
  17925. node = this.data.hierarchy[ h ];
  17926. object.useQuaternion = true;
  17927. if ( node.animationCache === undefined ) {
  17928. node.animationCache = {};
  17929. node.animationCache.prevKey = null;
  17930. node.animationCache.nextKey = null;
  17931. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17932. }
  17933. var keys = this.data.hierarchy[h].keys;
  17934. if (keys.length) {
  17935. node.animationCache.prevKey = keys[ 0 ];
  17936. node.animationCache.nextKey = keys[ 1 ];
  17937. this.startTime = Math.min( keys[0].time, this.startTime );
  17938. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  17939. }
  17940. }
  17941. this.update( 0 );
  17942. }
  17943. this.isPaused = false;
  17944. THREE.AnimationHandler.addToUpdate( this );
  17945. };
  17946. // Pause
  17947. THREE.KeyFrameAnimation.prototype.pause = function() {
  17948. if( this.isPaused ) {
  17949. THREE.AnimationHandler.addToUpdate( this );
  17950. } else {
  17951. THREE.AnimationHandler.removeFromUpdate( this );
  17952. }
  17953. this.isPaused = !this.isPaused;
  17954. };
  17955. // Stop
  17956. THREE.KeyFrameAnimation.prototype.stop = function() {
  17957. this.isPlaying = false;
  17958. this.isPaused = false;
  17959. THREE.AnimationHandler.removeFromUpdate( this );
  17960. // reset JIT matrix and remove cache
  17961. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  17962. var obj = this.hierarchy[ h ];
  17963. var node = this.data.hierarchy[ h ];
  17964. if ( node.animationCache !== undefined ) {
  17965. var original = node.animationCache.originalMatrix;
  17966. if( obj instanceof THREE.Bone ) {
  17967. original.copy( obj.skinMatrix );
  17968. obj.skinMatrix = original;
  17969. } else {
  17970. original.copy( obj.matrix );
  17971. obj.matrix = original;
  17972. }
  17973. delete node.animationCache;
  17974. }
  17975. }
  17976. };
  17977. // Update
  17978. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  17979. // early out
  17980. if( !this.isPlaying ) return;
  17981. // vars
  17982. var prevKey, nextKey;
  17983. var object;
  17984. var node;
  17985. var frame;
  17986. var JIThierarchy = this.data.JIT.hierarchy;
  17987. var currentTime, unloopedCurrentTime;
  17988. var looped;
  17989. // update
  17990. this.currentTime += deltaTimeMS * this.timeScale;
  17991. unloopedCurrentTime = this.currentTime;
  17992. currentTime = this.currentTime = this.currentTime % this.data.length;
  17993. // if looped around, the current time should be based on the startTime
  17994. if ( currentTime < this.startTimeMs ) {
  17995. currentTime = this.currentTime = this.startTimeMs + currentTime;
  17996. }
  17997. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17998. looped = currentTime < unloopedCurrentTime;
  17999. if ( looped && !this.loop ) {
  18000. // Set the animation to the last keyframes and stop
  18001. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18002. var keys = this.data.hierarchy[h].keys,
  18003. sids = this.data.hierarchy[h].sids,
  18004. end = keys.length-1,
  18005. obj = this.hierarchy[h];
  18006. if ( keys.length ) {
  18007. for ( var s = 0; s < sids.length; s++ ) {
  18008. var sid = sids[ s ],
  18009. prev = this.getPrevKeyWith( sid, h, end );
  18010. if ( prev ) {
  18011. prev.apply( sid );
  18012. }
  18013. }
  18014. this.data.hierarchy[h].node.updateMatrix();
  18015. obj.matrixWorldNeedsUpdate = true;
  18016. }
  18017. }
  18018. this.stop();
  18019. return;
  18020. }
  18021. // check pre-infinity
  18022. if ( currentTime < this.startTime ) {
  18023. return;
  18024. }
  18025. // update
  18026. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18027. object = this.hierarchy[ h ];
  18028. node = this.data.hierarchy[ h ];
  18029. var keys = node.keys,
  18030. animationCache = node.animationCache;
  18031. // use JIT?
  18032. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  18033. if( object instanceof THREE.Bone ) {
  18034. object.skinMatrix = JIThierarchy[ h ][ frame ];
  18035. object.matrixWorldNeedsUpdate = false;
  18036. } else {
  18037. object.matrix = JIThierarchy[ h ][ frame ];
  18038. object.matrixWorldNeedsUpdate = true;
  18039. }
  18040. // use interpolation
  18041. } else if ( keys.length ) {
  18042. // make sure so original matrix and not JIT matrix is set
  18043. if ( this.JITCompile && animationCache ) {
  18044. if( object instanceof THREE.Bone ) {
  18045. object.skinMatrix = animationCache.originalMatrix;
  18046. } else {
  18047. object.matrix = animationCache.originalMatrix;
  18048. }
  18049. }
  18050. prevKey = animationCache.prevKey;
  18051. nextKey = animationCache.nextKey;
  18052. if ( prevKey && nextKey ) {
  18053. // switch keys?
  18054. if ( nextKey.time <= unloopedCurrentTime ) {
  18055. // did we loop?
  18056. if ( looped && this.loop ) {
  18057. prevKey = keys[ 0 ];
  18058. nextKey = keys[ 1 ];
  18059. while ( nextKey.time < currentTime ) {
  18060. prevKey = nextKey;
  18061. nextKey = keys[ prevKey.index + 1 ];
  18062. }
  18063. } else if ( !looped ) {
  18064. var lastIndex = keys.length - 1;
  18065. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  18066. prevKey = nextKey;
  18067. nextKey = keys[ prevKey.index + 1 ];
  18068. }
  18069. }
  18070. animationCache.prevKey = prevKey;
  18071. animationCache.nextKey = nextKey;
  18072. }
  18073. if(nextKey.time >= currentTime)
  18074. prevKey.interpolate( nextKey, currentTime );
  18075. else
  18076. prevKey.interpolate( nextKey, nextKey.time);
  18077. }
  18078. this.data.hierarchy[h].node.updateMatrix();
  18079. object.matrixWorldNeedsUpdate = true;
  18080. }
  18081. }
  18082. // update JIT?
  18083. if ( this.JITCompile ) {
  18084. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  18085. this.hierarchy[ 0 ].updateMatrixWorld( true );
  18086. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  18087. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  18088. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  18089. } else {
  18090. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  18091. }
  18092. }
  18093. }
  18094. }
  18095. };
  18096. // Get next key with
  18097. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18098. var keys = this.data.hierarchy[ h ].keys;
  18099. key = key % keys.length;
  18100. for ( ; key < keys.length; key++ ) {
  18101. if ( keys[ key ].hasTarget( sid ) ) {
  18102. return keys[ key ];
  18103. }
  18104. }
  18105. return keys[ 0 ];
  18106. };
  18107. // Get previous key with
  18108. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18109. var keys = this.data.hierarchy[ h ].keys;
  18110. key = key >= 0 ? key : key + keys.length;
  18111. for ( ; key >= 0; key-- ) {
  18112. if ( keys[ key ].hasTarget( sid ) ) {
  18113. return keys[ key ];
  18114. }
  18115. }
  18116. return keys[ keys.length - 1 ];
  18117. };
  18118. /**
  18119. * Camera for rendering cube maps
  18120. * - renders scene into axis-aligned cube
  18121. *
  18122. * @author alteredq / http://alteredqualia.com/
  18123. */
  18124. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  18125. THREE.Object3D.call( this );
  18126. var fov = 90, aspect = 1;
  18127. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18128. cameraPX.up.set( 0, -1, 0 );
  18129. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  18130. this.add( cameraPX );
  18131. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18132. cameraNX.up.set( 0, -1, 0 );
  18133. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  18134. this.add( cameraNX );
  18135. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18136. cameraPY.up.set( 0, 0, 1 );
  18137. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  18138. this.add( cameraPY );
  18139. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18140. cameraNY.up.set( 0, 0, -1 );
  18141. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  18142. this.add( cameraNY );
  18143. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18144. cameraPZ.up.set( 0, -1, 0 );
  18145. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  18146. this.add( cameraPZ );
  18147. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18148. cameraNZ.up.set( 0, -1, 0 );
  18149. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  18150. this.add( cameraNZ );
  18151. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  18152. this.updateCubeMap = function ( renderer, scene ) {
  18153. var renderTarget = this.renderTarget;
  18154. var generateMipmaps = renderTarget.generateMipmaps;
  18155. renderTarget.generateMipmaps = false;
  18156. renderTarget.activeCubeFace = 0;
  18157. renderer.render( scene, cameraPX, renderTarget );
  18158. renderTarget.activeCubeFace = 1;
  18159. renderer.render( scene, cameraNX, renderTarget );
  18160. renderTarget.activeCubeFace = 2;
  18161. renderer.render( scene, cameraPY, renderTarget );
  18162. renderTarget.activeCubeFace = 3;
  18163. renderer.render( scene, cameraNY, renderTarget );
  18164. renderTarget.activeCubeFace = 4;
  18165. renderer.render( scene, cameraPZ, renderTarget );
  18166. renderTarget.generateMipmaps = generateMipmaps;
  18167. renderTarget.activeCubeFace = 5;
  18168. renderer.render( scene, cameraNZ, renderTarget );
  18169. };
  18170. };
  18171. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  18172. /*
  18173. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  18174. *
  18175. * A general perpose camera, for setting FOV, Lens Focal Length,
  18176. * and switching between perspective and orthographic views easily.
  18177. * Use this only if you do not wish to manage
  18178. * both a Orthographic and Perspective Camera
  18179. *
  18180. */
  18181. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  18182. THREE.Camera.call( this );
  18183. this.fov = fov;
  18184. this.left = -width / 2;
  18185. this.right = width / 2
  18186. this.top = height / 2;
  18187. this.bottom = -height / 2;
  18188. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  18189. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  18190. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  18191. this.zoom = 1;
  18192. this.toPerspective();
  18193. var aspect = width/height;
  18194. };
  18195. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  18196. THREE.CombinedCamera.prototype.toPerspective = function () {
  18197. // Switches to the Perspective Camera
  18198. this.near = this.cameraP.near;
  18199. this.far = this.cameraP.far;
  18200. this.cameraP.fov = this.fov / this.zoom ;
  18201. this.cameraP.updateProjectionMatrix();
  18202. this.projectionMatrix = this.cameraP.projectionMatrix;
  18203. this.inPerspectiveMode = true;
  18204. this.inOrthographicMode = false;
  18205. };
  18206. THREE.CombinedCamera.prototype.toOrthographic = function () {
  18207. // Switches to the Orthographic camera estimating viewport from Perspective
  18208. var fov = this.fov;
  18209. var aspect = this.cameraP.aspect;
  18210. var near = this.cameraP.near;
  18211. var far = this.cameraP.far;
  18212. // The size that we set is the mid plane of the viewing frustum
  18213. var hyperfocus = ( near + far ) / 2;
  18214. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  18215. var planeHeight = 2 * halfHeight;
  18216. var planeWidth = planeHeight * aspect;
  18217. var halfWidth = planeWidth / 2;
  18218. halfHeight /= this.zoom;
  18219. halfWidth /= this.zoom;
  18220. this.cameraO.left = -halfWidth;
  18221. this.cameraO.right = halfWidth;
  18222. this.cameraO.top = halfHeight;
  18223. this.cameraO.bottom = -halfHeight;
  18224. // this.cameraO.left = -farHalfWidth;
  18225. // this.cameraO.right = farHalfWidth;
  18226. // this.cameraO.top = farHalfHeight;
  18227. // this.cameraO.bottom = -farHalfHeight;
  18228. // this.cameraO.left = this.left / this.zoom;
  18229. // this.cameraO.right = this.right / this.zoom;
  18230. // this.cameraO.top = this.top / this.zoom;
  18231. // this.cameraO.bottom = this.bottom / this.zoom;
  18232. this.cameraO.updateProjectionMatrix();
  18233. this.near = this.cameraO.near;
  18234. this.far = this.cameraO.far;
  18235. this.projectionMatrix = this.cameraO.projectionMatrix;
  18236. this.inPerspectiveMode = false;
  18237. this.inOrthographicMode = true;
  18238. };
  18239. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  18240. this.cameraP.aspect = width / height;
  18241. this.left = -width / 2;
  18242. this.right = width / 2
  18243. this.top = height / 2;
  18244. this.bottom = -height / 2;
  18245. };
  18246. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  18247. this.fov = fov;
  18248. if ( this.inPerspectiveMode ) {
  18249. this.toPerspective();
  18250. } else {
  18251. this.toOrthographic();
  18252. }
  18253. };
  18254. // For mantaining similar API with PerspectiveCamera
  18255. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  18256. if ( this.inPerspectiveMode ) {
  18257. this.toPerspective();
  18258. } else {
  18259. this.toPerspective();
  18260. this.toOrthographic();
  18261. }
  18262. };
  18263. /*
  18264. * Uses Focal Length (in mm) to estimate and set FOV
  18265. * 35mm (fullframe) camera is used if frame size is not specified;
  18266. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  18267. */
  18268. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  18269. if ( frameHeight === undefined ) frameHeight = 24;
  18270. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  18271. this.setFov( fov );
  18272. return fov;
  18273. };
  18274. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  18275. this.zoom = zoom;
  18276. if ( this.inPerspectiveMode ) {
  18277. this.toPerspective();
  18278. } else {
  18279. this.toOrthographic();
  18280. }
  18281. };
  18282. THREE.CombinedCamera.prototype.toFrontView = function() {
  18283. this.rotation.x = 0;
  18284. this.rotation.y = 0;
  18285. this.rotation.z = 0;
  18286. // should we be modifing the matrix instead?
  18287. this.rotationAutoUpdate = false;
  18288. };
  18289. THREE.CombinedCamera.prototype.toBackView = function() {
  18290. this.rotation.x = 0;
  18291. this.rotation.y = Math.PI;
  18292. this.rotation.z = 0;
  18293. this.rotationAutoUpdate = false;
  18294. };
  18295. THREE.CombinedCamera.prototype.toLeftView = function() {
  18296. this.rotation.x = 0;
  18297. this.rotation.y = - Math.PI / 2;
  18298. this.rotation.z = 0;
  18299. this.rotationAutoUpdate = false;
  18300. };
  18301. THREE.CombinedCamera.prototype.toRightView = function() {
  18302. this.rotation.x = 0;
  18303. this.rotation.y = Math.PI / 2;
  18304. this.rotation.z = 0;
  18305. this.rotationAutoUpdate = false;
  18306. };
  18307. THREE.CombinedCamera.prototype.toTopView = function() {
  18308. this.rotation.x = - Math.PI / 2;
  18309. this.rotation.y = 0;
  18310. this.rotation.z = 0;
  18311. this.rotationAutoUpdate = false;
  18312. };
  18313. THREE.CombinedCamera.prototype.toBottomView = function() {
  18314. this.rotation.x = Math.PI / 2;
  18315. this.rotation.y = 0;
  18316. this.rotation.z = 0;
  18317. this.rotationAutoUpdate = false;
  18318. };
  18319. /**
  18320. * @author alteredq / http://alteredqualia.com/
  18321. *
  18322. * - 3d asterisk shape (for line pieces THREE.Line)
  18323. */
  18324. THREE.AsteriskGeometry = function ( innerRadius, outerRadius ) {
  18325. THREE.Geometry.call( this );
  18326. var sd = innerRadius;
  18327. var ed = outerRadius;
  18328. var sd2 = 0.707 * sd;
  18329. var ed2 = 0.707 * ed;
  18330. var rays = [ [ sd, 0, 0 ], [ ed, 0, 0 ], [ -sd, 0, 0 ], [ -ed, 0, 0 ],
  18331. [ 0, sd, 0 ], [ 0, ed, 0 ], [ 0, -sd, 0 ], [ 0, -ed, 0 ],
  18332. [ 0, 0, sd ], [ 0, 0, ed ], [ 0, 0, -sd ], [ 0, 0, -ed ],
  18333. [ sd2, sd2, 0 ], [ ed2, ed2, 0 ], [ -sd2, -sd2, 0 ], [ -ed2, -ed2, 0 ],
  18334. [ sd2, -sd2, 0 ], [ ed2, -ed2, 0 ], [ -sd2, sd2, 0 ], [ -ed2, ed2, 0 ],
  18335. [ sd2, 0, sd2 ], [ ed2, 0, ed2 ], [ -sd2, 0, -sd2 ], [ -ed2, 0, -ed2 ],
  18336. [ sd2, 0, -sd2 ], [ ed2, 0, -ed2 ], [ -sd2, 0, sd2 ], [ -ed2, 0, ed2 ],
  18337. [ 0, sd2, sd2 ], [ 0, ed2, ed2 ], [ 0, -sd2, -sd2 ], [ 0, -ed2, -ed2 ],
  18338. [ 0, sd2, -sd2 ], [ 0, ed2, -ed2 ], [ 0, -sd2, sd2 ], [ 0, -ed2, ed2 ]
  18339. ];
  18340. for ( var i = 0, il = rays.length; i < il; i ++ ) {
  18341. var x = rays[ i ][ 0 ];
  18342. var y = rays[ i ][ 1 ];
  18343. var z = rays[ i ][ 2 ];
  18344. this.vertices.push( new THREE.Vector3( x, y, z ) );
  18345. }
  18346. };
  18347. THREE.AsteriskGeometry.prototype = Object.create( THREE.Geometry.prototype );/**
  18348. * @author hughes
  18349. */
  18350. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18351. THREE.Geometry.call( this );
  18352. radius = radius || 50;
  18353. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18354. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18355. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18356. var i, uvs = [],
  18357. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18358. this.vertices.push(center);
  18359. uvs.push( centerUV );
  18360. for ( i = 0; i <= segments; i ++ ) {
  18361. var vertex = new THREE.Vector3();
  18362. vertex.x = radius * Math.cos( thetaStart + i / segments * thetaLength );
  18363. vertex.y = radius * Math.sin( thetaStart + i / segments * thetaLength );
  18364. this.vertices.push( vertex );
  18365. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  18366. }
  18367. var n = new THREE.Vector3( 0, 0, -1 );
  18368. for ( i = 1; i <= segments; i ++ ) {
  18369. var v1 = i;
  18370. var v2 = i + 1 ;
  18371. var v3 = 0;
  18372. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  18373. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  18374. }
  18375. this.computeCentroids();
  18376. this.computeFaceNormals();
  18377. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18378. };
  18379. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18380. /**
  18381. * @author mrdoob / http://mrdoob.com/
  18382. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18383. */
  18384. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18385. THREE.Geometry.call( this );
  18386. var scope = this;
  18387. this.width = width;
  18388. this.height = height;
  18389. this.depth = depth;
  18390. this.widthSegments = widthSegments || 1;
  18391. this.heightSegments = heightSegments || 1;
  18392. this.depthSegments = depthSegments || 1;
  18393. var width_half = this.width / 2;
  18394. var height_half = this.height / 2;
  18395. var depth_half = this.depth / 2;
  18396. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  18397. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  18398. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  18399. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  18400. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  18401. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  18402. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18403. var w, ix, iy,
  18404. gridX = scope.widthSegments,
  18405. gridY = scope.heightSegments,
  18406. width_half = width / 2,
  18407. height_half = height / 2,
  18408. offset = scope.vertices.length;
  18409. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18410. w = 'z';
  18411. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18412. w = 'y';
  18413. gridY = scope.depthSegments;
  18414. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18415. w = 'x';
  18416. gridX = scope.depthSegments;
  18417. }
  18418. var gridX1 = gridX + 1,
  18419. gridY1 = gridY + 1,
  18420. segment_width = width / gridX,
  18421. segment_height = height / gridY,
  18422. normal = new THREE.Vector3();
  18423. normal[ w ] = depth > 0 ? 1 : - 1;
  18424. for ( iy = 0; iy < gridY1; iy ++ ) {
  18425. for ( ix = 0; ix < gridX1; ix ++ ) {
  18426. var vector = new THREE.Vector3();
  18427. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18428. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18429. vector[ w ] = depth;
  18430. scope.vertices.push( vector );
  18431. }
  18432. }
  18433. for ( iy = 0; iy < gridY; iy++ ) {
  18434. for ( ix = 0; ix < gridX; ix++ ) {
  18435. var a = ix + gridX1 * iy;
  18436. var b = ix + gridX1 * ( iy + 1 );
  18437. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18438. var d = ( ix + 1 ) + gridX1 * iy;
  18439. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  18440. face.normal.copy( normal );
  18441. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  18442. face.materialIndex = materialIndex;
  18443. scope.faces.push( face );
  18444. scope.faceVertexUvs[ 0 ].push( [
  18445. new THREE.Vector2( ix / gridX, 1 - iy / gridY ),
  18446. new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  18447. new THREE.Vector2( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  18448. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY )
  18449. ] );
  18450. }
  18451. }
  18452. }
  18453. this.computeCentroids();
  18454. this.mergeVertices();
  18455. };
  18456. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18457. /**
  18458. * @author mrdoob / http://mrdoob.com/
  18459. */
  18460. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radiusSegments, heightSegments, openEnded ) {
  18461. THREE.Geometry.call( this );
  18462. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18463. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18464. height = height !== undefined ? height : 100;
  18465. var heightHalf = height / 2;
  18466. var segmentsX = radiusSegments || 8;
  18467. var segmentsY = heightSegments || 1;
  18468. var x, y, vertices = [], uvs = [];
  18469. for ( y = 0; y <= segmentsY; y ++ ) {
  18470. var verticesRow = [];
  18471. var uvsRow = [];
  18472. var v = y / segmentsY;
  18473. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18474. for ( x = 0; x <= segmentsX; x ++ ) {
  18475. var u = x / segmentsX;
  18476. var vertex = new THREE.Vector3();
  18477. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  18478. vertex.y = - v * height + heightHalf;
  18479. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  18480. this.vertices.push( vertex );
  18481. verticesRow.push( this.vertices.length - 1 );
  18482. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  18483. }
  18484. vertices.push( verticesRow );
  18485. uvs.push( uvsRow );
  18486. }
  18487. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18488. var na, nb;
  18489. for ( x = 0; x < segmentsX; x ++ ) {
  18490. if ( radiusTop !== 0 ) {
  18491. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18492. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18493. } else {
  18494. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18495. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18496. }
  18497. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18498. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18499. for ( y = 0; y < segmentsY; y ++ ) {
  18500. var v1 = vertices[ y ][ x ];
  18501. var v2 = vertices[ y + 1 ][ x ];
  18502. var v3 = vertices[ y + 1 ][ x + 1 ];
  18503. var v4 = vertices[ y ][ x + 1 ];
  18504. var n1 = na.clone();
  18505. var n2 = na.clone();
  18506. var n3 = nb.clone();
  18507. var n4 = nb.clone();
  18508. var uv1 = uvs[ y ][ x ].clone();
  18509. var uv2 = uvs[ y + 1 ][ x ].clone();
  18510. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18511. var uv4 = uvs[ y ][ x + 1 ].clone();
  18512. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  18513. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  18514. }
  18515. }
  18516. // top cap
  18517. if ( !openEnded && radiusTop > 0 ) {
  18518. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18519. for ( x = 0; x < segmentsX; x ++ ) {
  18520. var v1 = vertices[ 0 ][ x ];
  18521. var v2 = vertices[ 0 ][ x + 1 ];
  18522. var v3 = this.vertices.length - 1;
  18523. var n1 = new THREE.Vector3( 0, 1, 0 );
  18524. var n2 = new THREE.Vector3( 0, 1, 0 );
  18525. var n3 = new THREE.Vector3( 0, 1, 0 );
  18526. var uv1 = uvs[ 0 ][ x ].clone();
  18527. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18528. var uv3 = new THREE.Vector2( uv2.u, 0 );
  18529. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18530. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18531. }
  18532. }
  18533. // bottom cap
  18534. if ( !openEnded && radiusBottom > 0 ) {
  18535. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18536. for ( x = 0; x < segmentsX; x ++ ) {
  18537. var v1 = vertices[ y ][ x + 1 ];
  18538. var v2 = vertices[ y ][ x ];
  18539. var v3 = this.vertices.length - 1;
  18540. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18541. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18542. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18543. var uv1 = uvs[ y ][ x + 1 ].clone();
  18544. var uv2 = uvs[ y ][ x ].clone();
  18545. var uv3 = new THREE.Vector2( uv2.u, 1 );
  18546. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18547. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18548. }
  18549. }
  18550. this.computeCentroids();
  18551. this.computeFaceNormals();
  18552. }
  18553. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18554. /**
  18555. * @author zz85 / http://www.lab4games.net/zz85/blog
  18556. *
  18557. * Creates extruded geometry from a path shape.
  18558. *
  18559. * parameters = {
  18560. *
  18561. * size: <float>, // size of the text
  18562. * height: <float>, // thickness to extrude text
  18563. * curveSegments: <int>, // number of points on the curves
  18564. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18565. * amount: <int>, // Amount
  18566. *
  18567. * bevelEnabled: <bool>, // turn on bevel
  18568. * bevelThickness: <float>, // how deep into text bevel goes
  18569. * bevelSize: <float>, // how far from text outline is bevel
  18570. * bevelSegments: <int>, // number of bevel layers
  18571. *
  18572. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18573. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18574. *
  18575. * material: <int> // material index for front and back faces
  18576. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18577. * uvGenerator: <Object> // object that provides UV generator functions
  18578. *
  18579. * }
  18580. **/
  18581. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18582. if ( typeof( shapes ) === "undefined" ) {
  18583. shapes = [];
  18584. return;
  18585. }
  18586. THREE.Geometry.call( this );
  18587. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18588. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18589. this.addShapeList( shapes, options );
  18590. this.computeCentroids();
  18591. this.computeFaceNormals();
  18592. // can't really use automatic vertex normals
  18593. // as then front and back sides get smoothed too
  18594. // should do separate smoothing just for sides
  18595. //this.computeVertexNormals();
  18596. //console.log( "took", ( Date.now() - startTime ) );
  18597. };
  18598. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18599. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18600. var sl = shapes.length;
  18601. for ( var s = 0; s < sl; s ++ ) {
  18602. var shape = shapes[ s ];
  18603. this.addShape( shape, options );
  18604. }
  18605. };
  18606. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18607. var amount = options.amount !== undefined ? options.amount : 100;
  18608. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18609. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18610. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18611. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18612. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18613. var steps = options.steps !== undefined ? options.steps : 1;
  18614. var extrudePath = options.extrudePath;
  18615. var extrudePts, extrudeByPath = false;
  18616. var material = options.material;
  18617. var extrudeMaterial = options.extrudeMaterial;
  18618. // Use default WorldUVGenerator if no UV generators are specified.
  18619. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18620. var shapebb = this.shapebb;
  18621. //shapebb = shape.getBoundingBox();
  18622. var splineTube, binormal, normal, position2;
  18623. if ( extrudePath ) {
  18624. extrudePts = extrudePath.getSpacedPoints( steps );
  18625. extrudeByPath = true;
  18626. bevelEnabled = false; // bevels not supported for path extrusion
  18627. // SETUP TNB variables
  18628. // Reuse TNB from TubeGeomtry for now.
  18629. // TODO1 - have a .isClosed in spline?
  18630. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18631. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18632. binormal = new THREE.Vector3();
  18633. normal = new THREE.Vector3();
  18634. position2 = new THREE.Vector3();
  18635. }
  18636. // Safeguards if bevels are not enabled
  18637. if ( ! bevelEnabled ) {
  18638. bevelSegments = 0;
  18639. bevelThickness = 0;
  18640. bevelSize = 0;
  18641. }
  18642. // Variables initalization
  18643. var ahole, h, hl; // looping of holes
  18644. var scope = this;
  18645. var bevelPoints = [];
  18646. var shapesOffset = this.vertices.length;
  18647. var shapePoints = shape.extractPoints( curveSegments );
  18648. var vertices = shapePoints.shape;
  18649. var holes = shapePoints.holes;
  18650. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  18651. if ( reverse ) {
  18652. vertices = vertices.reverse();
  18653. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18654. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18655. ahole = holes[ h ];
  18656. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18657. holes[ h ] = ahole.reverse();
  18658. }
  18659. }
  18660. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18661. }
  18662. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18663. /* Vertices */
  18664. var contour = vertices; // vertices has all points but contour has only points of circumference
  18665. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18666. ahole = holes[ h ];
  18667. vertices = vertices.concat( ahole );
  18668. }
  18669. function scalePt2 ( pt, vec, size ) {
  18670. if ( !vec ) console.log( "die" );
  18671. return vec.clone().multiplyScalar( size ).add( pt );
  18672. }
  18673. var b, bs, t, z,
  18674. vert, vlen = vertices.length,
  18675. face, flen = faces.length,
  18676. cont, clen = contour.length;
  18677. // Find directions for point movement
  18678. var RAD_TO_DEGREES = 180 / Math.PI;
  18679. function getBevelVec( pt_i, pt_j, pt_k ) {
  18680. // Algorithm 2
  18681. return getBevelVec2( pt_i, pt_j, pt_k );
  18682. }
  18683. function getBevelVec1( pt_i, pt_j, pt_k ) {
  18684. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  18685. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  18686. if ( anglea > angleb ) {
  18687. angleb += Math.PI * 2;
  18688. }
  18689. var anglec = ( anglea + angleb ) / 2;
  18690. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  18691. var x = - Math.cos( anglec );
  18692. var y = - Math.sin( anglec );
  18693. var vec = new THREE.Vector2( x, y ); //.normalize();
  18694. return vec;
  18695. }
  18696. function getBevelVec2( pt_i, pt_j, pt_k ) {
  18697. var a = THREE.ExtrudeGeometry.__v1,
  18698. b = THREE.ExtrudeGeometry.__v2,
  18699. v_hat = THREE.ExtrudeGeometry.__v3,
  18700. w_hat = THREE.ExtrudeGeometry.__v4,
  18701. p = THREE.ExtrudeGeometry.__v5,
  18702. q = THREE.ExtrudeGeometry.__v6,
  18703. v, w,
  18704. v_dot_w_hat, q_sub_p_dot_w_hat,
  18705. s, intersection;
  18706. // good reading for line-line intersection
  18707. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  18708. // define a as vector j->i
  18709. // define b as vectot k->i
  18710. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  18711. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  18712. // get unit vectors
  18713. v = a.normalize();
  18714. w = b.normalize();
  18715. // normals from pt i
  18716. v_hat.set( -v.y, v.x );
  18717. w_hat.set( w.y, -w.x );
  18718. // pts from i
  18719. p.copy( pt_i ).add( v_hat );
  18720. q.copy( pt_i ).add( w_hat );
  18721. if ( p.equals( q ) ) {
  18722. //console.log("Warning: lines are straight");
  18723. return w_hat.clone();
  18724. }
  18725. // Points from j, k. helps prevents points cross overover most of the time
  18726. p.copy( pt_j ).add( v_hat );
  18727. q.copy( pt_k ).add( w_hat );
  18728. v_dot_w_hat = v.dot( w_hat );
  18729. q_sub_p_dot_w_hat = q.sub( p ).dot( w_hat );
  18730. // We should not reach these conditions
  18731. if ( v_dot_w_hat === 0 ) {
  18732. console.log( "Either infinite or no solutions!" );
  18733. if ( q_sub_p_dot_w_hat === 0 ) {
  18734. console.log( "Its finite solutions." );
  18735. } else {
  18736. console.log( "Too bad, no solutions." );
  18737. }
  18738. }
  18739. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  18740. if ( s < 0 ) {
  18741. // in case of emergecy, revert to algorithm 1.
  18742. return getBevelVec1( pt_i, pt_j, pt_k );
  18743. }
  18744. intersection = v.multiplyScalar( s ).add( p );
  18745. return intersection.sub( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  18746. }
  18747. var contourMovements = [];
  18748. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18749. if ( j === il ) j = 0;
  18750. if ( k === il ) k = 0;
  18751. // (j)---(i)---(k)
  18752. // console.log('i,j,k', i, j , k)
  18753. var pt_i = contour[ i ];
  18754. var pt_j = contour[ j ];
  18755. var pt_k = contour[ k ];
  18756. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18757. }
  18758. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18759. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18760. ahole = holes[ h ];
  18761. oneHoleMovements = [];
  18762. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18763. if ( j === il ) j = 0;
  18764. if ( k === il ) k = 0;
  18765. // (j)---(i)---(k)
  18766. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18767. }
  18768. holesMovements.push( oneHoleMovements );
  18769. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18770. }
  18771. // Loop bevelSegments, 1 for the front, 1 for the back
  18772. for ( b = 0; b < bevelSegments; b ++ ) {
  18773. //for ( b = bevelSegments; b > 0; b -- ) {
  18774. t = b / bevelSegments;
  18775. z = bevelThickness * ( 1 - t );
  18776. //z = bevelThickness * t;
  18777. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  18778. //bs = bevelSize * t ; // linear
  18779. // contract shape
  18780. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18781. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18782. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  18783. v( vert.x, vert.y, - z );
  18784. }
  18785. // expand holes
  18786. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  18787. ahole = holes[ h ];
  18788. oneHoleMovements = holesMovements[ h ];
  18789. for ( i = 0, il = ahole.length; i < il; i++ ) {
  18790. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18791. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  18792. v( vert.x, vert.y, -z );
  18793. }
  18794. }
  18795. }
  18796. bs = bevelSize;
  18797. // Back facing vertices
  18798. for ( i = 0; i < vlen; i ++ ) {
  18799. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18800. if ( !extrudeByPath ) {
  18801. v( vert.x, vert.y, 0 );
  18802. } else {
  18803. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18804. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  18805. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  18806. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  18807. v( position2.x, position2.y, position2.z );
  18808. }
  18809. }
  18810. // Add stepped vertices...
  18811. // Including front facing vertices
  18812. var s;
  18813. for ( s = 1; s <= steps; s ++ ) {
  18814. for ( i = 0; i < vlen; i ++ ) {
  18815. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18816. if ( !extrudeByPath ) {
  18817. v( vert.x, vert.y, amount / steps * s );
  18818. } else {
  18819. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18820. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  18821. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  18822. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  18823. v( position2.x, position2.y, position2.z );
  18824. }
  18825. }
  18826. }
  18827. // Add bevel segments planes
  18828. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18829. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  18830. t = b / bevelSegments;
  18831. z = bevelThickness * ( 1 - t );
  18832. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  18833. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  18834. // contract shape
  18835. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18836. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18837. v( vert.x, vert.y, amount + z );
  18838. }
  18839. // expand holes
  18840. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18841. ahole = holes[ h ];
  18842. oneHoleMovements = holesMovements[ h ];
  18843. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18844. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18845. if ( !extrudeByPath ) {
  18846. v( vert.x, vert.y, amount + z );
  18847. } else {
  18848. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  18849. }
  18850. }
  18851. }
  18852. }
  18853. /* Faces */
  18854. // Top and bottom faces
  18855. buildLidFaces();
  18856. // Sides faces
  18857. buildSideFaces();
  18858. ///// Internal functions
  18859. function buildLidFaces() {
  18860. if ( bevelEnabled ) {
  18861. var layer = 0 ; // steps + 1
  18862. var offset = vlen * layer;
  18863. // Bottom faces
  18864. for ( i = 0; i < flen; i ++ ) {
  18865. face = faces[ i ];
  18866. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  18867. }
  18868. layer = steps + bevelSegments * 2;
  18869. offset = vlen * layer;
  18870. // Top faces
  18871. for ( i = 0; i < flen; i ++ ) {
  18872. face = faces[ i ];
  18873. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  18874. }
  18875. } else {
  18876. // Bottom faces
  18877. for ( i = 0; i < flen; i++ ) {
  18878. face = faces[ i ];
  18879. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  18880. }
  18881. // Top faces
  18882. for ( i = 0; i < flen; i ++ ) {
  18883. face = faces[ i ];
  18884. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  18885. }
  18886. }
  18887. }
  18888. // Create faces for the z-sides of the shape
  18889. function buildSideFaces() {
  18890. var layeroffset = 0;
  18891. sidewalls( contour, layeroffset );
  18892. layeroffset += contour.length;
  18893. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18894. ahole = holes[ h ];
  18895. sidewalls( ahole, layeroffset );
  18896. //, true
  18897. layeroffset += ahole.length;
  18898. }
  18899. }
  18900. function sidewalls( contour, layeroffset ) {
  18901. var j, k;
  18902. i = contour.length;
  18903. while ( --i >= 0 ) {
  18904. j = i;
  18905. k = i - 1;
  18906. if ( k < 0 ) k = contour.length - 1;
  18907. //console.log('b', i,j, i-1, k,vertices.length);
  18908. var s = 0, sl = steps + bevelSegments * 2;
  18909. for ( s = 0; s < sl; s ++ ) {
  18910. var slen1 = vlen * s;
  18911. var slen2 = vlen * ( s + 1 );
  18912. var a = layeroffset + j + slen1,
  18913. b = layeroffset + k + slen1,
  18914. c = layeroffset + k + slen2,
  18915. d = layeroffset + j + slen2;
  18916. f4( a, b, c, d, contour, s, sl, j, k );
  18917. }
  18918. }
  18919. }
  18920. function v( x, y, z ) {
  18921. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  18922. }
  18923. function f3( a, b, c, isBottom ) {
  18924. a += shapesOffset;
  18925. b += shapesOffset;
  18926. c += shapesOffset;
  18927. // normal, color, material
  18928. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18929. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  18930. scope.faceVertexUvs[ 0 ].push( uvs );
  18931. }
  18932. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  18933. a += shapesOffset;
  18934. b += shapesOffset;
  18935. c += shapesOffset;
  18936. d += shapesOffset;
  18937. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  18938. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  18939. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  18940. scope.faceVertexUvs[ 0 ].push( uvs );
  18941. }
  18942. };
  18943. THREE.ExtrudeGeometry.WorldUVGenerator = {
  18944. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18945. var ax = geometry.vertices[ indexA ].x,
  18946. ay = geometry.vertices[ indexA ].y,
  18947. bx = geometry.vertices[ indexB ].x,
  18948. by = geometry.vertices[ indexB ].y,
  18949. cx = geometry.vertices[ indexC ].x,
  18950. cy = geometry.vertices[ indexC ].y;
  18951. return [
  18952. new THREE.Vector2( ax, ay ),
  18953. new THREE.Vector2( bx, by ),
  18954. new THREE.Vector2( cx, cy )
  18955. ];
  18956. },
  18957. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18958. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  18959. },
  18960. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  18961. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  18962. contourIndex1, contourIndex2 ) {
  18963. var ax = geometry.vertices[ indexA ].x,
  18964. ay = geometry.vertices[ indexA ].y,
  18965. az = geometry.vertices[ indexA ].z,
  18966. bx = geometry.vertices[ indexB ].x,
  18967. by = geometry.vertices[ indexB ].y,
  18968. bz = geometry.vertices[ indexB ].z,
  18969. cx = geometry.vertices[ indexC ].x,
  18970. cy = geometry.vertices[ indexC ].y,
  18971. cz = geometry.vertices[ indexC ].z,
  18972. dx = geometry.vertices[ indexD ].x,
  18973. dy = geometry.vertices[ indexD ].y,
  18974. dz = geometry.vertices[ indexD ].z;
  18975. if ( Math.abs( ay - by ) < 0.01 ) {
  18976. return [
  18977. new THREE.Vector2( ax, 1 - az ),
  18978. new THREE.Vector2( bx, 1 - bz ),
  18979. new THREE.Vector2( cx, 1 - cz ),
  18980. new THREE.Vector2( dx, 1 - dz )
  18981. ];
  18982. } else {
  18983. return [
  18984. new THREE.Vector2( ay, 1 - az ),
  18985. new THREE.Vector2( by, 1 - bz ),
  18986. new THREE.Vector2( cy, 1 - cz ),
  18987. new THREE.Vector2( dy, 1 - dz )
  18988. ];
  18989. }
  18990. }
  18991. };
  18992. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  18993. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  18994. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  18995. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  18996. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  18997. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  18998. /**
  18999. * @author jonobr1 / http://jonobr1.com
  19000. *
  19001. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19002. * ExtrudeGeometry.
  19003. *
  19004. * parameters = {
  19005. *
  19006. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19007. *
  19008. * material: <int> // material index for front and back faces
  19009. * uvGenerator: <Object> // object that provides UV generator functions
  19010. *
  19011. * }
  19012. **/
  19013. THREE.ShapeGeometry = function ( shapes, options ) {
  19014. THREE.Geometry.call( this );
  19015. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19016. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19017. this.addShapeList( shapes, options );
  19018. this.computeCentroids();
  19019. this.computeFaceNormals();
  19020. };
  19021. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19022. /**
  19023. * Add an array of shapes to THREE.ShapeGeometry.
  19024. */
  19025. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19026. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19027. this.addShape( shapes[ i ], options );
  19028. }
  19029. return this;
  19030. };
  19031. /**
  19032. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19033. */
  19034. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19035. if ( options === undefined ) options = {};
  19036. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19037. var material = options.material;
  19038. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19039. var shapebb = this.shapebb;
  19040. //
  19041. var i, l, hole, s;
  19042. var shapesOffset = this.vertices.length;
  19043. var shapePoints = shape.extractPoints( curveSegments );
  19044. var vertices = shapePoints.shape;
  19045. var holes = shapePoints.holes;
  19046. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19047. if ( reverse ) {
  19048. vertices = vertices.reverse();
  19049. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19050. for ( i = 0, l = holes.length; i < l; i++ ) {
  19051. hole = holes[ i ];
  19052. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19053. holes[ i ] = hole.reverse();
  19054. }
  19055. }
  19056. reverse = false;
  19057. }
  19058. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19059. // Vertices
  19060. var contour = vertices;
  19061. for ( i = 0, l = holes.length; i < l; i++ ) {
  19062. hole = holes[ i ];
  19063. vertices = vertices.concat( hole );
  19064. }
  19065. //
  19066. var vert, vlen = vertices.length;
  19067. var face, flen = faces.length;
  19068. var cont, clen = contour.length;
  19069. for ( i = 0; i < vlen; i++ ) {
  19070. vert = vertices[ i ];
  19071. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19072. }
  19073. for ( i = 0; i < flen; i++ ) {
  19074. face = faces[ i ];
  19075. var a = face[ 0 ] + shapesOffset;
  19076. var b = face[ 1 ] + shapesOffset;
  19077. var c = face[ 2 ] + shapesOffset;
  19078. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19079. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19080. }
  19081. };
  19082. /**
  19083. * @author astrodud / http://astrodud.isgreat.org/
  19084. * @author zz85 / https://github.com/zz85
  19085. * @author bhouston / http://exocortex.com
  19086. */
  19087. // points - to create a closed torus, one must use a set of points
  19088. // like so: [ a, b, c, d, a ], see first is the same as last.
  19089. // segments - the number of circumference segments to create
  19090. // phiStart - the starting radian
  19091. // phiLength - the radian (0 to 2*PI) range of the lathed section
  19092. // 2*pi is a closed lathe, less than 2PI is a portion.
  19093. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  19094. THREE.Geometry.call( this );
  19095. segments = segments || 12;
  19096. phiStart = phiStart || 0;
  19097. phiLength = phiLength || 2 * Math.PI;
  19098. var inversePointLength = 1.0 / ( points.length - 1 );
  19099. var inverseSegments = 1.0 / segments;
  19100. for ( var i = 0, il = segments; i <= il; i ++ ) {
  19101. var phi = phiStart + i * inverseSegments * phiLength;
  19102. var c = Math.cos( phi ),
  19103. s = Math.sin( phi );
  19104. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  19105. var pt = points[ j ];
  19106. var vertex = new THREE.Vector3();
  19107. vertex.x = c * pt.x - s * pt.y;
  19108. vertex.y = s * pt.x + c * pt.y;
  19109. vertex.z = pt.z;
  19110. this.vertices.push( vertex );
  19111. }
  19112. }
  19113. var np = points.length;
  19114. for ( var i = 0, il = segments; i < il; i ++ ) {
  19115. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  19116. var base = j + np * i;
  19117. var a = base;
  19118. var b = base + np;
  19119. var c = base + 1 + np;
  19120. var d = base + 1;
  19121. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19122. var u0 = i * inverseSegments;
  19123. var v0 = j * inversePointLength;
  19124. var u1 = u0 + inverseSegments;
  19125. var v1 = v0 + inversePointLength;
  19126. this.faceVertexUvs[ 0 ].push( [
  19127. new THREE.Vector2( u0, v0 ),
  19128. new THREE.Vector2( u1, v0 ),
  19129. new THREE.Vector2( u1, v1 ),
  19130. new THREE.Vector2( u0, v1 )
  19131. ] );
  19132. }
  19133. }
  19134. this.mergeVertices();
  19135. this.computeCentroids();
  19136. this.computeFaceNormals();
  19137. this.computeVertexNormals();
  19138. };
  19139. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19140. /**
  19141. * @author mrdoob / http://mrdoob.com/
  19142. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19143. */
  19144. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19145. THREE.Geometry.call( this );
  19146. this.width = width;
  19147. this.height = height;
  19148. this.widthSegments = widthSegments || 1;
  19149. this.heightSegments = heightSegments || 1;
  19150. var ix, iz;
  19151. var width_half = width / 2;
  19152. var height_half = height / 2;
  19153. var gridX = this.widthSegments;
  19154. var gridZ = this.heightSegments;
  19155. var gridX1 = gridX + 1;
  19156. var gridZ1 = gridZ + 1;
  19157. var segment_width = this.width / gridX;
  19158. var segment_height = this.height / gridZ;
  19159. var normal = new THREE.Vector3( 0, 0, 1 );
  19160. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19161. for ( ix = 0; ix < gridX1; ix ++ ) {
  19162. var x = ix * segment_width - width_half;
  19163. var y = iz * segment_height - height_half;
  19164. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19165. }
  19166. }
  19167. for ( iz = 0; iz < gridZ; iz ++ ) {
  19168. for ( ix = 0; ix < gridX; ix ++ ) {
  19169. var a = ix + gridX1 * iz;
  19170. var b = ix + gridX1 * ( iz + 1 );
  19171. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19172. var d = ( ix + 1 ) + gridX1 * iz;
  19173. var face = new THREE.Face4( a, b, c, d );
  19174. face.normal.copy( normal );
  19175. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  19176. this.faces.push( face );
  19177. this.faceVertexUvs[ 0 ].push( [
  19178. new THREE.Vector2( ix / gridX, 1 - iz / gridZ ),
  19179. new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  19180. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  19181. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  19182. ] );
  19183. }
  19184. }
  19185. this.computeCentroids();
  19186. };
  19187. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19188. /**
  19189. * @author mrdoob / http://mrdoob.com/
  19190. */
  19191. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19192. THREE.Geometry.call( this );
  19193. this.radius = radius || 50;
  19194. this.widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19195. this.heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19196. phiStart = phiStart !== undefined ? phiStart : 0;
  19197. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19198. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19199. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19200. var x, y, vertices = [], uvs = [];
  19201. for ( y = 0; y <= this.heightSegments; y ++ ) {
  19202. var verticesRow = [];
  19203. var uvsRow = [];
  19204. for ( x = 0; x <= this.widthSegments; x ++ ) {
  19205. var u = x / this.widthSegments;
  19206. var v = y / this.heightSegments;
  19207. var vertex = new THREE.Vector3();
  19208. vertex.x = - this.radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19209. vertex.y = this.radius * Math.cos( thetaStart + v * thetaLength );
  19210. vertex.z = this.radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19211. this.vertices.push( vertex );
  19212. verticesRow.push( this.vertices.length - 1 );
  19213. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19214. }
  19215. vertices.push( verticesRow );
  19216. uvs.push( uvsRow );
  19217. }
  19218. for ( y = 0; y < this.heightSegments; y ++ ) {
  19219. for ( x = 0; x < this.widthSegments; x ++ ) {
  19220. var v1 = vertices[ y ][ x + 1 ];
  19221. var v2 = vertices[ y ][ x ];
  19222. var v3 = vertices[ y + 1 ][ x ];
  19223. var v4 = vertices[ y + 1 ][ x + 1 ];
  19224. var n1 = this.vertices[ v1 ].clone().normalize();
  19225. var n2 = this.vertices[ v2 ].clone().normalize();
  19226. var n3 = this.vertices[ v3 ].clone().normalize();
  19227. var n4 = this.vertices[ v4 ].clone().normalize();
  19228. var uv1 = uvs[ y ][ x + 1 ].clone();
  19229. var uv2 = uvs[ y ][ x ].clone();
  19230. var uv3 = uvs[ y + 1 ][ x ].clone();
  19231. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19232. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  19233. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19234. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19235. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  19236. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19237. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19238. } else {
  19239. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  19240. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  19241. }
  19242. }
  19243. }
  19244. this.computeCentroids();
  19245. this.computeFaceNormals();
  19246. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19247. };
  19248. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19249. /**
  19250. * @author zz85 / http://www.lab4games.net/zz85/blog
  19251. * @author alteredq / http://alteredqualia.com/
  19252. *
  19253. * For creating 3D text geometry in three.js
  19254. *
  19255. * Text = 3D Text
  19256. *
  19257. * parameters = {
  19258. * size: <float>, // size of the text
  19259. * height: <float>, // thickness to extrude text
  19260. * curveSegments: <int>, // number of points on the curves
  19261. *
  19262. * font: <string>, // font name
  19263. * weight: <string>, // font weight (normal, bold)
  19264. * style: <string>, // font style (normal, italics)
  19265. *
  19266. * bevelEnabled: <bool>, // turn on bevel
  19267. * bevelThickness: <float>, // how deep into text bevel goes
  19268. * bevelSize: <float>, // how far from text outline is bevel
  19269. * }
  19270. *
  19271. */
  19272. /* Usage Examples
  19273. // TextGeometry wrapper
  19274. var text3d = new TextGeometry( text, options );
  19275. // Complete manner
  19276. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19277. var text3d = new ExtrudeGeometry( textShapes, options );
  19278. */
  19279. THREE.TextGeometry = function ( text, parameters ) {
  19280. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19281. // translate parameters to ExtrudeGeometry API
  19282. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19283. // defaults
  19284. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19285. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19286. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19287. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19288. };
  19289. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19290. /**
  19291. * @author oosmoxiecode
  19292. * @author mrdoob / http://mrdoob.com/
  19293. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19294. */
  19295. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19296. THREE.Geometry.call( this );
  19297. var scope = this;
  19298. this.radius = radius || 100;
  19299. this.tube = tube || 40;
  19300. this.radialSegments = radialSegments || 8;
  19301. this.tubularSegments = tubularSegments || 6;
  19302. this.arc = arc || Math.PI * 2;
  19303. var center = new THREE.Vector3(), uvs = [], normals = [];
  19304. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  19305. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  19306. var u = i / this.tubularSegments * this.arc;
  19307. var v = j / this.radialSegments * Math.PI * 2;
  19308. center.x = this.radius * Math.cos( u );
  19309. center.y = this.radius * Math.sin( u );
  19310. var vertex = new THREE.Vector3();
  19311. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  19312. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  19313. vertex.z = this.tube * Math.sin( v );
  19314. this.vertices.push( vertex );
  19315. uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
  19316. normals.push( vertex.clone().sub( center ).normalize() );
  19317. }
  19318. }
  19319. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  19320. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  19321. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  19322. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19323. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  19324. var d = ( this.tubularSegments + 1 ) * j + i;
  19325. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  19326. face.normal.add( normals[ a ] );
  19327. face.normal.add( normals[ b ] );
  19328. face.normal.add( normals[ c ] );
  19329. face.normal.add( normals[ d ] );
  19330. face.normal.normalize();
  19331. this.faces.push( face );
  19332. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19333. }
  19334. }
  19335. this.computeCentroids();
  19336. };
  19337. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19338. /**
  19339. * @author oosmoxiecode
  19340. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19341. */
  19342. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19343. THREE.Geometry.call( this );
  19344. var scope = this;
  19345. this.radius = radius || 100;
  19346. this.tube = tube || 40;
  19347. this.radialSegments = radialSegments || 64;
  19348. this.tubularSegments = tubularSegments || 8;
  19349. this.p = p || 2;
  19350. this.q = q || 3;
  19351. this.heightScale = heightScale || 1;
  19352. this.grid = new Array( this.radialSegments );
  19353. var tang = new THREE.Vector3();
  19354. var n = new THREE.Vector3();
  19355. var bitan = new THREE.Vector3();
  19356. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19357. this.grid[ i ] = new Array( this.tubularSegments );
  19358. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19359. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  19360. var v = j / this.tubularSegments * 2 * Math.PI;
  19361. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  19362. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  19363. var cx, cy;
  19364. tang.subVectors( p2, p1 );
  19365. n.addVectors( p2, p1 );
  19366. bitan.crossVectors( tang, n );
  19367. n.crossVectors( bitan, tang );
  19368. bitan.normalize();
  19369. n.normalize();
  19370. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19371. cy = this.tube * Math.sin( v );
  19372. p1.x += cx * n.x + cy * bitan.x;
  19373. p1.y += cx * n.y + cy * bitan.y;
  19374. p1.z += cx * n.z + cy * bitan.z;
  19375. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  19376. }
  19377. }
  19378. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19379. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19380. var ip = ( i + 1 ) % this.radialSegments;
  19381. var jp = ( j + 1 ) % this.tubularSegments;
  19382. var a = this.grid[ i ][ j ];
  19383. var b = this.grid[ ip ][ j ];
  19384. var c = this.grid[ ip ][ jp ];
  19385. var d = this.grid[ i ][ jp ];
  19386. var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
  19387. var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  19388. var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19389. var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19390. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19391. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  19392. }
  19393. }
  19394. this.computeCentroids();
  19395. this.computeFaceNormals();
  19396. this.computeVertexNormals();
  19397. function vert( x, y, z ) {
  19398. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19399. }
  19400. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  19401. var cu = Math.cos( u );
  19402. var cv = Math.cos( v );
  19403. var su = Math.sin( u );
  19404. var quOverP = in_q / in_p * u;
  19405. var cs = Math.cos( quOverP );
  19406. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19407. var ty = radius * ( 2 + cs ) * su * 0.5;
  19408. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19409. return new THREE.Vector3( tx, ty, tz );
  19410. }
  19411. };
  19412. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19413. /**
  19414. * @author WestLangley / https://github.com/WestLangley
  19415. * @author zz85 / https://github.com/zz85
  19416. * @author miningold / https://github.com/miningold
  19417. *
  19418. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19419. *
  19420. * Creates a tube which extrudes along a 3d spline
  19421. *
  19422. * Uses parallel transport frames as described in
  19423. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19424. */
  19425. THREE.TubeGeometry = function( path, segments, radius, radiusSegments, closed, debug ) {
  19426. THREE.Geometry.call( this );
  19427. this.path = path;
  19428. this.segments = segments || 64;
  19429. this.radius = radius || 1;
  19430. this.radiusSegments = radiusSegments || 8;
  19431. this.closed = closed || false;
  19432. if ( debug ) this.debug = new THREE.Object3D();
  19433. this.grid = [];
  19434. var scope = this,
  19435. tangent,
  19436. normal,
  19437. binormal,
  19438. numpoints = this.segments + 1,
  19439. x, y, z,
  19440. tx, ty, tz,
  19441. u, v,
  19442. cx, cy,
  19443. pos, pos2 = new THREE.Vector3(),
  19444. i, j,
  19445. ip, jp,
  19446. a, b, c, d,
  19447. uva, uvb, uvc, uvd;
  19448. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  19449. tangents = frames.tangents,
  19450. normals = frames.normals,
  19451. binormals = frames.binormals;
  19452. // proxy internals
  19453. this.tangents = tangents;
  19454. this.normals = normals;
  19455. this.binormals = binormals;
  19456. function vert( x, y, z ) {
  19457. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19458. }
  19459. // consruct the grid
  19460. for ( i = 0; i < numpoints; i++ ) {
  19461. this.grid[ i ] = [];
  19462. u = i / ( numpoints - 1 );
  19463. pos = path.getPointAt( u );
  19464. tangent = tangents[ i ];
  19465. normal = normals[ i ];
  19466. binormal = binormals[ i ];
  19467. if ( this.debug ) {
  19468. this.debug.add( new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff ) );
  19469. this.debug.add( new THREE.ArrowHelper(normal, pos, radius, 0xff0000 ) );
  19470. this.debug.add( new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00 ) );
  19471. }
  19472. for ( j = 0; j < this.radiusSegments; j++ ) {
  19473. v = j / this.radiusSegments * 2 * Math.PI;
  19474. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19475. cy = this.radius * Math.sin( v );
  19476. pos2.copy( pos );
  19477. pos2.x += cx * normal.x + cy * binormal.x;
  19478. pos2.y += cx * normal.y + cy * binormal.y;
  19479. pos2.z += cx * normal.z + cy * binormal.z;
  19480. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  19481. }
  19482. }
  19483. // construct the mesh
  19484. for ( i = 0; i < this.segments; i++ ) {
  19485. for ( j = 0; j < this.radiusSegments; j++ ) {
  19486. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  19487. jp = (j + 1) % this.radiusSegments;
  19488. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  19489. b = this.grid[ ip ][ j ];
  19490. c = this.grid[ ip ][ jp ];
  19491. d = this.grid[ i ][ jp ];
  19492. uva = new THREE.Vector2( i / this.segments, j / this.radiusSegments );
  19493. uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radiusSegments );
  19494. uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radiusSegments );
  19495. uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radiusSegments );
  19496. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19497. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  19498. }
  19499. }
  19500. this.computeCentroids();
  19501. this.computeFaceNormals();
  19502. this.computeVertexNormals();
  19503. };
  19504. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19505. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19506. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  19507. var tangent = new THREE.Vector3(),
  19508. normal = new THREE.Vector3(),
  19509. binormal = new THREE.Vector3(),
  19510. tangents = [],
  19511. normals = [],
  19512. binormals = [],
  19513. vec = new THREE.Vector3(),
  19514. mat = new THREE.Matrix4(),
  19515. numpoints = segments + 1,
  19516. theta,
  19517. epsilon = 0.0001,
  19518. smallest,
  19519. tx, ty, tz,
  19520. i, u, v;
  19521. // expose internals
  19522. this.tangents = tangents;
  19523. this.normals = normals;
  19524. this.binormals = binormals;
  19525. // compute the tangent vectors for each segment on the path
  19526. for ( i = 0; i < numpoints; i++ ) {
  19527. u = i / ( numpoints - 1 );
  19528. tangents[ i ] = path.getTangentAt( u );
  19529. tangents[ i ].normalize();
  19530. }
  19531. initialNormal3();
  19532. function initialNormal1(lastBinormal) {
  19533. // fixed start binormal. Has dangers of 0 vectors
  19534. normals[ 0 ] = new THREE.Vector3();
  19535. binormals[ 0 ] = new THREE.Vector3();
  19536. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19537. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  19538. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19539. }
  19540. function initialNormal2() {
  19541. // This uses the Frenet-Serret formula for deriving binormal
  19542. var t2 = path.getTangentAt( epsilon );
  19543. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  19544. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  19545. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  19546. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19547. }
  19548. function initialNormal3() {
  19549. // select an initial normal vector perpenicular to the first tangent vector,
  19550. // and in the direction of the smallest tangent xyz component
  19551. normals[ 0 ] = new THREE.Vector3();
  19552. binormals[ 0 ] = new THREE.Vector3();
  19553. smallest = Number.MAX_VALUE;
  19554. tx = Math.abs( tangents[ 0 ].x );
  19555. ty = Math.abs( tangents[ 0 ].y );
  19556. tz = Math.abs( tangents[ 0 ].z );
  19557. if ( tx <= smallest ) {
  19558. smallest = tx;
  19559. normal.set( 1, 0, 0 );
  19560. }
  19561. if ( ty <= smallest ) {
  19562. smallest = ty;
  19563. normal.set( 0, 1, 0 );
  19564. }
  19565. if ( tz <= smallest ) {
  19566. normal.set( 0, 0, 1 );
  19567. }
  19568. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19569. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19570. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19571. }
  19572. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19573. for ( i = 1; i < numpoints; i++ ) {
  19574. normals[ i ] = normals[ i-1 ].clone();
  19575. binormals[ i ] = binormals[ i-1 ].clone();
  19576. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  19577. if ( vec.length() > epsilon ) {
  19578. vec.normalize();
  19579. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  19580. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19581. }
  19582. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19583. }
  19584. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19585. if ( closed ) {
  19586. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  19587. theta /= ( numpoints - 1 );
  19588. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  19589. theta = -theta;
  19590. }
  19591. for ( i = 1; i < numpoints; i++ ) {
  19592. // twist a little...
  19593. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19594. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19595. }
  19596. }
  19597. };
  19598. /**
  19599. * @author clockworkgeek / https://github.com/clockworkgeek
  19600. * @author timothypratley / https://github.com/timothypratley
  19601. */
  19602. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  19603. THREE.Geometry.call( this );
  19604. radius = radius || 1;
  19605. detail = detail || 0;
  19606. var that = this;
  19607. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  19608. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  19609. }
  19610. var midpoints = [], p = this.vertices;
  19611. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19612. make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );
  19613. }
  19614. this.mergeVertices();
  19615. // Apply radius
  19616. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19617. this.vertices[ i ].multiplyScalar( radius );
  19618. }
  19619. // Project vector onto sphere's surface
  19620. function prepare( vector ) {
  19621. var vertex = vector.normalize().clone();
  19622. vertex.index = that.vertices.push( vertex ) - 1;
  19623. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19624. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19625. var v = inclination( vector ) / Math.PI + 0.5;
  19626. vertex.uv = new THREE.Vector2( u, 1 - v );
  19627. return vertex;
  19628. }
  19629. // Approximate a curved face with recursively sub-divided triangles.
  19630. function make( v1, v2, v3, detail ) {
  19631. if ( detail < 1 ) {
  19632. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19633. face.centroid.add( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  19634. face.normal = face.centroid.clone().normalize();
  19635. that.faces.push( face );
  19636. var azi = azimuth( face.centroid );
  19637. that.faceVertexUvs[ 0 ].push( [
  19638. correctUV( v1.uv, v1, azi ),
  19639. correctUV( v2.uv, v2, azi ),
  19640. correctUV( v3.uv, v3, azi )
  19641. ] );
  19642. } else {
  19643. detail -= 1;
  19644. // split triangle into 4 smaller triangles
  19645. make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
  19646. make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
  19647. make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
  19648. make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant
  19649. }
  19650. }
  19651. function midpoint( v1, v2 ) {
  19652. if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
  19653. if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];
  19654. var mid = midpoints[ v1.index ][ v2.index ];
  19655. if ( mid === undefined ) {
  19656. // generate mean point and project to surface with prepare()
  19657. midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
  19658. new THREE.Vector3().addVectors( v1, v2 ).divideScalar( 2 )
  19659. );
  19660. }
  19661. return mid;
  19662. }
  19663. // Angle around the Y axis, counter-clockwise when looking from above.
  19664. function azimuth( vector ) {
  19665. return Math.atan2( vector.z, -vector.x );
  19666. }
  19667. // Angle above the XZ plane.
  19668. function inclination( vector ) {
  19669. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19670. }
  19671. // Texture fixing helper. Spheres have some odd behaviours.
  19672. function correctUV( uv, vector, azimuth ) {
  19673. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  19674. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  19675. return uv;
  19676. }
  19677. this.computeCentroids();
  19678. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19679. };
  19680. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19681. /**
  19682. * @author timothypratley / https://github.com/timothypratley
  19683. */
  19684. THREE.IcosahedronGeometry = function ( radius, detail ) {
  19685. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19686. var vertices = [
  19687. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  19688. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  19689. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  19690. ];
  19691. var faces = [
  19692. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  19693. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  19694. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  19695. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  19696. ];
  19697. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19698. };
  19699. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19700. /**
  19701. * @author timothypratley / https://github.com/timothypratley
  19702. */
  19703. THREE.OctahedronGeometry = function ( radius, detail ) {
  19704. var vertices = [
  19705. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  19706. ];
  19707. var faces = [
  19708. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  19709. ];
  19710. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19711. };
  19712. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19713. /**
  19714. * @author timothypratley / https://github.com/timothypratley
  19715. */
  19716. THREE.TetrahedronGeometry = function ( radius, detail ) {
  19717. var vertices = [
  19718. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  19719. ];
  19720. var faces = [
  19721. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  19722. ];
  19723. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19724. };
  19725. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19726. /**
  19727. * @author zz85 / https://github.com/zz85
  19728. * Parametric Surfaces Geometry
  19729. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  19730. *
  19731. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  19732. *
  19733. */
  19734. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  19735. THREE.Geometry.call( this );
  19736. var verts = this.vertices;
  19737. var faces = this.faces;
  19738. var uvs = this.faceVertexUvs[ 0 ];
  19739. useTris = (useTris === undefined) ? false : useTris;
  19740. var i, il, j, p;
  19741. var u, v;
  19742. var stackCount = stacks + 1;
  19743. var sliceCount = slices + 1;
  19744. for ( i = 0; i <= stacks; i ++ ) {
  19745. v = i / stacks;
  19746. for ( j = 0; j <= slices; j ++ ) {
  19747. u = j / slices;
  19748. p = func( u, v );
  19749. verts.push( p );
  19750. }
  19751. }
  19752. var a, b, c, d;
  19753. var uva, uvb, uvc, uvd;
  19754. for ( i = 0; i < stacks; i ++ ) {
  19755. for ( j = 0; j < slices; j ++ ) {
  19756. a = i * sliceCount + j;
  19757. b = i * sliceCount + j + 1;
  19758. c = (i + 1) * sliceCount + j;
  19759. d = (i + 1) * sliceCount + j + 1;
  19760. uva = new THREE.Vector2( j / slices, i / stacks );
  19761. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  19762. uvc = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  19763. uvd = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  19764. if ( useTris ) {
  19765. faces.push( new THREE.Face3( a, b, c ) );
  19766. faces.push( new THREE.Face3( b, d, c ) );
  19767. uvs.push( [ uva, uvb, uvc ] );
  19768. uvs.push( [ uvb, uvd, uvc ] );
  19769. } else {
  19770. faces.push( new THREE.Face4( a, b, d, c ) );
  19771. uvs.push( [ uva, uvb, uvd, uvc ] );
  19772. }
  19773. }
  19774. }
  19775. // console.log(this);
  19776. // magic bullet
  19777. // var diff = this.mergeVertices();
  19778. // console.log('removed ', diff, ' vertices by merging');
  19779. this.computeCentroids();
  19780. this.computeFaceNormals();
  19781. this.computeVertexNormals();
  19782. };
  19783. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19784. /**
  19785. * @author qiao / https://github.com/qiao
  19786. * @fileoverview This is a convex hull generator using the incremental method.
  19787. * The complexity is O(n^2) where n is the number of vertices.
  19788. * O(nlogn) algorithms do exist, but they are much more complicated.
  19789. *
  19790. * Benchmark:
  19791. *
  19792. * Platform: CPU: P7350 @2.00GHz Engine: V8
  19793. *
  19794. * Num Vertices Time(ms)
  19795. *
  19796. * 10 1
  19797. * 20 3
  19798. * 30 19
  19799. * 40 48
  19800. * 50 107
  19801. */
  19802. THREE.ConvexGeometry = function( vertices ) {
  19803. THREE.Geometry.call( this );
  19804. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  19805. for ( var i = 3; i < vertices.length; i++ ) {
  19806. addPoint( i );
  19807. }
  19808. function addPoint( vertexId ) {
  19809. var vertex = vertices[ vertexId ].clone();
  19810. var mag = vertex.length();
  19811. vertex.x += mag * randomOffset();
  19812. vertex.y += mag * randomOffset();
  19813. vertex.z += mag * randomOffset();
  19814. var hole = [];
  19815. for ( var f = 0; f < faces.length; ) {
  19816. var face = faces[ f ];
  19817. // for each face, if the vertex can see it,
  19818. // then we try to add the face's edges into the hole.
  19819. if ( visible( face, vertex ) ) {
  19820. for ( var e = 0; e < 3; e++ ) {
  19821. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  19822. var boundary = true;
  19823. // remove duplicated edges.
  19824. for ( var h = 0; h < hole.length; h++ ) {
  19825. if ( equalEdge( hole[ h ], edge ) ) {
  19826. hole[ h ] = hole[ hole.length - 1 ];
  19827. hole.pop();
  19828. boundary = false;
  19829. break;
  19830. }
  19831. }
  19832. if ( boundary ) {
  19833. hole.push( edge );
  19834. }
  19835. }
  19836. // remove faces[ f ]
  19837. faces[ f ] = faces[ faces.length - 1 ];
  19838. faces.pop();
  19839. } else { // not visible
  19840. f++;
  19841. }
  19842. }
  19843. // construct the new faces formed by the edges of the hole and the vertex
  19844. for ( var h = 0; h < hole.length; h++ ) {
  19845. faces.push( [
  19846. hole[ h ][ 0 ],
  19847. hole[ h ][ 1 ],
  19848. vertexId
  19849. ] );
  19850. }
  19851. }
  19852. /**
  19853. * Whether the face is visible from the vertex
  19854. */
  19855. function visible( face, vertex ) {
  19856. var va = vertices[ face[ 0 ] ];
  19857. var vb = vertices[ face[ 1 ] ];
  19858. var vc = vertices[ face[ 2 ] ];
  19859. var n = normal( va, vb, vc );
  19860. // distance from face to origin
  19861. var dist = n.dot( va );
  19862. return n.dot( vertex ) >= dist;
  19863. }
  19864. /**
  19865. * Face normal
  19866. */
  19867. function normal( va, vb, vc ) {
  19868. var cb = new THREE.Vector3();
  19869. var ab = new THREE.Vector3();
  19870. cb.subVectors( vc, vb );
  19871. ab.subVectors( va, vb );
  19872. cb.cross( ab );
  19873. cb.normalize();
  19874. return cb;
  19875. }
  19876. /**
  19877. * Detect whether two edges are equal.
  19878. * Note that when constructing the convex hull, two same edges can only
  19879. * be of the negative direction.
  19880. */
  19881. function equalEdge( ea, eb ) {
  19882. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  19883. }
  19884. /**
  19885. * Create a random offset between -1e-6 and 1e-6.
  19886. */
  19887. function randomOffset() {
  19888. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  19889. }
  19890. /**
  19891. * XXX: Not sure if this is the correct approach. Need someone to review.
  19892. */
  19893. function vertexUv( vertex ) {
  19894. var mag = vertex.length();
  19895. return new THREE.Vector2( vertex.x / mag, vertex.y / mag );
  19896. }
  19897. // Push vertices into `this.vertices`, skipping those inside the hull
  19898. var id = 0;
  19899. var newId = new Array( vertices.length ); // map from old vertex id to new id
  19900. for ( var i = 0; i < faces.length; i++ ) {
  19901. var face = faces[ i ];
  19902. for ( var j = 0; j < 3; j++ ) {
  19903. if ( newId[ face[ j ] ] === undefined ) {
  19904. newId[ face[ j ] ] = id++;
  19905. this.vertices.push( vertices[ face[ j ] ] );
  19906. }
  19907. face[ j ] = newId[ face[ j ] ];
  19908. }
  19909. }
  19910. // Convert faces into instances of THREE.Face3
  19911. for ( var i = 0; i < faces.length; i++ ) {
  19912. this.faces.push( new THREE.Face3(
  19913. faces[ i ][ 0 ],
  19914. faces[ i ][ 1 ],
  19915. faces[ i ][ 2 ]
  19916. ) );
  19917. }
  19918. // Compute UVs
  19919. for ( var i = 0; i < this.faces.length; i++ ) {
  19920. var face = this.faces[ i ];
  19921. this.faceVertexUvs[ 0 ].push( [
  19922. vertexUv( this.vertices[ face.a ] ),
  19923. vertexUv( this.vertices[ face.b ] ),
  19924. vertexUv( this.vertices[ face.c ])
  19925. ] );
  19926. }
  19927. this.computeCentroids();
  19928. this.computeFaceNormals();
  19929. this.computeVertexNormals();
  19930. };
  19931. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19932. /**
  19933. * @author sroucheray / http://sroucheray.org/
  19934. * @author mrdoob / http://mrdoob.com/
  19935. */
  19936. THREE.AxisHelper = function ( size ) {
  19937. var geometry = new THREE.Geometry();
  19938. geometry.vertices.push(
  19939. new THREE.Vector3(), new THREE.Vector3( size || 1, 0, 0 ),
  19940. new THREE.Vector3(), new THREE.Vector3( 0, size || 1, 0 ),
  19941. new THREE.Vector3(), new THREE.Vector3( 0, 0, size || 1 )
  19942. );
  19943. geometry.colors.push(
  19944. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  19945. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  19946. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  19947. );
  19948. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  19949. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  19950. };
  19951. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  19952. /**
  19953. * @author WestLangley / http://github.com/WestLangley
  19954. * @author zz85 / https://github.com/zz85
  19955. * @author bhouston / https://exocortex.com
  19956. *
  19957. * Creates an arrow for visualizing directions
  19958. *
  19959. * Parameters:
  19960. * dir - Vector3
  19961. * origin - Vector3
  19962. * length - Number
  19963. * hex - color in hex value
  19964. */
  19965. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  19966. THREE.Object3D.call( this );
  19967. if ( length === undefined ) length = 20;
  19968. if ( hex === undefined ) hex = 0xffff00;
  19969. var lineGeometry = new THREE.Geometry();
  19970. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  19971. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  19972. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  19973. this.add( this.line );
  19974. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  19975. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  19976. this.cone.position.set( 0, 1, 0 );
  19977. this.add( this.cone );
  19978. if ( origin instanceof THREE.Vector3 ) this.position = origin;
  19979. this.setDirection( dir );
  19980. this.setLength( length );
  19981. };
  19982. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  19983. THREE.ArrowHelper.prototype.setDirection = function ( dir ) {
  19984. var d = THREE.ArrowHelper.__v1.copy( dir ).normalize();
  19985. if ( d.y > 0.999 ) {
  19986. this.rotation.set( 0, 0, 0 );
  19987. } else if ( d.y < - 0.999 ) {
  19988. this.rotation.set( Math.PI, 0, 0 );
  19989. } else {
  19990. var axis = THREE.ArrowHelper.__v2.set( d.z, 0, - d.x ).normalize();
  19991. var radians = Math.acos( d.y );
  19992. var quaternion = THREE.ArrowHelper.__q1.setFromAxisAngle( axis, radians );
  19993. this.rotation.setEulerFromQuaternion( quaternion, this.eulerOrder );
  19994. }
  19995. };
  19996. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  19997. this.scale.set( length, length, length );
  19998. };
  19999. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  20000. this.line.material.color.setHex( hex );
  20001. this.cone.material.color.setHex( hex );
  20002. };
  20003. THREE.ArrowHelper.__v1 = new THREE.Vector3();
  20004. THREE.ArrowHelper.__v2 = new THREE.Vector3();
  20005. THREE.ArrowHelper.__q1 = new THREE.Quaternion();
  20006. /**
  20007. * @author alteredq / http://alteredqualia.com/
  20008. *
  20009. * - shows frustum, line of sight and up of the camera
  20010. * - suitable for fast updates
  20011. * - based on frustum visualization in lightgl.js shadowmap example
  20012. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20013. */
  20014. THREE.CameraHelper = function ( camera ) {
  20015. THREE.Line.call( this );
  20016. var scope = this;
  20017. this.geometry = new THREE.Geometry();
  20018. this.material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20019. this.type = THREE.LinePieces;
  20020. this.matrixWorld = camera.matrixWorld;
  20021. this.matrixAutoUpdate = false;
  20022. this.pointMap = {};
  20023. // colors
  20024. var hexFrustum = 0xffaa00;
  20025. var hexCone = 0xff0000;
  20026. var hexUp = 0x00aaff;
  20027. var hexTarget = 0xffffff;
  20028. var hexCross = 0x333333;
  20029. // near
  20030. addLine( "n1", "n2", hexFrustum );
  20031. addLine( "n2", "n4", hexFrustum );
  20032. addLine( "n4", "n3", hexFrustum );
  20033. addLine( "n3", "n1", hexFrustum );
  20034. // far
  20035. addLine( "f1", "f2", hexFrustum );
  20036. addLine( "f2", "f4", hexFrustum );
  20037. addLine( "f4", "f3", hexFrustum );
  20038. addLine( "f3", "f1", hexFrustum );
  20039. // sides
  20040. addLine( "n1", "f1", hexFrustum );
  20041. addLine( "n2", "f2", hexFrustum );
  20042. addLine( "n3", "f3", hexFrustum );
  20043. addLine( "n4", "f4", hexFrustum );
  20044. // cone
  20045. addLine( "p", "n1", hexCone );
  20046. addLine( "p", "n2", hexCone );
  20047. addLine( "p", "n3", hexCone );
  20048. addLine( "p", "n4", hexCone );
  20049. // up
  20050. addLine( "u1", "u2", hexUp );
  20051. addLine( "u2", "u3", hexUp );
  20052. addLine( "u3", "u1", hexUp );
  20053. // target
  20054. addLine( "c", "t", hexTarget );
  20055. addLine( "p", "c", hexCross );
  20056. // cross
  20057. addLine( "cn1", "cn2", hexCross );
  20058. addLine( "cn3", "cn4", hexCross );
  20059. addLine( "cf1", "cf2", hexCross );
  20060. addLine( "cf3", "cf4", hexCross );
  20061. this.camera = camera;
  20062. function addLine( a, b, hex ) {
  20063. addPoint( a, hex );
  20064. addPoint( b, hex );
  20065. }
  20066. function addPoint( id, hex ) {
  20067. scope.geometry.vertices.push( new THREE.Vector3() );
  20068. scope.geometry.colors.push( new THREE.Color( hex ) );
  20069. if ( scope.pointMap[ id ] === undefined ) scope.pointMap[ id ] = [];
  20070. scope.pointMap[ id ].push( scope.geometry.vertices.length - 1 );
  20071. }
  20072. this.update( camera );
  20073. };
  20074. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20075. THREE.CameraHelper.prototype.update = function () {
  20076. var scope = this;
  20077. var w = 1, h = 1;
  20078. // we need just camera projection matrix
  20079. // world matrix must be identity
  20080. THREE.CameraHelper.__c.projectionMatrix.copy( this.camera.projectionMatrix );
  20081. // center / target
  20082. setPoint( "c", 0, 0, -1 );
  20083. setPoint( "t", 0, 0, 1 );
  20084. // near
  20085. setPoint( "n1", -w, -h, -1 );
  20086. setPoint( "n2", w, -h, -1 );
  20087. setPoint( "n3", -w, h, -1 );
  20088. setPoint( "n4", w, h, -1 );
  20089. // far
  20090. setPoint( "f1", -w, -h, 1 );
  20091. setPoint( "f2", w, -h, 1 );
  20092. setPoint( "f3", -w, h, 1 );
  20093. setPoint( "f4", w, h, 1 );
  20094. // up
  20095. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  20096. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  20097. setPoint( "u3", 0, h * 2, -1 );
  20098. // cross
  20099. setPoint( "cf1", -w, 0, 1 );
  20100. setPoint( "cf2", w, 0, 1 );
  20101. setPoint( "cf3", 0, -h, 1 );
  20102. setPoint( "cf4", 0, h, 1 );
  20103. setPoint( "cn1", -w, 0, -1 );
  20104. setPoint( "cn2", w, 0, -1 );
  20105. setPoint( "cn3", 0, -h, -1 );
  20106. setPoint( "cn4", 0, h, -1 );
  20107. function setPoint( point, x, y, z ) {
  20108. THREE.CameraHelper.__v.set( x, y, z );
  20109. THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
  20110. var points = scope.pointMap[ point ];
  20111. if ( points !== undefined ) {
  20112. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20113. scope.geometry.vertices[ points[ i ] ].copy( THREE.CameraHelper.__v );
  20114. }
  20115. }
  20116. }
  20117. this.geometry.verticesNeedUpdate = true;
  20118. };
  20119. THREE.CameraHelper.__projector = new THREE.Projector();
  20120. THREE.CameraHelper.__v = new THREE.Vector3();
  20121. THREE.CameraHelper.__c = new THREE.Camera();
  20122. /**
  20123. * @author alteredq / http://alteredqualia.com/
  20124. *
  20125. * - shows directional light color, intensity, position, orientation and target
  20126. */
  20127. THREE.DirectionalLightHelper = function ( light, sphereSize ) {
  20128. THREE.Object3D.call( this );
  20129. this.light = light;
  20130. // position
  20131. this.position = light.position;
  20132. // direction
  20133. this.direction = new THREE.Vector3();
  20134. this.direction.subVectors( light.target.position, light.position );
  20135. // color
  20136. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20137. this.color = light.color.clone();
  20138. this.color.multiplyScalar( intensity );
  20139. var hexColor = this.color.getHex();
  20140. // light helper
  20141. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20142. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20143. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20144. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20145. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20146. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20147. this.add( this.lightSphere );
  20148. this.add( this.lightRays );
  20149. this.lightSphere.properties.isGizmo = true;
  20150. this.lightSphere.properties.gizmoSubject = light;
  20151. this.lightSphere.properties.gizmoRoot = this;
  20152. // light target helper
  20153. this.targetSphere = null;
  20154. if ( light.target.properties.targetInverse !== undefined ) {
  20155. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  20156. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  20157. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  20158. this.targetSphere.position = light.target.position;
  20159. this.targetSphere.properties.isGizmo = true;
  20160. this.targetSphere.properties.gizmoSubject = light.target;
  20161. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  20162. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20163. var lineGeometry = new THREE.Geometry();
  20164. lineGeometry.vertices.push( this.position.clone() );
  20165. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  20166. lineGeometry.computeLineDistances();
  20167. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  20168. this.targetLine.properties.isGizmo = true;
  20169. }
  20170. //
  20171. this.properties.isGizmo = true;
  20172. }
  20173. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20174. THREE.DirectionalLightHelper.prototype.update = function () {
  20175. // update arrow orientation
  20176. // pointing from light to target
  20177. this.direction.subVectors( this.light.target.position, this.light.position );
  20178. // update arrow, spheres, rays and line colors to light color * light intensity
  20179. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20180. this.color.copy( this.light.color );
  20181. this.color.multiplyScalar( intensity );
  20182. this.lightSphere.material.color.copy( this.color );
  20183. this.lightRays.material.color.copy( this.color );
  20184. // Only update targetSphere and targetLine if available
  20185. if ( this.targetSphere !== null ) {
  20186. this.targetSphere.material.color.copy( this.color );
  20187. this.targetLine.material.color.copy( this.color );
  20188. // update target line vertices
  20189. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  20190. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  20191. this.targetLine.geometry.computeLineDistances();
  20192. this.targetLine.geometry.verticesNeedUpdate = true;
  20193. }
  20194. }
  20195. /**
  20196. * @author alteredq / http://alteredqualia.com/
  20197. *
  20198. * - shows hemisphere light intensity, sky and ground colors and directions
  20199. */
  20200. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  20201. THREE.Object3D.call( this );
  20202. this.light = light;
  20203. // position
  20204. this.position = light.position;
  20205. //
  20206. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20207. // sky color
  20208. this.color = light.color.clone();
  20209. this.color.multiplyScalar( intensity );
  20210. var hexColor = this.color.getHex();
  20211. // ground color
  20212. this.groundColor = light.groundColor.clone();
  20213. this.groundColor.multiplyScalar( intensity );
  20214. var hexColorGround = this.groundColor.getHex();
  20215. // double colored light bulb
  20216. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, 0, Math.PI * 0.5 );
  20217. var bulbGroundGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, Math.PI * 0.5, Math.PI );
  20218. var bulbSkyMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20219. var bulbGroundMaterial = new THREE.MeshBasicMaterial( { color: hexColorGround, fog: false } );
  20220. for ( var i = 0, il = bulbGeometry.faces.length; i < il; i ++ ) {
  20221. bulbGeometry.faces[ i ].materialIndex = 0;
  20222. }
  20223. for ( var i = 0, il = bulbGroundGeometry.faces.length; i < il; i ++ ) {
  20224. bulbGroundGeometry.faces[ i ].materialIndex = 1;
  20225. }
  20226. THREE.GeometryUtils.merge( bulbGeometry, bulbGroundGeometry );
  20227. this.lightSphere = new THREE.Mesh( bulbGeometry, new THREE.MeshFaceMaterial( [ bulbSkyMaterial, bulbGroundMaterial ] ) );
  20228. // arrows for sky and ground light directions
  20229. this.lightArrow = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * 1.1, 0 ), arrowLength, hexColor );
  20230. this.lightArrow.rotation.x = Math.PI;
  20231. this.lightArrowGround = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * -1.1, 0 ), arrowLength, hexColorGround );
  20232. var joint = new THREE.Object3D();
  20233. joint.rotation.x = -Math.PI * 0.5;
  20234. joint.add( this.lightSphere );
  20235. joint.add( this.lightArrow );
  20236. joint.add( this.lightArrowGround );
  20237. this.add( joint );
  20238. //
  20239. this.lightSphere.properties.isGizmo = true;
  20240. this.lightSphere.properties.gizmoSubject = light;
  20241. this.lightSphere.properties.gizmoRoot = this;
  20242. //
  20243. this.properties.isGizmo = true;
  20244. //
  20245. this.target = new THREE.Vector3();
  20246. this.lookAt( this.target );
  20247. }
  20248. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20249. THREE.HemisphereLightHelper.prototype.update = function () {
  20250. // update sphere sky and ground colors to light color * light intensity
  20251. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20252. this.color.copy( this.light.color );
  20253. this.color.multiplyScalar( intensity );
  20254. this.groundColor.copy( this.light.groundColor );
  20255. this.groundColor.multiplyScalar( intensity );
  20256. this.lightSphere.material.materials[ 0 ].color.copy( this.color );
  20257. this.lightSphere.material.materials[ 1 ].color.copy( this.groundColor );
  20258. this.lightArrow.setColor( this.color.getHex() );
  20259. this.lightArrowGround.setColor( this.groundColor.getHex() );
  20260. this.lookAt( this.target );
  20261. }
  20262. /**
  20263. * @author alteredq / http://alteredqualia.com/
  20264. *
  20265. * - shows point light color, intensity, position and distance
  20266. */
  20267. THREE.PointLightHelper = function ( light, sphereSize ) {
  20268. THREE.Object3D.call( this );
  20269. this.light = light;
  20270. // position
  20271. this.position = light.position;
  20272. // color
  20273. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20274. this.color = light.color.clone();
  20275. this.color.multiplyScalar( intensity );
  20276. var hexColor = this.color.getHex();
  20277. // light helper
  20278. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20279. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20280. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20281. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20282. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20283. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20284. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20285. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20286. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20287. var d = light.distance;
  20288. if ( d === 0.0 ) {
  20289. this.lightDistance.visible = false;
  20290. } else {
  20291. this.lightDistance.scale.set( d, d, d );
  20292. }
  20293. this.add( this.lightSphere );
  20294. this.add( this.lightRays );
  20295. this.add( this.lightDistance );
  20296. //
  20297. this.lightSphere.properties.isGizmo = true;
  20298. this.lightSphere.properties.gizmoSubject = light;
  20299. this.lightSphere.properties.gizmoRoot = this;
  20300. //
  20301. this.properties.isGizmo = true;
  20302. }
  20303. THREE.PointLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20304. THREE.PointLightHelper.prototype.update = function () {
  20305. // update sphere and rays colors to light color * light intensity
  20306. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20307. this.color.copy( this.light.color );
  20308. this.color.multiplyScalar( intensity );
  20309. this.lightSphere.material.color.copy( this.color );
  20310. this.lightRays.material.color.copy( this.color );
  20311. this.lightDistance.material.color.copy( this.color );
  20312. //
  20313. var d = this.light.distance;
  20314. if ( d === 0.0 ) {
  20315. this.lightDistance.visible = false;
  20316. } else {
  20317. this.lightDistance.visible = true;
  20318. this.lightDistance.scale.set( d, d, d );
  20319. }
  20320. }
  20321. /**
  20322. * @author alteredq / http://alteredqualia.com/
  20323. *
  20324. * - shows spot light color, intensity, position, orientation, light cone and target
  20325. */
  20326. THREE.SpotLightHelper = function ( light, sphereSize ) {
  20327. THREE.Object3D.call( this );
  20328. this.light = light;
  20329. // position
  20330. this.position = light.position;
  20331. // direction
  20332. this.direction = new THREE.Vector3();
  20333. this.direction.subVectors( light.target.position, light.position );
  20334. // color
  20335. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20336. this.color = light.color.clone();
  20337. this.color.multiplyScalar( intensity );
  20338. var hexColor = this.color.getHex();
  20339. // light helper
  20340. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20341. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20342. var coneGeometry = new THREE.CylinderGeometry( 0.0001, 1, 1, 8, 1, true );
  20343. var coneMatrix = new THREE.Matrix4();
  20344. coneMatrix.rotateX( -Math.PI/2 );
  20345. coneMatrix.translate( new THREE.Vector3( 0, -0.5, 0 ) );
  20346. coneGeometry.applyMatrix( coneMatrix );
  20347. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20348. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20349. var coneMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.3, transparent: true } );
  20350. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20351. this.lightCone = new THREE.Mesh( coneGeometry, coneMaterial );
  20352. var coneLength = light.distance ? light.distance : 10000;
  20353. var coneWidth = coneLength * Math.tan( light.angle * 0.5 ) * 2;
  20354. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  20355. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20356. this.gyroscope = new THREE.Gyroscope();
  20357. this.gyroscope.add( this.lightSphere );
  20358. this.gyroscope.add( this.lightRays );
  20359. this.add( this.gyroscope );
  20360. this.add( this.lightCone );
  20361. this.lookAt( light.target.position );
  20362. this.lightSphere.properties.isGizmo = true;
  20363. this.lightSphere.properties.gizmoSubject = light;
  20364. this.lightSphere.properties.gizmoRoot = this;
  20365. // light target helper
  20366. this.targetSphere = null;
  20367. if ( light.target.properties.targetInverse !== undefined ) {
  20368. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  20369. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  20370. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  20371. this.targetSphere.position = light.target.position;
  20372. this.targetSphere.properties.isGizmo = true;
  20373. this.targetSphere.properties.gizmoSubject = light.target;
  20374. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  20375. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20376. var lineGeometry = new THREE.Geometry();
  20377. lineGeometry.vertices.push( this.position.clone() );
  20378. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  20379. lineGeometry.computeLineDistances();
  20380. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  20381. this.targetLine.properties.isGizmo = true;
  20382. }
  20383. //
  20384. this.properties.isGizmo = true;
  20385. }
  20386. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20387. THREE.SpotLightHelper.prototype.update = function () {
  20388. // update arrow orientation
  20389. // pointing from light to target
  20390. this.direction.subVectors( this.light.target.position, this.light.position );
  20391. // update light cone orientation and size
  20392. this.lookAt( this.light.target.position );
  20393. var coneLength = this.light.distance ? this.light.distance : 10000;
  20394. var coneWidth = coneLength * Math.tan( this.light.angle * 0.5 ) * 2;
  20395. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  20396. // update arrow, spheres, rays and line colors to light color * light intensity
  20397. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20398. this.color.copy( this.light.color );
  20399. this.color.multiplyScalar( intensity );
  20400. this.lightSphere.material.color.copy( this.color );
  20401. this.lightRays.material.color.copy( this.color );
  20402. this.lightCone.material.color.copy( this.color );
  20403. // Only update targetSphere and targetLine if available
  20404. if ( this.targetSphere !== null ) {
  20405. this.targetSphere.material.color.copy( this.color );
  20406. this.targetLine.material.color.copy( this.color );
  20407. // update target line vertices
  20408. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  20409. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  20410. this.targetLine.geometry.computeLineDistances();
  20411. this.targetLine.geometry.verticesNeedUpdate = true;
  20412. }
  20413. };
  20414. /**
  20415. * @author alteredq / http://alteredqualia.com/
  20416. */
  20417. THREE.ImmediateRenderObject = function () {
  20418. THREE.Object3D.call( this );
  20419. this.render = function ( renderCallback ) { };
  20420. };
  20421. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20422. /**
  20423. * @author mikael emtinger / http://gomo.se/
  20424. * @author alteredq / http://alteredqualia.com/
  20425. */
  20426. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20427. THREE.Object3D.call( this );
  20428. this.lensFlares = [];
  20429. this.positionScreen = new THREE.Vector3();
  20430. this.customUpdateCallback = undefined;
  20431. if( texture !== undefined ) {
  20432. this.add( texture, size, distance, blending, color );
  20433. }
  20434. };
  20435. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20436. /*
  20437. * Add: adds another flare
  20438. */
  20439. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20440. if( size === undefined ) size = -1;
  20441. if( distance === undefined ) distance = 0;
  20442. if( opacity === undefined ) opacity = 1;
  20443. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20444. if( blending === undefined ) blending = THREE.NormalBlending;
  20445. distance = Math.min( distance, Math.max( 0, distance ) );
  20446. this.lensFlares.push( { texture: texture, // THREE.Texture
  20447. size: size, // size in pixels (-1 = use texture.width)
  20448. distance: distance, // distance (0-1) from light source (0=at light source)
  20449. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20450. scale: 1, // scale
  20451. rotation: 1, // rotation
  20452. opacity: opacity, // opacity
  20453. color: color, // color
  20454. blending: blending } ); // blending
  20455. };
  20456. /*
  20457. * Update lens flares update positions on all flares based on the screen position
  20458. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20459. */
  20460. THREE.LensFlare.prototype.updateLensFlares = function () {
  20461. var f, fl = this.lensFlares.length;
  20462. var flare;
  20463. var vecX = -this.positionScreen.x * 2;
  20464. var vecY = -this.positionScreen.y * 2;
  20465. for( f = 0; f < fl; f ++ ) {
  20466. flare = this.lensFlares[ f ];
  20467. flare.x = this.positionScreen.x + vecX * flare.distance;
  20468. flare.y = this.positionScreen.y + vecY * flare.distance;
  20469. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20470. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20471. }
  20472. };
  20473. /**
  20474. * @author alteredq / http://alteredqualia.com/
  20475. */
  20476. THREE.MorphBlendMesh = function( geometry, material ) {
  20477. THREE.Mesh.call( this, geometry, material );
  20478. this.animationsMap = {};
  20479. this.animationsList = [];
  20480. // prepare default animation
  20481. // (all frames played together in 1 second)
  20482. var numFrames = this.geometry.morphTargets.length;
  20483. var name = "__default";
  20484. var startFrame = 0;
  20485. var endFrame = numFrames - 1;
  20486. var fps = numFrames / 1;
  20487. this.createAnimation( name, startFrame, endFrame, fps );
  20488. this.setAnimationWeight( name, 1 );
  20489. };
  20490. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20491. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20492. var animation = {
  20493. startFrame: start,
  20494. endFrame: end,
  20495. length: end - start + 1,
  20496. fps: fps,
  20497. duration: ( end - start ) / fps,
  20498. lastFrame: 0,
  20499. currentFrame: 0,
  20500. active: false,
  20501. time: 0,
  20502. direction: 1,
  20503. weight: 1,
  20504. directionBackwards: false,
  20505. mirroredLoop: false
  20506. };
  20507. this.animationsMap[ name ] = animation;
  20508. this.animationsList.push( animation );
  20509. };
  20510. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20511. var pattern = /([a-z]+)(\d+)/;
  20512. var firstAnimation, frameRanges = {};
  20513. var geometry = this.geometry;
  20514. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20515. var morph = geometry.morphTargets[ i ];
  20516. var chunks = morph.name.match( pattern );
  20517. if ( chunks && chunks.length > 1 ) {
  20518. var name = chunks[ 1 ];
  20519. var num = chunks[ 2 ];
  20520. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20521. var range = frameRanges[ name ];
  20522. if ( i < range.start ) range.start = i;
  20523. if ( i > range.end ) range.end = i;
  20524. if ( ! firstAnimation ) firstAnimation = name;
  20525. }
  20526. }
  20527. for ( var name in frameRanges ) {
  20528. var range = frameRanges[ name ];
  20529. this.createAnimation( name, range.start, range.end, fps );
  20530. }
  20531. this.firstAnimation = firstAnimation;
  20532. };
  20533. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20534. var animation = this.animationsMap[ name ];
  20535. if ( animation ) {
  20536. animation.direction = 1;
  20537. animation.directionBackwards = false;
  20538. }
  20539. };
  20540. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20541. var animation = this.animationsMap[ name ];
  20542. if ( animation ) {
  20543. animation.direction = -1;
  20544. animation.directionBackwards = true;
  20545. }
  20546. };
  20547. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20548. var animation = this.animationsMap[ name ];
  20549. if ( animation ) {
  20550. animation.fps = fps;
  20551. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20552. }
  20553. };
  20554. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20555. var animation = this.animationsMap[ name ];
  20556. if ( animation ) {
  20557. animation.duration = duration;
  20558. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20559. }
  20560. };
  20561. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20562. var animation = this.animationsMap[ name ];
  20563. if ( animation ) {
  20564. animation.weight = weight;
  20565. }
  20566. };
  20567. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20568. var animation = this.animationsMap[ name ];
  20569. if ( animation ) {
  20570. animation.time = time;
  20571. }
  20572. };
  20573. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20574. var time = 0;
  20575. var animation = this.animationsMap[ name ];
  20576. if ( animation ) {
  20577. time = animation.time;
  20578. }
  20579. return time;
  20580. };
  20581. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20582. var duration = -1;
  20583. var animation = this.animationsMap[ name ];
  20584. if ( animation ) {
  20585. duration = animation.duration;
  20586. }
  20587. return duration;
  20588. };
  20589. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20590. var animation = this.animationsMap[ name ];
  20591. if ( animation ) {
  20592. animation.time = 0;
  20593. animation.active = true;
  20594. } else {
  20595. console.warn( "animation[" + name + "] undefined" );
  20596. }
  20597. };
  20598. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20599. var animation = this.animationsMap[ name ];
  20600. if ( animation ) {
  20601. animation.active = false;
  20602. }
  20603. };
  20604. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20605. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20606. var animation = this.animationsList[ i ];
  20607. if ( ! animation.active ) continue;
  20608. var frameTime = animation.duration / animation.length;
  20609. animation.time += animation.direction * delta;
  20610. if ( animation.mirroredLoop ) {
  20611. if ( animation.time > animation.duration || animation.time < 0 ) {
  20612. animation.direction *= -1;
  20613. if ( animation.time > animation.duration ) {
  20614. animation.time = animation.duration;
  20615. animation.directionBackwards = true;
  20616. }
  20617. if ( animation.time < 0 ) {
  20618. animation.time = 0;
  20619. animation.directionBackwards = false;
  20620. }
  20621. }
  20622. } else {
  20623. animation.time = animation.time % animation.duration;
  20624. if ( animation.time < 0 ) animation.time += animation.duration;
  20625. }
  20626. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20627. var weight = animation.weight;
  20628. if ( keyframe !== animation.currentFrame ) {
  20629. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20630. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20631. this.morphTargetInfluences[ keyframe ] = 0;
  20632. animation.lastFrame = animation.currentFrame;
  20633. animation.currentFrame = keyframe;
  20634. }
  20635. var mix = ( animation.time % frameTime ) / frameTime;
  20636. if ( animation.directionBackwards ) mix = 1 - mix;
  20637. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  20638. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  20639. }
  20640. };
  20641. /**
  20642. * @author mikael emtinger / http://gomo.se/
  20643. * @author alteredq / http://alteredqualia.com/
  20644. */
  20645. THREE.LensFlarePlugin = function () {
  20646. var _gl, _renderer, _precision, _lensFlare = {};
  20647. this.init = function ( renderer ) {
  20648. _gl = renderer.context;
  20649. _renderer = renderer;
  20650. _precision = renderer.getPrecision();
  20651. _lensFlare.vertices = new Float32Array( 8 + 8 );
  20652. _lensFlare.faces = new Uint16Array( 6 );
  20653. var i = 0;
  20654. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  20655. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  20656. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  20657. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  20658. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20659. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20660. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  20661. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  20662. i = 0;
  20663. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  20664. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  20665. // buffers
  20666. _lensFlare.vertexBuffer = _gl.createBuffer();
  20667. _lensFlare.elementBuffer = _gl.createBuffer();
  20668. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20669. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  20670. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20671. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  20672. // textures
  20673. _lensFlare.tempTexture = _gl.createTexture();
  20674. _lensFlare.occlusionTexture = _gl.createTexture();
  20675. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20676. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  20677. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20678. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20679. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20680. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20681. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20682. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  20683. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20684. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20685. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20686. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20687. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  20688. _lensFlare.hasVertexTexture = false;
  20689. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  20690. } else {
  20691. _lensFlare.hasVertexTexture = true;
  20692. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  20693. }
  20694. _lensFlare.attributes = {};
  20695. _lensFlare.uniforms = {};
  20696. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  20697. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  20698. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  20699. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  20700. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  20701. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  20702. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  20703. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  20704. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  20705. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  20706. };
  20707. /*
  20708. * Render lens flares
  20709. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  20710. * reads these back and calculates occlusion.
  20711. * Then _lensFlare.update_lensFlares() is called to re-position and
  20712. * update transparency of flares. Then they are rendered.
  20713. *
  20714. */
  20715. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20716. var flares = scene.__webglFlares,
  20717. nFlares = flares.length;
  20718. if ( ! nFlares ) return;
  20719. var tempPosition = new THREE.Vector3();
  20720. var invAspect = viewportHeight / viewportWidth,
  20721. halfViewportWidth = viewportWidth * 0.5,
  20722. halfViewportHeight = viewportHeight * 0.5;
  20723. var size = 16 / viewportHeight,
  20724. scale = new THREE.Vector2( size * invAspect, size );
  20725. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  20726. screenPositionPixels = new THREE.Vector2( 1, 1 );
  20727. var uniforms = _lensFlare.uniforms,
  20728. attributes = _lensFlare.attributes;
  20729. // set _lensFlare program and reset blending
  20730. _gl.useProgram( _lensFlare.program );
  20731. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  20732. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  20733. // loop through all lens flares to update their occlusion and positions
  20734. // setup gl and common used attribs/unforms
  20735. _gl.uniform1i( uniforms.occlusionMap, 0 );
  20736. _gl.uniform1i( uniforms.map, 1 );
  20737. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20738. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  20739. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  20740. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20741. _gl.disable( _gl.CULL_FACE );
  20742. _gl.depthMask( false );
  20743. var i, j, jl, flare, sprite;
  20744. for ( i = 0; i < nFlares; i ++ ) {
  20745. size = 16 / viewportHeight;
  20746. scale.set( size * invAspect, size );
  20747. // calc object screen position
  20748. flare = flares[ i ];
  20749. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  20750. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  20751. tempPosition.applyProjection( camera.projectionMatrix );
  20752. // setup arrays for gl programs
  20753. screenPosition.copy( tempPosition )
  20754. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  20755. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  20756. // screen cull
  20757. if ( _lensFlare.hasVertexTexture || (
  20758. screenPositionPixels.x > 0 &&
  20759. screenPositionPixels.x < viewportWidth &&
  20760. screenPositionPixels.y > 0 &&
  20761. screenPositionPixels.y < viewportHeight ) ) {
  20762. // save current RGB to temp texture
  20763. _gl.activeTexture( _gl.TEXTURE1 );
  20764. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20765. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20766. // render pink quad
  20767. _gl.uniform1i( uniforms.renderType, 0 );
  20768. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20769. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20770. _gl.disable( _gl.BLEND );
  20771. _gl.enable( _gl.DEPTH_TEST );
  20772. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20773. // copy result to occlusionMap
  20774. _gl.activeTexture( _gl.TEXTURE0 );
  20775. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20776. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20777. // restore graphics
  20778. _gl.uniform1i( uniforms.renderType, 1 );
  20779. _gl.disable( _gl.DEPTH_TEST );
  20780. _gl.activeTexture( _gl.TEXTURE1 );
  20781. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20782. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20783. // update object positions
  20784. flare.positionScreen.copy( screenPosition )
  20785. if ( flare.customUpdateCallback ) {
  20786. flare.customUpdateCallback( flare );
  20787. } else {
  20788. flare.updateLensFlares();
  20789. }
  20790. // render flares
  20791. _gl.uniform1i( uniforms.renderType, 2 );
  20792. _gl.enable( _gl.BLEND );
  20793. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  20794. sprite = flare.lensFlares[ j ];
  20795. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  20796. screenPosition.x = sprite.x;
  20797. screenPosition.y = sprite.y;
  20798. screenPosition.z = sprite.z;
  20799. size = sprite.size * sprite.scale / viewportHeight;
  20800. scale.x = size * invAspect;
  20801. scale.y = size;
  20802. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20803. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20804. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  20805. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  20806. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  20807. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  20808. _renderer.setTexture( sprite.texture, 1 );
  20809. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20810. }
  20811. }
  20812. }
  20813. }
  20814. // restore gl
  20815. _gl.enable( _gl.CULL_FACE );
  20816. _gl.enable( _gl.DEPTH_TEST );
  20817. _gl.depthMask( true );
  20818. };
  20819. function createProgram ( shader, precision ) {
  20820. var program = _gl.createProgram();
  20821. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  20822. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  20823. var prefix = "precision " + precision + " float;\n";
  20824. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  20825. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  20826. _gl.compileShader( fragmentShader );
  20827. _gl.compileShader( vertexShader );
  20828. _gl.attachShader( program, fragmentShader );
  20829. _gl.attachShader( program, vertexShader );
  20830. _gl.linkProgram( program );
  20831. return program;
  20832. };
  20833. };
  20834. /**
  20835. * @author alteredq / http://alteredqualia.com/
  20836. */
  20837. THREE.ShadowMapPlugin = function () {
  20838. var _gl,
  20839. _renderer,
  20840. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  20841. _frustum = new THREE.Frustum(),
  20842. _projScreenMatrix = new THREE.Matrix4(),
  20843. _min = new THREE.Vector3(),
  20844. _max = new THREE.Vector3();
  20845. this.init = function ( renderer ) {
  20846. _gl = renderer.context;
  20847. _renderer = renderer;
  20848. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  20849. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  20850. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  20851. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  20852. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  20853. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  20854. _depthMaterial._shadowPass = true;
  20855. _depthMaterialMorph._shadowPass = true;
  20856. _depthMaterialSkin._shadowPass = true;
  20857. _depthMaterialMorphSkin._shadowPass = true;
  20858. };
  20859. this.render = function ( scene, camera ) {
  20860. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  20861. this.update( scene, camera );
  20862. };
  20863. this.update = function ( scene, camera ) {
  20864. var i, il, j, jl, n,
  20865. shadowMap, shadowMatrix, shadowCamera,
  20866. program, buffer, material,
  20867. webglObject, object, light,
  20868. renderList,
  20869. lights = [],
  20870. k = 0,
  20871. fog = null;
  20872. // set GL state for depth map
  20873. _gl.clearColor( 1, 1, 1, 1 );
  20874. _gl.disable( _gl.BLEND );
  20875. _gl.enable( _gl.CULL_FACE );
  20876. _gl.frontFace( _gl.CCW );
  20877. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  20878. _gl.cullFace( _gl.FRONT );
  20879. } else {
  20880. _gl.cullFace( _gl.BACK );
  20881. }
  20882. _renderer.setDepthTest( true );
  20883. // preprocess lights
  20884. // - skip lights that are not casting shadows
  20885. // - create virtual lights for cascaded shadow maps
  20886. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  20887. light = scene.__lights[ i ];
  20888. if ( ! light.castShadow ) continue;
  20889. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  20890. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  20891. var virtualLight;
  20892. if ( ! light.shadowCascadeArray[ n ] ) {
  20893. virtualLight = createVirtualLight( light, n );
  20894. virtualLight.originalCamera = camera;
  20895. var gyro = new THREE.Gyroscope();
  20896. gyro.position = light.shadowCascadeOffset;
  20897. gyro.add( virtualLight );
  20898. gyro.add( virtualLight.target );
  20899. camera.add( gyro );
  20900. light.shadowCascadeArray[ n ] = virtualLight;
  20901. console.log( "Created virtualLight", virtualLight );
  20902. } else {
  20903. virtualLight = light.shadowCascadeArray[ n ];
  20904. }
  20905. updateVirtualLight( light, n );
  20906. lights[ k ] = virtualLight;
  20907. k ++;
  20908. }
  20909. } else {
  20910. lights[ k ] = light;
  20911. k ++;
  20912. }
  20913. }
  20914. // render depth map
  20915. for ( i = 0, il = lights.length; i < il; i ++ ) {
  20916. light = lights[ i ];
  20917. if ( ! light.shadowMap ) {
  20918. var shadowFilter = THREE.LinearFilter;
  20919. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  20920. shadowFilter = THREE.NearestFilter;
  20921. }
  20922. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  20923. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  20924. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  20925. light.shadowMatrix = new THREE.Matrix4();
  20926. }
  20927. if ( ! light.shadowCamera ) {
  20928. if ( light instanceof THREE.SpotLight ) {
  20929. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  20930. } else if ( light instanceof THREE.DirectionalLight ) {
  20931. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  20932. } else {
  20933. console.error( "Unsupported light type for shadow" );
  20934. continue;
  20935. }
  20936. scene.add( light.shadowCamera );
  20937. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  20938. }
  20939. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  20940. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  20941. light.shadowCamera.add( light.cameraHelper );
  20942. }
  20943. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  20944. updateShadowCamera( camera, light );
  20945. }
  20946. shadowMap = light.shadowMap;
  20947. shadowMatrix = light.shadowMatrix;
  20948. shadowCamera = light.shadowCamera;
  20949. shadowCamera.position.getPositionFromMatrix( light.matrixWorld );
  20950. shadowCamera.lookAt( light.target.matrixWorld.getPosition() );
  20951. shadowCamera.updateMatrixWorld();
  20952. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  20953. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  20954. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  20955. // compute shadow matrix
  20956. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  20957. 0.0, 0.5, 0.0, 0.5,
  20958. 0.0, 0.0, 0.5, 0.5,
  20959. 0.0, 0.0, 0.0, 1.0 );
  20960. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  20961. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  20962. // update camera matrices and frustum
  20963. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  20964. _frustum.setFromMatrix( _projScreenMatrix );
  20965. // render shadow map
  20966. _renderer.setRenderTarget( shadowMap );
  20967. _renderer.clear();
  20968. // set object matrices & frustum culling
  20969. renderList = scene.__webglObjects;
  20970. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20971. webglObject = renderList[ j ];
  20972. object = webglObject.object;
  20973. webglObject.render = false;
  20974. if ( object.visible && object.castShadow ) {
  20975. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  20976. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  20977. webglObject.render = true;
  20978. }
  20979. }
  20980. }
  20981. // render regular objects
  20982. var objectMaterial, useMorphing, useSkinning;
  20983. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20984. webglObject = renderList[ j ];
  20985. if ( webglObject.render ) {
  20986. object = webglObject.object;
  20987. buffer = webglObject.buffer;
  20988. // culling is overriden globally for all objects
  20989. // while rendering depth map
  20990. // need to deal with MeshFaceMaterial somehow
  20991. // in that case just use the first of material.materials for now
  20992. // (proper solution would require to break objects by materials
  20993. // similarly to regular rendering and then set corresponding
  20994. // depth materials per each chunk instead of just once per object)
  20995. objectMaterial = getObjectMaterial( object );
  20996. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  20997. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  20998. if ( object.customDepthMaterial ) {
  20999. material = object.customDepthMaterial;
  21000. } else if ( useSkinning ) {
  21001. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21002. } else if ( useMorphing ) {
  21003. material = _depthMaterialMorph;
  21004. } else {
  21005. material = _depthMaterial;
  21006. }
  21007. if ( buffer instanceof THREE.BufferGeometry ) {
  21008. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21009. } else {
  21010. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21011. }
  21012. }
  21013. }
  21014. // set matrices and render immediate objects
  21015. renderList = scene.__webglObjectsImmediate;
  21016. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21017. webglObject = renderList[ j ];
  21018. object = webglObject.object;
  21019. if ( object.visible && object.castShadow ) {
  21020. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21021. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21022. }
  21023. }
  21024. }
  21025. // restore GL state
  21026. var clearColor = _renderer.getClearColor(),
  21027. clearAlpha = _renderer.getClearAlpha();
  21028. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21029. _gl.enable( _gl.BLEND );
  21030. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21031. _gl.cullFace( _gl.BACK );
  21032. }
  21033. };
  21034. function createVirtualLight( light, cascade ) {
  21035. var virtualLight = new THREE.DirectionalLight();
  21036. virtualLight.isVirtual = true;
  21037. virtualLight.onlyShadow = true;
  21038. virtualLight.castShadow = true;
  21039. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21040. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21041. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21042. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21043. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21044. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21045. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21046. virtualLight.shadowDarkness = light.shadowDarkness;
  21047. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21048. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21049. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21050. virtualLight.pointsWorld = [];
  21051. virtualLight.pointsFrustum = [];
  21052. var pointsWorld = virtualLight.pointsWorld,
  21053. pointsFrustum = virtualLight.pointsFrustum;
  21054. for ( var i = 0; i < 8; i ++ ) {
  21055. pointsWorld[ i ] = new THREE.Vector3();
  21056. pointsFrustum[ i ] = new THREE.Vector3();
  21057. }
  21058. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21059. var farZ = light.shadowCascadeFarZ[ cascade ];
  21060. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21061. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21062. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21063. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21064. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21065. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21066. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21067. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21068. return virtualLight;
  21069. }
  21070. // Synchronize virtual light with the original light
  21071. function updateVirtualLight( light, cascade ) {
  21072. var virtualLight = light.shadowCascadeArray[ cascade ];
  21073. virtualLight.position.copy( light.position );
  21074. virtualLight.target.position.copy( light.target.position );
  21075. virtualLight.lookAt( virtualLight.target );
  21076. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21077. virtualLight.shadowDarkness = light.shadowDarkness;
  21078. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21079. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21080. var farZ = light.shadowCascadeFarZ[ cascade ];
  21081. var pointsFrustum = virtualLight.pointsFrustum;
  21082. pointsFrustum[ 0 ].z = nearZ;
  21083. pointsFrustum[ 1 ].z = nearZ;
  21084. pointsFrustum[ 2 ].z = nearZ;
  21085. pointsFrustum[ 3 ].z = nearZ;
  21086. pointsFrustum[ 4 ].z = farZ;
  21087. pointsFrustum[ 5 ].z = farZ;
  21088. pointsFrustum[ 6 ].z = farZ;
  21089. pointsFrustum[ 7 ].z = farZ;
  21090. }
  21091. // Fit shadow camera's ortho frustum to camera frustum
  21092. function updateShadowCamera( camera, light ) {
  21093. var shadowCamera = light.shadowCamera,
  21094. pointsFrustum = light.pointsFrustum,
  21095. pointsWorld = light.pointsWorld;
  21096. _min.set( Infinity, Infinity, Infinity );
  21097. _max.set( -Infinity, -Infinity, -Infinity );
  21098. for ( var i = 0; i < 8; i ++ ) {
  21099. var p = pointsWorld[ i ];
  21100. p.copy( pointsFrustum[ i ] );
  21101. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21102. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  21103. if ( p.x < _min.x ) _min.x = p.x;
  21104. if ( p.x > _max.x ) _max.x = p.x;
  21105. if ( p.y < _min.y ) _min.y = p.y;
  21106. if ( p.y > _max.y ) _max.y = p.y;
  21107. if ( p.z < _min.z ) _min.z = p.z;
  21108. if ( p.z > _max.z ) _max.z = p.z;
  21109. }
  21110. shadowCamera.left = _min.x;
  21111. shadowCamera.right = _max.x;
  21112. shadowCamera.top = _max.y;
  21113. shadowCamera.bottom = _min.y;
  21114. // can't really fit near/far
  21115. //shadowCamera.near = _min.z;
  21116. //shadowCamera.far = _max.z;
  21117. shadowCamera.updateProjectionMatrix();
  21118. }
  21119. // For the moment just ignore objects that have multiple materials with different animation methods
  21120. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  21121. function getObjectMaterial( object ) {
  21122. return object.material instanceof THREE.MeshFaceMaterial
  21123. ? object.material.materials[ 0 ]
  21124. : object.material;
  21125. };
  21126. };
  21127. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21128. /**
  21129. * @author mikael emtinger / http://gomo.se/
  21130. * @author alteredq / http://alteredqualia.com/
  21131. */
  21132. THREE.SpritePlugin = function () {
  21133. var _gl, _renderer, _precision, _sprite = {};
  21134. this.init = function ( renderer ) {
  21135. _gl = renderer.context;
  21136. _renderer = renderer;
  21137. _precision = renderer.getPrecision();
  21138. _sprite.vertices = new Float32Array( 8 + 8 );
  21139. _sprite.faces = new Uint16Array( 6 );
  21140. var i = 0;
  21141. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  21142. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  21143. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  21144. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  21145. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  21146. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  21147. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  21148. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  21149. i = 0;
  21150. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  21151. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  21152. _sprite.vertexBuffer = _gl.createBuffer();
  21153. _sprite.elementBuffer = _gl.createBuffer();
  21154. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21155. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  21156. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21157. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  21158. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ], _precision );
  21159. _sprite.attributes = {};
  21160. _sprite.uniforms = {};
  21161. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  21162. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  21163. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  21164. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  21165. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  21166. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  21167. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  21168. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  21169. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  21170. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  21171. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  21172. _sprite.uniforms.sizeAttenuation = _gl.getUniformLocation( _sprite.program, "sizeAttenuation" );
  21173. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  21174. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  21175. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  21176. _sprite.uniforms.fogType = _gl.getUniformLocation( _sprite.program, "fogType" );
  21177. _sprite.uniforms.fogDensity = _gl.getUniformLocation( _sprite.program, "fogDensity" );
  21178. _sprite.uniforms.fogNear = _gl.getUniformLocation( _sprite.program, "fogNear" );
  21179. _sprite.uniforms.fogFar = _gl.getUniformLocation( _sprite.program, "fogFar" );
  21180. _sprite.uniforms.fogColor = _gl.getUniformLocation( _sprite.program, "fogColor" );
  21181. _sprite.uniforms.alphaTest = _gl.getUniformLocation( _sprite.program, "alphaTest" );
  21182. };
  21183. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21184. var sprites = scene.__webglSprites,
  21185. nSprites = sprites.length;
  21186. if ( ! nSprites ) return;
  21187. var attributes = _sprite.attributes,
  21188. uniforms = _sprite.uniforms;
  21189. var invAspect = viewportHeight / viewportWidth;
  21190. var halfViewportWidth = viewportWidth * 0.5,
  21191. halfViewportHeight = viewportHeight * 0.5;
  21192. // setup gl
  21193. _gl.useProgram( _sprite.program );
  21194. _gl.enableVertexAttribArray( attributes.position );
  21195. _gl.enableVertexAttribArray( attributes.uv );
  21196. _gl.disable( _gl.CULL_FACE );
  21197. _gl.enable( _gl.BLEND );
  21198. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21199. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21200. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21201. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21202. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  21203. _gl.activeTexture( _gl.TEXTURE0 );
  21204. _gl.uniform1i( uniforms.map, 0 );
  21205. var oldFogType = 0;
  21206. var sceneFogType = 0;
  21207. var fog = scene.fog;
  21208. if ( fog ) {
  21209. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  21210. if ( fog instanceof THREE.Fog ) {
  21211. _gl.uniform1f( uniforms.fogNear, fog.near );
  21212. _gl.uniform1f( uniforms.fogFar, fog.far );
  21213. _gl.uniform1i( uniforms.fogType, 1 );
  21214. oldFogType = 1;
  21215. sceneFogType = 1;
  21216. } else if ( fog instanceof THREE.FogExp2 ) {
  21217. _gl.uniform1f( uniforms.fogDensity, fog.density );
  21218. _gl.uniform1i( uniforms.fogType, 2 );
  21219. oldFogType = 2;
  21220. sceneFogType = 2;
  21221. }
  21222. } else {
  21223. _gl.uniform1i( uniforms.fogType, 0 );
  21224. oldFogType = 0;
  21225. sceneFogType = 0;
  21226. }
  21227. // update positions and sort
  21228. var i, sprite, material, screenPosition, size, fogType, scale = [];
  21229. for( i = 0; i < nSprites; i ++ ) {
  21230. sprite = sprites[ i ];
  21231. material = sprite.material;
  21232. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21233. if ( ! material.useScreenCoordinates ) {
  21234. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  21235. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  21236. } else {
  21237. sprite.z = - sprite.position.z;
  21238. }
  21239. }
  21240. sprites.sort( painterSortStable );
  21241. // render all sprites
  21242. for( i = 0; i < nSprites; i ++ ) {
  21243. sprite = sprites[ i ];
  21244. material = sprite.material;
  21245. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21246. if ( material.map && material.map.image && material.map.image.width ) {
  21247. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  21248. if ( material.useScreenCoordinates === true ) {
  21249. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  21250. _gl.uniform3f(
  21251. uniforms.screenPosition,
  21252. ( ( sprite.position.x * _renderer.devicePixelRatio ) - halfViewportWidth ) / halfViewportWidth,
  21253. ( halfViewportHeight - ( sprite.position.y * _renderer.devicePixelRatio ) ) / halfViewportHeight,
  21254. Math.max( 0, Math.min( 1, sprite.position.z ) )
  21255. );
  21256. scale[ 0 ] = _renderer.devicePixelRatio;
  21257. scale[ 1 ] = _renderer.devicePixelRatio;
  21258. } else {
  21259. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  21260. _gl.uniform1i( uniforms.sizeAttenuation, material.sizeAttenuation ? 1 : 0 );
  21261. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  21262. scale[ 0 ] = 1;
  21263. scale[ 1 ] = 1;
  21264. }
  21265. if ( scene.fog && material.fog ) {
  21266. fogType = sceneFogType;
  21267. } else {
  21268. fogType = 0;
  21269. }
  21270. if ( oldFogType !== fogType ) {
  21271. _gl.uniform1i( uniforms.fogType, fogType );
  21272. oldFogType = fogType;
  21273. }
  21274. size = 1 / ( material.scaleByViewport ? viewportHeight : 1 );
  21275. scale[ 0 ] *= size * invAspect * sprite.scale.x
  21276. scale[ 1 ] *= size * sprite.scale.y;
  21277. _gl.uniform2f( uniforms.uvScale, material.uvScale.x, material.uvScale.y );
  21278. _gl.uniform2f( uniforms.uvOffset, material.uvOffset.x, material.uvOffset.y );
  21279. _gl.uniform2f( uniforms.alignment, material.alignment.x, material.alignment.y );
  21280. _gl.uniform1f( uniforms.opacity, material.opacity );
  21281. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  21282. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21283. _gl.uniform2fv( uniforms.scale, scale );
  21284. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  21285. _renderer.setDepthTest( material.depthTest );
  21286. _renderer.setDepthWrite( material.depthWrite );
  21287. _renderer.setTexture( material.map, 0 );
  21288. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21289. }
  21290. }
  21291. // restore gl
  21292. _gl.enable( _gl.CULL_FACE );
  21293. };
  21294. function createProgram ( shader, precision ) {
  21295. var program = _gl.createProgram();
  21296. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21297. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21298. var prefix = "precision " + precision + " float;\n";
  21299. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21300. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21301. _gl.compileShader( fragmentShader );
  21302. _gl.compileShader( vertexShader );
  21303. _gl.attachShader( program, fragmentShader );
  21304. _gl.attachShader( program, vertexShader );
  21305. _gl.linkProgram( program );
  21306. return program;
  21307. };
  21308. function painterSortStable ( a, b ) {
  21309. if ( a.z !== b.z ) {
  21310. return b.z - a.z;
  21311. } else {
  21312. return b.id - a.id;
  21313. }
  21314. };
  21315. };
  21316. /**
  21317. * @author alteredq / http://alteredqualia.com/
  21318. */
  21319. THREE.DepthPassPlugin = function () {
  21320. this.enabled = false;
  21321. this.renderTarget = null;
  21322. var _gl,
  21323. _renderer,
  21324. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21325. _frustum = new THREE.Frustum(),
  21326. _projScreenMatrix = new THREE.Matrix4();
  21327. this.init = function ( renderer ) {
  21328. _gl = renderer.context;
  21329. _renderer = renderer;
  21330. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21331. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21332. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21333. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21334. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21335. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21336. _depthMaterial._shadowPass = true;
  21337. _depthMaterialMorph._shadowPass = true;
  21338. _depthMaterialSkin._shadowPass = true;
  21339. _depthMaterialMorphSkin._shadowPass = true;
  21340. };
  21341. this.render = function ( scene, camera ) {
  21342. if ( ! this.enabled ) return;
  21343. this.update( scene, camera );
  21344. };
  21345. this.update = function ( scene, camera ) {
  21346. var i, il, j, jl, n,
  21347. program, buffer, material,
  21348. webglObject, object, light,
  21349. renderList,
  21350. fog = null;
  21351. // set GL state for depth map
  21352. _gl.clearColor( 1, 1, 1, 1 );
  21353. _gl.disable( _gl.BLEND );
  21354. _renderer.setDepthTest( true );
  21355. // update scene
  21356. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21357. // update camera matrices and frustum
  21358. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21359. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  21360. _frustum.setFromMatrix( _projScreenMatrix );
  21361. // render depth map
  21362. _renderer.setRenderTarget( this.renderTarget );
  21363. _renderer.clear();
  21364. // set object matrices & frustum culling
  21365. renderList = scene.__webglObjects;
  21366. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21367. webglObject = renderList[ j ];
  21368. object = webglObject.object;
  21369. webglObject.render = false;
  21370. if ( object.visible ) {
  21371. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21372. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21373. webglObject.render = true;
  21374. }
  21375. }
  21376. }
  21377. // render regular objects
  21378. var objectMaterial, useMorphing, useSkinning;
  21379. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21380. webglObject = renderList[ j ];
  21381. if ( webglObject.render ) {
  21382. object = webglObject.object;
  21383. buffer = webglObject.buffer;
  21384. // todo: create proper depth material for particles
  21385. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  21386. objectMaterial = getObjectMaterial( object );
  21387. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  21388. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21389. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21390. if ( object.customDepthMaterial ) {
  21391. material = object.customDepthMaterial;
  21392. } else if ( useSkinning ) {
  21393. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21394. } else if ( useMorphing ) {
  21395. material = _depthMaterialMorph;
  21396. } else {
  21397. material = _depthMaterial;
  21398. }
  21399. if ( buffer instanceof THREE.BufferGeometry ) {
  21400. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21401. } else {
  21402. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21403. }
  21404. }
  21405. }
  21406. // set matrices and render immediate objects
  21407. renderList = scene.__webglObjectsImmediate;
  21408. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21409. webglObject = renderList[ j ];
  21410. object = webglObject.object;
  21411. if ( object.visible ) {
  21412. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21413. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21414. }
  21415. }
  21416. // restore GL state
  21417. var clearColor = _renderer.getClearColor(),
  21418. clearAlpha = _renderer.getClearAlpha();
  21419. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21420. _gl.enable( _gl.BLEND );
  21421. };
  21422. // For the moment just ignore objects that have multiple materials with different animation methods
  21423. // Only the first material will be taken into account for deciding which depth material to use
  21424. function getObjectMaterial( object ) {
  21425. return object.material instanceof THREE.MeshFaceMaterial
  21426. ? object.material.materials[ 0 ]
  21427. : object.material;
  21428. };
  21429. };
  21430. /**
  21431. * @author mikael emtinger / http://gomo.se/
  21432. *
  21433. */
  21434. THREE.ShaderFlares = {
  21435. 'lensFlareVertexTexture': {
  21436. vertexShader: [
  21437. "uniform lowp int renderType;",
  21438. "uniform vec3 screenPosition;",
  21439. "uniform vec2 scale;",
  21440. "uniform float rotation;",
  21441. "uniform sampler2D occlusionMap;",
  21442. "attribute vec2 position;",
  21443. "attribute vec2 uv;",
  21444. "varying vec2 vUV;",
  21445. "varying float vVisibility;",
  21446. "void main() {",
  21447. "vUV = uv;",
  21448. "vec2 pos = position;",
  21449. "if( renderType == 2 ) {",
  21450. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  21451. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  21452. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  21453. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  21454. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  21455. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  21456. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  21457. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  21458. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21459. "vVisibility = ( visibility.r / 9.0 ) *",
  21460. "( 1.0 - visibility.g / 9.0 ) *",
  21461. "( visibility.b / 9.0 ) *",
  21462. "( 1.0 - visibility.a / 9.0 );",
  21463. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21464. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21465. "}",
  21466. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21467. "}"
  21468. ].join( "\n" ),
  21469. fragmentShader: [
  21470. "uniform lowp int renderType;",
  21471. "uniform sampler2D map;",
  21472. "uniform float opacity;",
  21473. "uniform vec3 color;",
  21474. "varying vec2 vUV;",
  21475. "varying float vVisibility;",
  21476. "void main() {",
  21477. // pink square
  21478. "if( renderType == 0 ) {",
  21479. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21480. // restore
  21481. "} else if( renderType == 1 ) {",
  21482. "gl_FragColor = texture2D( map, vUV );",
  21483. // flare
  21484. "} else {",
  21485. "vec4 texture = texture2D( map, vUV );",
  21486. "texture.a *= opacity * vVisibility;",
  21487. "gl_FragColor = texture;",
  21488. "gl_FragColor.rgb *= color;",
  21489. "}",
  21490. "}"
  21491. ].join( "\n" )
  21492. },
  21493. 'lensFlare': {
  21494. vertexShader: [
  21495. "uniform lowp int renderType;",
  21496. "uniform vec3 screenPosition;",
  21497. "uniform vec2 scale;",
  21498. "uniform float rotation;",
  21499. "attribute vec2 position;",
  21500. "attribute vec2 uv;",
  21501. "varying vec2 vUV;",
  21502. "void main() {",
  21503. "vUV = uv;",
  21504. "vec2 pos = position;",
  21505. "if( renderType == 2 ) {",
  21506. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21507. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21508. "}",
  21509. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21510. "}"
  21511. ].join( "\n" ),
  21512. fragmentShader: [
  21513. "precision mediump float;",
  21514. "uniform lowp int renderType;",
  21515. "uniform sampler2D map;",
  21516. "uniform sampler2D occlusionMap;",
  21517. "uniform float opacity;",
  21518. "uniform vec3 color;",
  21519. "varying vec2 vUV;",
  21520. "void main() {",
  21521. // pink square
  21522. "if( renderType == 0 ) {",
  21523. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  21524. // restore
  21525. "} else if( renderType == 1 ) {",
  21526. "gl_FragColor = texture2D( map, vUV );",
  21527. // flare
  21528. "} else {",
  21529. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  21530. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  21531. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  21532. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  21533. "visibility = ( 1.0 - visibility / 4.0 );",
  21534. "vec4 texture = texture2D( map, vUV );",
  21535. "texture.a *= opacity * visibility;",
  21536. "gl_FragColor = texture;",
  21537. "gl_FragColor.rgb *= color;",
  21538. "}",
  21539. "}"
  21540. ].join( "\n" )
  21541. }
  21542. };
  21543. /**
  21544. * @author mikael emtinger / http://gomo.se/
  21545. * @author alteredq / http://alteredqualia.com/
  21546. *
  21547. */
  21548. THREE.ShaderSprite = {
  21549. 'sprite': {
  21550. vertexShader: [
  21551. "uniform int useScreenCoordinates;",
  21552. "uniform int sizeAttenuation;",
  21553. "uniform vec3 screenPosition;",
  21554. "uniform mat4 modelViewMatrix;",
  21555. "uniform mat4 projectionMatrix;",
  21556. "uniform float rotation;",
  21557. "uniform vec2 scale;",
  21558. "uniform vec2 alignment;",
  21559. "uniform vec2 uvOffset;",
  21560. "uniform vec2 uvScale;",
  21561. "attribute vec2 position;",
  21562. "attribute vec2 uv;",
  21563. "varying vec2 vUV;",
  21564. "void main() {",
  21565. "vUV = uvOffset + uv * uvScale;",
  21566. "vec2 alignedPosition = position + alignment;",
  21567. "vec2 rotatedPosition;",
  21568. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  21569. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  21570. "vec4 finalPosition;",
  21571. "if( useScreenCoordinates != 0 ) {",
  21572. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  21573. "} else {",
  21574. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  21575. "finalPosition.xy += rotatedPosition * ( sizeAttenuation == 1 ? 1.0 : finalPosition.z );",
  21576. "}",
  21577. "gl_Position = finalPosition;",
  21578. "}"
  21579. ].join( "\n" ),
  21580. fragmentShader: [
  21581. "uniform vec3 color;",
  21582. "uniform sampler2D map;",
  21583. "uniform float opacity;",
  21584. "uniform int fogType;",
  21585. "uniform vec3 fogColor;",
  21586. "uniform float fogDensity;",
  21587. "uniform float fogNear;",
  21588. "uniform float fogFar;",
  21589. "uniform float alphaTest;",
  21590. "varying vec2 vUV;",
  21591. "void main() {",
  21592. "vec4 texture = texture2D( map, vUV );",
  21593. "if ( texture.a < alphaTest ) discard;",
  21594. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  21595. "if ( fogType > 0 ) {",
  21596. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  21597. "float fogFactor = 0.0;",
  21598. "if ( fogType == 1 ) {",
  21599. "fogFactor = smoothstep( fogNear, fogFar, depth );",
  21600. "} else {",
  21601. "const float LOG2 = 1.442695;",
  21602. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  21603. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  21604. "}",
  21605. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  21606. "}",
  21607. "}"
  21608. ].join( "\n" )
  21609. }
  21610. };