three.js 793 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. */
  5. var THREE = THREE || { REVISION: '55dev' };
  6. self.console = self.console || {
  7. info: function () {},
  8. log: function () {},
  9. debug: function () {},
  10. warn: function () {},
  11. error: function () {}
  12. };
  13. self.Int32Array = self.Int32Array || Array;
  14. self.Float32Array = self.Float32Array || Array;
  15. // Shims for "startsWith", "endsWith", and "trim" for browsers where this is not yet implemented
  16. // not sure we should have this, or at least not have it here
  17. // http://stackoverflow.com/questions/646628/javascript-startswith
  18. // http://stackoverflow.com/questions/498970/how-do-i-trim-a-string-in-javascript
  19. // http://wiki.ecmascript.org/doku.php?id=harmony%3astring_extras
  20. String.prototype.startsWith = String.prototype.startsWith || function ( str ) {
  21. return this.slice( 0, str.length ) === str;
  22. };
  23. String.prototype.endsWith = String.prototype.endsWith || function ( str ) {
  24. var t = String( str );
  25. var index = this.lastIndexOf( t );
  26. return ( -1 < index && index ) === (this.length - t.length);
  27. };
  28. String.prototype.trim = String.prototype.trim || function () {
  29. return this.replace( /^\s+|\s+$/g, '' );
  30. };
  31. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  32. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  33. // requestAnimationFrame polyfill by Erik Möller
  34. // fixes from Paul Irish and Tino Zijdel
  35. ( function () {
  36. var lastTime = 0;
  37. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  38. for ( var x = 0; x < vendors.length && !window.requestAnimationFrame; ++ x ) {
  39. window.requestAnimationFrame = window[ vendors[ x ] + 'RequestAnimationFrame' ];
  40. window.cancelAnimationFrame = window[ vendors[ x ] + 'CancelAnimationFrame' ] || window[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  41. }
  42. if ( window.requestAnimationFrame === undefined ) {
  43. window.requestAnimationFrame = function ( callback, element ) {
  44. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  45. var id = window.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  46. lastTime = currTime + timeToCall;
  47. return id;
  48. };
  49. }
  50. window.cancelAnimationFrame = window.cancelAnimationFrame || function ( id ) { window.clearTimeout( id ) };
  51. }() );
  52. // GL STATE CONSTANTS
  53. THREE.CullFaceNone = 0;
  54. THREE.CullFaceBack = 1;
  55. THREE.CullFaceFront = 2;
  56. THREE.CullFaceFrontBack = 3;
  57. THREE.FrontFaceDirectionCW = 0;
  58. THREE.FrontFaceDirectionCCW = 1;
  59. // SHADOWING TYPES
  60. THREE.BasicShadowMap = 0;
  61. THREE.PCFShadowMap = 1;
  62. THREE.PCFSoftShadowMap = 2;
  63. // MATERIAL CONSTANTS
  64. // side
  65. THREE.FrontSide = 0;
  66. THREE.BackSide = 1;
  67. THREE.DoubleSide = 2;
  68. // shading
  69. THREE.NoShading = 0;
  70. THREE.FlatShading = 1;
  71. THREE.SmoothShading = 2;
  72. // colors
  73. THREE.NoColors = 0;
  74. THREE.FaceColors = 1;
  75. THREE.VertexColors = 2;
  76. // blending modes
  77. THREE.NoBlending = 0;
  78. THREE.NormalBlending = 1;
  79. THREE.AdditiveBlending = 2;
  80. THREE.SubtractiveBlending = 3;
  81. THREE.MultiplyBlending = 4;
  82. THREE.CustomBlending = 5;
  83. // custom blending equations
  84. // (numbers start from 100 not to clash with other
  85. // mappings to OpenGL constants defined in Texture.js)
  86. THREE.AddEquation = 100;
  87. THREE.SubtractEquation = 101;
  88. THREE.ReverseSubtractEquation = 102;
  89. // custom blending destination factors
  90. THREE.ZeroFactor = 200;
  91. THREE.OneFactor = 201;
  92. THREE.SrcColorFactor = 202;
  93. THREE.OneMinusSrcColorFactor = 203;
  94. THREE.SrcAlphaFactor = 204;
  95. THREE.OneMinusSrcAlphaFactor = 205;
  96. THREE.DstAlphaFactor = 206;
  97. THREE.OneMinusDstAlphaFactor = 207;
  98. // custom blending source factors
  99. //THREE.ZeroFactor = 200;
  100. //THREE.OneFactor = 201;
  101. //THREE.SrcAlphaFactor = 204;
  102. //THREE.OneMinusSrcAlphaFactor = 205;
  103. //THREE.DstAlphaFactor = 206;
  104. //THREE.OneMinusDstAlphaFactor = 207;
  105. THREE.DstColorFactor = 208;
  106. THREE.OneMinusDstColorFactor = 209;
  107. THREE.SrcAlphaSaturateFactor = 210;
  108. // TEXTURE CONSTANTS
  109. THREE.MultiplyOperation = 0;
  110. THREE.MixOperation = 1;
  111. THREE.AddOperation = 2;
  112. // Mapping modes
  113. THREE.UVMapping = function () {};
  114. THREE.CubeReflectionMapping = function () {};
  115. THREE.CubeRefractionMapping = function () {};
  116. THREE.SphericalReflectionMapping = function () {};
  117. THREE.SphericalRefractionMapping = function () {};
  118. // Wrapping modes
  119. THREE.RepeatWrapping = 1000;
  120. THREE.ClampToEdgeWrapping = 1001;
  121. THREE.MirroredRepeatWrapping = 1002;
  122. // Filters
  123. THREE.NearestFilter = 1003;
  124. THREE.NearestMipMapNearestFilter = 1004;
  125. THREE.NearestMipMapLinearFilter = 1005;
  126. THREE.LinearFilter = 1006;
  127. THREE.LinearMipMapNearestFilter = 1007;
  128. THREE.LinearMipMapLinearFilter = 1008;
  129. // Data types
  130. THREE.UnsignedByteType = 1009;
  131. THREE.ByteType = 1010;
  132. THREE.ShortType = 1011;
  133. THREE.UnsignedShortType = 1012;
  134. THREE.IntType = 1013;
  135. THREE.UnsignedIntType = 1014;
  136. THREE.FloatType = 1015;
  137. // Pixel types
  138. //THREE.UnsignedByteType = 1009;
  139. THREE.UnsignedShort4444Type = 1016;
  140. THREE.UnsignedShort5551Type = 1017;
  141. THREE.UnsignedShort565Type = 1018;
  142. // Pixel formats
  143. THREE.AlphaFormat = 1019;
  144. THREE.RGBFormat = 1020;
  145. THREE.RGBAFormat = 1021;
  146. THREE.LuminanceFormat = 1022;
  147. THREE.LuminanceAlphaFormat = 1023;
  148. // Compressed texture formats
  149. THREE.RGB_S3TC_DXT1_Format = 2001;
  150. THREE.RGBA_S3TC_DXT1_Format = 2002;
  151. THREE.RGBA_S3TC_DXT3_Format = 2003;
  152. THREE.RGBA_S3TC_DXT5_Format = 2004;
  153. /*
  154. // Potential future PVRTC compressed texture formats
  155. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  156. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  157. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  158. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  159. */
  160. /**
  161. * @author mrdoob / http://mrdoob.com/
  162. */
  163. THREE.Color = function ( value ) {
  164. if ( value !== undefined ) this.set( value );
  165. return this;
  166. };
  167. THREE.Color.prototype = {
  168. constructor: THREE.Color,
  169. r: 1, g: 1, b: 1,
  170. set: function ( value ) {
  171. switch ( typeof value ) {
  172. case "number":
  173. this.setHex( value );
  174. break;
  175. case "string":
  176. this.setStyle( value );
  177. break;
  178. }
  179. },
  180. setHex: function ( hex ) {
  181. hex = Math.floor( hex );
  182. this.r = ( hex >> 16 & 255 ) / 255;
  183. this.g = ( hex >> 8 & 255 ) / 255;
  184. this.b = ( hex & 255 ) / 255;
  185. return this;
  186. },
  187. setRGB: function ( r, g, b ) {
  188. this.r = r;
  189. this.g = g;
  190. this.b = b;
  191. return this;
  192. },
  193. setHSV: function ( h, s, v ) {
  194. // based on MochiKit implementation by Bob Ippolito
  195. // h,s,v ranges are < 0.0 - 1.0 >
  196. var i, f, p, q, t;
  197. if ( v === 0 ) {
  198. this.r = this.g = this.b = 0;
  199. } else {
  200. i = Math.floor( h * 6 );
  201. f = ( h * 6 ) - i;
  202. p = v * ( 1 - s );
  203. q = v * ( 1 - ( s * f ) );
  204. t = v * ( 1 - ( s * ( 1 - f ) ) );
  205. if ( i === 0 ) {
  206. this.r = v;
  207. this.g = t;
  208. this.b = p;
  209. } else if ( i === 1 ) {
  210. this.r = q;
  211. this.g = v;
  212. this.b = p;
  213. } else if ( i === 2 ) {
  214. this.r = p;
  215. this.g = v;
  216. this.b = t;
  217. } else if ( i === 3 ) {
  218. this.r = p;
  219. this.g = q;
  220. this.b = v;
  221. } else if ( i === 4 ) {
  222. this.r = t;
  223. this.g = p;
  224. this.b = v;
  225. } else if ( i === 5 ) {
  226. this.r = v;
  227. this.g = p;
  228. this.b = q;
  229. }
  230. }
  231. return this;
  232. },
  233. setStyle: function ( style ) {
  234. // rgb(255,0,0)
  235. if ( /^rgb\((\d+),(\d+),(\d+)\)$/i.test( style ) ) {
  236. var color = /^rgb\((\d+),(\d+),(\d+)\)$/i.exec( style );
  237. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  238. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  239. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  240. return this;
  241. }
  242. // rgb(100%,0%,0%)
  243. if ( /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.test( style ) ) {
  244. var color = /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.exec( style );
  245. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  246. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  247. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  248. return this;
  249. }
  250. // #ff0000
  251. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  252. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  253. this.setHex( parseInt( color[ 1 ], 16 ) );
  254. return this;
  255. }
  256. // #f00
  257. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  258. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  259. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  260. return this;
  261. }
  262. // red
  263. if ( /^(\w+)$/i.test( style ) ) {
  264. this.setHex( THREE.ColorKeywords[ style ] );
  265. return this;
  266. }
  267. },
  268. copy: function ( color ) {
  269. this.r = color.r;
  270. this.g = color.g;
  271. this.b = color.b;
  272. return this;
  273. },
  274. copyGammaToLinear: function ( color ) {
  275. this.r = color.r * color.r;
  276. this.g = color.g * color.g;
  277. this.b = color.b * color.b;
  278. return this;
  279. },
  280. copyLinearToGamma: function ( color ) {
  281. this.r = Math.sqrt( color.r );
  282. this.g = Math.sqrt( color.g );
  283. this.b = Math.sqrt( color.b );
  284. return this;
  285. },
  286. convertGammaToLinear: function () {
  287. var r = this.r, g = this.g, b = this.b;
  288. this.r = r * r;
  289. this.g = g * g;
  290. this.b = b * b;
  291. return this;
  292. },
  293. convertLinearToGamma: function () {
  294. this.r = Math.sqrt( this.r );
  295. this.g = Math.sqrt( this.g );
  296. this.b = Math.sqrt( this.b );
  297. return this;
  298. },
  299. getHex: function () {
  300. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  301. },
  302. getHexString: function () {
  303. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  304. },
  305. getStyle: function () {
  306. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  307. },
  308. getHSV: function ( hsv ) {
  309. // based on MochiKit implementation by Bob Ippolito
  310. // h,s,v ranges are < 0.0 - 1.0 >
  311. var r = this.r;
  312. var g = this.g;
  313. var b = this.b;
  314. var max = Math.max( Math.max( r, g ), b );
  315. var min = Math.min( Math.min( r, g ), b );
  316. var hue;
  317. var saturation;
  318. var value = max;
  319. if ( min === max ) {
  320. hue = 0;
  321. saturation = 0;
  322. } else {
  323. var delta = ( max - min );
  324. saturation = delta / max;
  325. if ( r === max ) {
  326. hue = ( g - b ) / delta;
  327. } else if ( g === max ) {
  328. hue = 2 + ( ( b - r ) / delta );
  329. } else {
  330. hue = 4 + ( ( r - g ) / delta );
  331. }
  332. hue /= 6;
  333. if ( hue < 0 ) {
  334. hue += 1;
  335. }
  336. if ( hue > 1 ) {
  337. hue -= 1;
  338. }
  339. }
  340. if ( hsv === undefined ) {
  341. hsv = { h: 0, s: 0, v: 0 };
  342. }
  343. hsv.h = hue;
  344. hsv.s = saturation;
  345. hsv.v = value;
  346. return hsv;
  347. },
  348. add: function ( color ) {
  349. this.r += color.r;
  350. this.g += color.g;
  351. this.b += color.b;
  352. return this;
  353. },
  354. addColors: function ( color1, color2 ) {
  355. this.r = color1.r + color2.r;
  356. this.g = color1.g + color2.g;
  357. this.b = color1.b + color2.b;
  358. return this;
  359. },
  360. addScalar: function ( s ) {
  361. this.r += s;
  362. this.g += s;
  363. this.b += s;
  364. return this;
  365. },
  366. multiply: function ( color ) {
  367. this.r *= color.r;
  368. this.g *= color.g;
  369. this.b *= color.b;
  370. return this;
  371. },
  372. multiplyScalar: function ( s ) {
  373. this.r *= s;
  374. this.g *= s;
  375. this.b *= s;
  376. return this;
  377. },
  378. lerp: function ( color, alpha ) {
  379. this.r += ( color.r - this.r ) * alpha;
  380. this.g += ( color.g - this.g ) * alpha;
  381. this.b += ( color.b - this.b ) * alpha;
  382. return this;
  383. },
  384. clone: function () {
  385. return new THREE.Color().setRGB( this.r, this.g, this.b );
  386. }
  387. };
  388. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF,
  389. "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2,
  390. "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50,
  391. "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B,
  392. "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B,
  393. "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F,
  394. "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3,
  395. "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222,
  396. "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700,
  397. "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4,
  398. "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00,
  399. "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3,
  400. "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA,
  401. "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32,
  402. "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3,
  403. "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC,
  404. "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD,
  405. "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6,
  406. "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9,
  407. "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F,
  408. "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE,
  409. "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA,
  410. "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0,
  411. "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  412. /**
  413. * @author mrdoob / http://mrdoob.com/
  414. * @author philogb / http://blog.thejit.org/
  415. * @author egraether / http://egraether.com/
  416. * @author zz85 / http://www.lab4games.net/zz85/blog
  417. */
  418. THREE.Vector2 = function ( x, y ) {
  419. this.x = x || 0;
  420. this.y = y || 0;
  421. };
  422. THREE.Vector2.prototype = {
  423. constructor: THREE.Vector2,
  424. set: function ( x, y ) {
  425. this.x = x;
  426. this.y = y;
  427. return this;
  428. },
  429. setX: function ( x ) {
  430. this.x = x;
  431. return this;
  432. },
  433. setY: function ( y ) {
  434. this.y = y;
  435. return this;
  436. },
  437. setComponent: function ( index, value ) {
  438. switch ( index ) {
  439. case 0: this.x = value; break;
  440. case 1: this.y = value; break;
  441. default: throw new Error( "index is out of range: " + index );
  442. }
  443. },
  444. getComponent: function ( index ) {
  445. switch ( index ) {
  446. case 0: return this.x;
  447. case 1: return this.y;
  448. default: throw new Error( "index is out of range: " + index );
  449. }
  450. },
  451. copy: function ( v ) {
  452. this.x = v.x;
  453. this.y = v.y;
  454. return this;
  455. },
  456. add: function ( v, w ) {
  457. if ( w !== undefined ) {
  458. console.warn( 'DEPRECATED: Vector2\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  459. return this.addVectors( v, w );
  460. }
  461. this.x += v.x;
  462. this.y += v.y;
  463. return this;
  464. },
  465. addVectors: function ( a, b ) {
  466. this.x = a.x + b.x;
  467. this.y = a.y + b.y;
  468. return this;
  469. },
  470. addScalar: function ( s ) {
  471. this.x += s;
  472. this.y += s;
  473. return this;
  474. },
  475. sub: function ( v, w ) {
  476. if ( w !== undefined ) {
  477. console.warn( 'DEPRECATED: Vector2\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  478. return this.subVectors( v, w );
  479. }
  480. this.x -= v.x;
  481. this.y -= v.y;
  482. return this;
  483. },
  484. subVectors: function ( a, b ) {
  485. this.x = a.x - b.x;
  486. this.y = a.y - b.y;
  487. return this;
  488. },
  489. multiplyScalar: function ( s ) {
  490. this.x *= s;
  491. this.y *= s;
  492. return this;
  493. },
  494. divideScalar: function ( s ) {
  495. if ( s !== 0 ) {
  496. this.x /= s;
  497. this.y /= s;
  498. } else {
  499. this.set( 0, 0 );
  500. }
  501. return this;
  502. },
  503. min: function ( v ) {
  504. if ( this.x > v.x ) {
  505. this.x = v.x;
  506. }
  507. if ( this.y > v.y ) {
  508. this.y = v.y;
  509. }
  510. return this;
  511. },
  512. max: function ( v ) {
  513. if ( this.x < v.x ) {
  514. this.x = v.x;
  515. }
  516. if ( this.y < v.y ) {
  517. this.y = v.y;
  518. }
  519. return this;
  520. },
  521. clamp: function ( min, max ) {
  522. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  523. if ( this.x < min.x ) {
  524. this.x = min.x;
  525. } else if ( this.x > max.x ) {
  526. this.x = max.x;
  527. }
  528. if ( this.y < min.y ) {
  529. this.y = min.y;
  530. } else if ( this.y > max.y ) {
  531. this.y = max.y;
  532. }
  533. return this;
  534. },
  535. negate: function() {
  536. return this.multiplyScalar( - 1 );
  537. },
  538. dot: function ( v ) {
  539. return this.x * v.x + this.y * v.y;
  540. },
  541. lengthSq: function () {
  542. return this.x * this.x + this.y * this.y;
  543. },
  544. length: function () {
  545. return Math.sqrt( this.x * this.x + this.y * this.y );
  546. },
  547. normalize: function () {
  548. return this.divideScalar( this.length() );
  549. },
  550. distanceTo: function ( v ) {
  551. return Math.sqrt( this.distanceToSquared( v ) );
  552. },
  553. distanceToSquared: function ( v ) {
  554. var dx = this.x - v.x, dy = this.y - v.y;
  555. return dx * dx + dy * dy;
  556. },
  557. setLength: function ( l ) {
  558. var oldLength = this.length();
  559. if ( oldLength !== 0 && l !== oldLength ) {
  560. this.multiplyScalar( l / oldLength );
  561. }
  562. return this;
  563. },
  564. lerp: function ( v, alpha ) {
  565. this.x += ( v.x - this.x ) * alpha;
  566. this.y += ( v.y - this.y ) * alpha;
  567. return this;
  568. },
  569. equals: function( v ) {
  570. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  571. },
  572. clone: function () {
  573. return new THREE.Vector2( this.x, this.y );
  574. }
  575. };
  576. /**
  577. * @author mrdoob / http://mrdoob.com/
  578. * @author *kile / http://kile.stravaganza.org/
  579. * @author philogb / http://blog.thejit.org/
  580. * @author mikael emtinger / http://gomo.se/
  581. * @author egraether / http://egraether.com/
  582. * @author WestLangley / http://github.com/WestLangley
  583. */
  584. THREE.Vector3 = function ( x, y, z ) {
  585. this.x = x || 0;
  586. this.y = y || 0;
  587. this.z = z || 0;
  588. };
  589. THREE.Vector3.prototype = {
  590. constructor: THREE.Vector3,
  591. set: function ( x, y, z ) {
  592. this.x = x;
  593. this.y = y;
  594. this.z = z;
  595. return this;
  596. },
  597. setX: function ( x ) {
  598. this.x = x;
  599. return this;
  600. },
  601. setY: function ( y ) {
  602. this.y = y;
  603. return this;
  604. },
  605. setZ: function ( z ) {
  606. this.z = z;
  607. return this;
  608. },
  609. setComponent: function ( index, value ) {
  610. switch ( index ) {
  611. case 0: this.x = value; break;
  612. case 1: this.y = value; break;
  613. case 2: this.z = value; break;
  614. default: throw new Error( "index is out of range: " + index );
  615. }
  616. },
  617. getComponent: function ( index ) {
  618. switch ( index ) {
  619. case 0: return this.x;
  620. case 1: return this.y;
  621. case 2: return this.z;
  622. default: throw new Error( "index is out of range: " + index );
  623. }
  624. },
  625. copy: function ( v ) {
  626. this.x = v.x;
  627. this.y = v.y;
  628. this.z = v.z;
  629. return this;
  630. },
  631. add: function ( v, w ) {
  632. if ( w !== undefined ) {
  633. console.warn( 'DEPRECATED: Vector3\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  634. return this.addVectors( v, w );
  635. }
  636. this.x += v.x;
  637. this.y += v.y;
  638. this.z += v.z;
  639. return this;
  640. },
  641. addScalar: function ( s ) {
  642. this.x += s;
  643. this.y += s;
  644. this.z += s;
  645. return this;
  646. },
  647. addVectors: function ( a, b ) {
  648. this.x = a.x + b.x;
  649. this.y = a.y + b.y;
  650. this.z = a.z + b.z;
  651. return this;
  652. },
  653. sub: function ( v, w ) {
  654. if ( w !== undefined ) {
  655. console.warn( 'DEPRECATED: Vector3\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  656. return this.subVectors( v, w );
  657. }
  658. this.x -= v.x;
  659. this.y -= v.y;
  660. this.z -= v.z;
  661. return this;
  662. },
  663. subVectors: function ( a, b ) {
  664. this.x = a.x - b.x;
  665. this.y = a.y - b.y;
  666. this.z = a.z - b.z;
  667. return this;
  668. },
  669. multiply: function ( v, w ) {
  670. if ( w !== undefined ) {
  671. console.warn( 'DEPRECATED: Vector3\'s .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  672. return this.multiplyVectors( v, w );
  673. }
  674. this.x *= v.x;
  675. this.y *= v.y;
  676. this.z *= v.z;
  677. return this;
  678. },
  679. multiplyScalar: function ( s ) {
  680. this.x *= s;
  681. this.y *= s;
  682. this.z *= s;
  683. return this;
  684. },
  685. multiplyVectors: function ( a, b ) {
  686. this.x = a.x * b.x;
  687. this.y = a.y * b.y;
  688. this.z = a.z * b.z;
  689. return this;
  690. },
  691. applyMatrix3: function ( m ) {
  692. var x = this.x;
  693. var y = this.y;
  694. var z = this.z;
  695. var e = m.elements;
  696. this.x = e[0] * x + e[3] * y + e[6] * z;
  697. this.y = e[1] * x + e[4] * y + e[7] * z;
  698. this.z = e[2] * x + e[5] * y + e[8] * z;
  699. return this;
  700. },
  701. applyMatrix4: function ( m ) {
  702. var x = this.x;
  703. var y = this.y;
  704. var z = this.z;
  705. var e = m.elements;
  706. var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] );
  707. this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
  708. this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
  709. this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
  710. return this;
  711. },
  712. applyQuaternion: function ( q ) {
  713. var x = this.x;
  714. var y = this.y;
  715. var z = this.z;
  716. var qx = q.x;
  717. var qy = q.y;
  718. var qz = q.z;
  719. var qw = q.w;
  720. // calculate quat * vector
  721. var ix = qw * x + qy * z - qz * y;
  722. var iy = qw * y + qz * x - qx * z;
  723. var iz = qw * z + qx * y - qy * x;
  724. var iw = -qx * x - qy * y - qz * z;
  725. // calculate result * inverse quat
  726. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  727. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  728. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  729. return this;
  730. },
  731. divide: function ( v ) {
  732. this.x /= v.x;
  733. this.y /= v.y;
  734. this.z /= v.z;
  735. return this;
  736. },
  737. divideScalar: function ( s ) {
  738. if ( s !== 0 ) {
  739. this.x /= s;
  740. this.y /= s;
  741. this.z /= s;
  742. } else {
  743. this.x = 0;
  744. this.y = 0;
  745. this.z = 0;
  746. }
  747. return this;
  748. },
  749. min: function ( v ) {
  750. if ( this.x > v.x ) {
  751. this.x = v.x;
  752. }
  753. if ( this.y > v.y ) {
  754. this.y = v.y;
  755. }
  756. if ( this.z > v.z ) {
  757. this.z = v.z;
  758. }
  759. return this;
  760. },
  761. max: function ( v ) {
  762. if ( this.x < v.x ) {
  763. this.x = v.x;
  764. }
  765. if ( this.y < v.y ) {
  766. this.y = v.y;
  767. }
  768. if ( this.z < v.z ) {
  769. this.z = v.z;
  770. }
  771. return this;
  772. },
  773. clamp: function ( min, max ) {
  774. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  775. if ( this.x < min.x ) {
  776. this.x = min.x;
  777. } else if ( this.x > max.x ) {
  778. this.x = max.x;
  779. }
  780. if ( this.y < min.y ) {
  781. this.y = min.y;
  782. } else if ( this.y > max.y ) {
  783. this.y = max.y;
  784. }
  785. if ( this.z < min.z ) {
  786. this.z = min.z;
  787. } else if ( this.z > max.z ) {
  788. this.z = max.z;
  789. }
  790. return this;
  791. },
  792. negate: function() {
  793. return this.multiplyScalar( - 1 );
  794. },
  795. dot: function ( v ) {
  796. return this.x * v.x + this.y * v.y + this.z * v.z;
  797. },
  798. lengthSq: function () {
  799. return this.x * this.x + this.y * this.y + this.z * this.z;
  800. },
  801. length: function () {
  802. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  803. },
  804. lengthManhattan: function () {
  805. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  806. },
  807. normalize: function () {
  808. return this.divideScalar( this.length() );
  809. },
  810. setLength: function ( l ) {
  811. var oldLength = this.length();
  812. if ( oldLength !== 0 && l !== oldLength ) {
  813. this.multiplyScalar( l / oldLength );
  814. }
  815. return this;
  816. },
  817. lerp: function ( v, alpha ) {
  818. this.x += ( v.x - this.x ) * alpha;
  819. this.y += ( v.y - this.y ) * alpha;
  820. this.z += ( v.z - this.z ) * alpha;
  821. return this;
  822. },
  823. cross: function ( v, w ) {
  824. if ( w !== undefined ) {
  825. console.warn( 'DEPRECATED: Vector3\'s .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  826. return this.crossVectors( v, w );
  827. }
  828. var x = this.x, y = this.y, z = this.z;
  829. this.x = y * v.z - z * v.y;
  830. this.y = z * v.x - x * v.z;
  831. this.z = x * v.y - y * v.x;
  832. return this;
  833. },
  834. crossVectors: function ( a, b ) {
  835. this.x = a.y * b.z - a.z * b.y;
  836. this.y = a.z * b.x - a.x * b.z;
  837. this.z = a.x * b.y - a.y * b.x;
  838. return this;
  839. },
  840. angleTo: function ( v ) {
  841. return Math.acos( this.dot( v ) / this.length() / v.length() );
  842. },
  843. distanceTo: function ( v ) {
  844. return Math.sqrt( this.distanceToSquared( v ) );
  845. },
  846. distanceToSquared: function ( v ) {
  847. var dx = this.x - v.x;
  848. var dy = this.y - v.y;
  849. var dz = this.z - v.z;
  850. return dx * dx + dy * dy + dz * dz;
  851. },
  852. getPositionFromMatrix: function ( m ) {
  853. this.x = m.elements[12];
  854. this.y = m.elements[13];
  855. this.z = m.elements[14];
  856. return this;
  857. },
  858. setEulerFromRotationMatrix: function ( m, order ) {
  859. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  860. // clamp, to handle numerical problems
  861. function clamp( x ) {
  862. return Math.min( Math.max( x, -1 ), 1 );
  863. }
  864. var te = m.elements;
  865. var m11 = te[0], m12 = te[4], m13 = te[8];
  866. var m21 = te[1], m22 = te[5], m23 = te[9];
  867. var m31 = te[2], m32 = te[6], m33 = te[10];
  868. if ( order === undefined || order === 'XYZ' ) {
  869. this.y = Math.asin( clamp( m13 ) );
  870. if ( Math.abs( m13 ) < 0.99999 ) {
  871. this.x = Math.atan2( - m23, m33 );
  872. this.z = Math.atan2( - m12, m11 );
  873. } else {
  874. this.x = Math.atan2( m32, m22 );
  875. this.z = 0;
  876. }
  877. } else if ( order === 'YXZ' ) {
  878. this.x = Math.asin( - clamp( m23 ) );
  879. if ( Math.abs( m23 ) < 0.99999 ) {
  880. this.y = Math.atan2( m13, m33 );
  881. this.z = Math.atan2( m21, m22 );
  882. } else {
  883. this.y = Math.atan2( - m31, m11 );
  884. this.z = 0;
  885. }
  886. } else if ( order === 'ZXY' ) {
  887. this.x = Math.asin( clamp( m32 ) );
  888. if ( Math.abs( m32 ) < 0.99999 ) {
  889. this.y = Math.atan2( - m31, m33 );
  890. this.z = Math.atan2( - m12, m22 );
  891. } else {
  892. this.y = 0;
  893. this.z = Math.atan2( m21, m11 );
  894. }
  895. } else if ( order === 'ZYX' ) {
  896. this.y = Math.asin( - clamp( m31 ) );
  897. if ( Math.abs( m31 ) < 0.99999 ) {
  898. this.x = Math.atan2( m32, m33 );
  899. this.z = Math.atan2( m21, m11 );
  900. } else {
  901. this.x = 0;
  902. this.z = Math.atan2( - m12, m22 );
  903. }
  904. } else if ( order === 'YZX' ) {
  905. this.z = Math.asin( clamp( m21 ) );
  906. if ( Math.abs( m21 ) < 0.99999 ) {
  907. this.x = Math.atan2( - m23, m22 );
  908. this.y = Math.atan2( - m31, m11 );
  909. } else {
  910. this.x = 0;
  911. this.y = Math.atan2( m13, m33 );
  912. }
  913. } else if ( order === 'XZY' ) {
  914. this.z = Math.asin( - clamp( m12 ) );
  915. if ( Math.abs( m12 ) < 0.99999 ) {
  916. this.x = Math.atan2( m32, m22 );
  917. this.y = Math.atan2( m13, m11 );
  918. } else {
  919. this.x = Math.atan2( - m23, m33 );
  920. this.y = 0;
  921. }
  922. }
  923. return this;
  924. },
  925. setEulerFromQuaternion: function ( q, order ) {
  926. // q is assumed to be normalized
  927. // clamp, to handle numerical problems
  928. function clamp( x ) {
  929. return Math.min( Math.max( x, -1 ), 1 );
  930. }
  931. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  932. var sqx = q.x * q.x;
  933. var sqy = q.y * q.y;
  934. var sqz = q.z * q.z;
  935. var sqw = q.w * q.w;
  936. if ( order === undefined || order === 'XYZ' ) {
  937. this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  938. this.y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  939. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  940. } else if ( order === 'YXZ' ) {
  941. this.x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  942. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  943. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  944. } else if ( order === 'ZXY' ) {
  945. this.x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  946. this.y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  947. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  948. } else if ( order === 'ZYX' ) {
  949. this.x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  950. this.y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  951. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  952. } else if ( order === 'YZX' ) {
  953. this.x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  954. this.y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  955. this.z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  956. } else if ( order === 'XZY' ) {
  957. this.x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  958. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  959. this.z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  960. }
  961. return this;
  962. },
  963. getScaleFromMatrix: function ( m ) {
  964. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  965. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  966. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  967. this.x = sx;
  968. this.y = sy;
  969. this.z = sz;
  970. return this;
  971. },
  972. equals: function ( v ) {
  973. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  974. },
  975. clone: function () {
  976. return new THREE.Vector3( this.x, this.y, this.z );
  977. }
  978. };
  979. /**
  980. * @author supereggbert / http://www.paulbrunt.co.uk/
  981. * @author philogb / http://blog.thejit.org/
  982. * @author mikael emtinger / http://gomo.se/
  983. * @author egraether / http://egraether.com/
  984. * @author WestLangley / http://github.com/WestLangley
  985. */
  986. THREE.Vector4 = function ( x, y, z, w ) {
  987. this.x = x || 0;
  988. this.y = y || 0;
  989. this.z = z || 0;
  990. this.w = ( w !== undefined ) ? w : 1;
  991. };
  992. THREE.Vector4.prototype = {
  993. constructor: THREE.Vector4,
  994. set: function ( x, y, z, w ) {
  995. this.x = x;
  996. this.y = y;
  997. this.z = z;
  998. this.w = w;
  999. return this;
  1000. },
  1001. setX: function ( x ) {
  1002. this.x = x;
  1003. return this;
  1004. },
  1005. setY: function ( y ) {
  1006. this.y = y;
  1007. return this;
  1008. },
  1009. setZ: function ( z ) {
  1010. this.z = z;
  1011. return this;
  1012. },
  1013. setW: function ( w ) {
  1014. this.w = w;
  1015. return this;
  1016. },
  1017. setComponent: function ( index, value ) {
  1018. switch ( index ) {
  1019. case 0: this.x = value; break;
  1020. case 1: this.y = value; break;
  1021. case 2: this.z = value; break;
  1022. case 3: this.w = value; break;
  1023. default: throw new Error( "index is out of range: " + index );
  1024. }
  1025. },
  1026. getComponent: function ( index ) {
  1027. switch ( index ) {
  1028. case 0: return this.x;
  1029. case 1: return this.y;
  1030. case 2: return this.z;
  1031. case 3: return this.w;
  1032. default: throw new Error( "index is out of range: " + index );
  1033. }
  1034. },
  1035. copy: function ( v ) {
  1036. this.x = v.x;
  1037. this.y = v.y;
  1038. this.z = v.z;
  1039. this.w = ( v.w !== undefined ) ? v.w : 1;
  1040. return this;
  1041. },
  1042. add: function ( v, w ) {
  1043. if ( w !== undefined ) {
  1044. console.warn( 'DEPRECATED: Vector4\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1045. return this.addVectors( v, w );
  1046. }
  1047. this.x += v.x;
  1048. this.y += v.y;
  1049. this.z += v.z;
  1050. this.w += v.w;
  1051. return this;
  1052. },
  1053. addScalar: function ( s ) {
  1054. this.x += s;
  1055. this.y += s;
  1056. this.z += s;
  1057. this.w += s;
  1058. return this;
  1059. },
  1060. addVectors: function ( a, b ) {
  1061. this.x = a.x + b.x;
  1062. this.y = a.y + b.y;
  1063. this.z = a.z + b.z;
  1064. this.w = a.w + b.w;
  1065. return this;
  1066. },
  1067. sub: function ( v, w ) {
  1068. if ( w !== undefined ) {
  1069. console.warn( 'DEPRECATED: Vector4\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1070. return this.subVectors( v, w );
  1071. }
  1072. this.x -= v.x;
  1073. this.y -= v.y;
  1074. this.z -= v.z;
  1075. this.w -= v.w;
  1076. return this;
  1077. },
  1078. subVectors: function ( a, b ) {
  1079. this.x = a.x - b.x;
  1080. this.y = a.y - b.y;
  1081. this.z = a.z - b.z;
  1082. this.w = a.w - b.w;
  1083. return this;
  1084. },
  1085. multiplyScalar: function ( s ) {
  1086. this.x *= s;
  1087. this.y *= s;
  1088. this.z *= s;
  1089. this.w *= s;
  1090. return this;
  1091. },
  1092. applyMatrix4: function ( m ) {
  1093. var x = this.x;
  1094. var y = this.y;
  1095. var z = this.z;
  1096. var w = this.w;
  1097. var e = m.elements;
  1098. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1099. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1100. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1101. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1102. return this;
  1103. },
  1104. divideScalar: function ( s ) {
  1105. if ( s !== 0 ) {
  1106. this.x /= s;
  1107. this.y /= s;
  1108. this.z /= s;
  1109. this.w /= s;
  1110. } else {
  1111. this.x = 0;
  1112. this.y = 0;
  1113. this.z = 0;
  1114. this.w = 1;
  1115. }
  1116. return this;
  1117. },
  1118. min: function ( v ) {
  1119. if ( this.x > v.x ) {
  1120. this.x = v.x;
  1121. }
  1122. if ( this.y > v.y ) {
  1123. this.y = v.y;
  1124. }
  1125. if ( this.z > v.z ) {
  1126. this.z = v.z;
  1127. }
  1128. if ( this.w > v.w ) {
  1129. this.w = v.w;
  1130. }
  1131. return this;
  1132. },
  1133. max: function ( v ) {
  1134. if ( this.x < v.x ) {
  1135. this.x = v.x;
  1136. }
  1137. if ( this.y < v.y ) {
  1138. this.y = v.y;
  1139. }
  1140. if ( this.z < v.z ) {
  1141. this.z = v.z;
  1142. }
  1143. if ( this.w < v.w ) {
  1144. this.w = v.w;
  1145. }
  1146. return this;
  1147. },
  1148. clamp: function ( min, max ) {
  1149. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1150. if ( this.x < min.x ) {
  1151. this.x = min.x;
  1152. } else if ( this.x > max.x ) {
  1153. this.x = max.x;
  1154. }
  1155. if ( this.y < min.y ) {
  1156. this.y = min.y;
  1157. } else if ( this.y > max.y ) {
  1158. this.y = max.y;
  1159. }
  1160. if ( this.z < min.z ) {
  1161. this.z = min.z;
  1162. } else if ( this.z > max.z ) {
  1163. this.z = max.z;
  1164. }
  1165. if ( this.w < min.w ) {
  1166. this.w = min.w;
  1167. } else if ( this.w > max.w ) {
  1168. this.w = max.w;
  1169. }
  1170. return this;
  1171. },
  1172. negate: function() {
  1173. return this.multiplyScalar( -1 );
  1174. },
  1175. dot: function ( v ) {
  1176. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1177. },
  1178. lengthSq: function () {
  1179. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1180. },
  1181. length: function () {
  1182. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1183. },
  1184. lengthManhattan: function () {
  1185. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1186. },
  1187. normalize: function () {
  1188. return this.divideScalar( this.length() );
  1189. },
  1190. setLength: function ( l ) {
  1191. var oldLength = this.length();
  1192. if ( oldLength !== 0 && l !== oldLength ) {
  1193. this.multiplyScalar( l / oldLength );
  1194. }
  1195. return this;
  1196. },
  1197. lerp: function ( v, alpha ) {
  1198. this.x += ( v.x - this.x ) * alpha;
  1199. this.y += ( v.y - this.y ) * alpha;
  1200. this.z += ( v.z - this.z ) * alpha;
  1201. this.w += ( v.w - this.w ) * alpha;
  1202. return this;
  1203. },
  1204. equals: function ( v ) {
  1205. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1206. },
  1207. clone: function () {
  1208. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1209. },
  1210. setAxisAngleFromQuaternion: function ( q ) {
  1211. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1212. // q is assumed to be normalized
  1213. this.w = 2 * Math.acos( q.w );
  1214. var s = Math.sqrt( 1 - q.w * q.w );
  1215. if ( s < 0.0001 ) {
  1216. this.x = 1;
  1217. this.y = 0;
  1218. this.z = 0;
  1219. } else {
  1220. this.x = q.x / s;
  1221. this.y = q.y / s;
  1222. this.z = q.z / s;
  1223. }
  1224. return this;
  1225. },
  1226. setAxisAngleFromRotationMatrix: function ( m ) {
  1227. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1228. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1229. var angle, x, y, z, // variables for result
  1230. epsilon = 0.01, // margin to allow for rounding errors
  1231. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1232. te = m.elements,
  1233. m11 = te[0], m12 = te[4], m13 = te[8],
  1234. m21 = te[1], m22 = te[5], m23 = te[9],
  1235. m31 = te[2], m32 = te[6], m33 = te[10];
  1236. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1237. && ( Math.abs( m13 - m31 ) < epsilon )
  1238. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1239. // singularity found
  1240. // first check for identity matrix which must have +1 for all terms
  1241. // in leading diagonal and zero in other terms
  1242. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1243. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1244. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1245. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1246. // this singularity is identity matrix so angle = 0
  1247. this.set( 1, 0, 0, 0 );
  1248. return this; // zero angle, arbitrary axis
  1249. }
  1250. // otherwise this singularity is angle = 180
  1251. angle = Math.PI;
  1252. var xx = ( m11 + 1 ) / 2;
  1253. var yy = ( m22 + 1 ) / 2;
  1254. var zz = ( m33 + 1 ) / 2;
  1255. var xy = ( m12 + m21 ) / 4;
  1256. var xz = ( m13 + m31 ) / 4;
  1257. var yz = ( m23 + m32 ) / 4;
  1258. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1259. if ( xx < epsilon ) {
  1260. x = 0;
  1261. y = 0.707106781;
  1262. z = 0.707106781;
  1263. } else {
  1264. x = Math.sqrt( xx );
  1265. y = xy / x;
  1266. z = xz / x;
  1267. }
  1268. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1269. if ( yy < epsilon ) {
  1270. x = 0.707106781;
  1271. y = 0;
  1272. z = 0.707106781;
  1273. } else {
  1274. y = Math.sqrt( yy );
  1275. x = xy / y;
  1276. z = yz / y;
  1277. }
  1278. } else { // m33 is the largest diagonal term so base result on this
  1279. if ( zz < epsilon ) {
  1280. x = 0.707106781;
  1281. y = 0.707106781;
  1282. z = 0;
  1283. } else {
  1284. z = Math.sqrt( zz );
  1285. x = xz / z;
  1286. y = yz / z;
  1287. }
  1288. }
  1289. this.set( x, y, z, angle );
  1290. return this; // return 180 deg rotation
  1291. }
  1292. // as we have reached here there are no singularities so we can handle normally
  1293. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1294. + ( m13 - m31 ) * ( m13 - m31 )
  1295. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1296. if ( Math.abs( s ) < 0.001 ) s = 1;
  1297. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1298. // caught by singularity test above, but I've left it in just in case
  1299. this.x = ( m32 - m23 ) / s;
  1300. this.y = ( m13 - m31 ) / s;
  1301. this.z = ( m21 - m12 ) / s;
  1302. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1303. return this;
  1304. }
  1305. };
  1306. /**
  1307. * @author bhouston / http://exocortex.com
  1308. */
  1309. THREE.Box2 = function ( min, max ) {
  1310. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  1311. this.max = ( max !== undefined ) ? max : new THREE.Vector2( -Infinity, -Infinity );
  1312. };
  1313. THREE.Box2.prototype = {
  1314. constructor: THREE.Box2,
  1315. set: function ( min, max ) {
  1316. this.min.copy( min );
  1317. this.max.copy( max );
  1318. return this;
  1319. },
  1320. setFromPoints: function ( points ) {
  1321. if ( points.length > 0 ) {
  1322. var point = points[ 0 ];
  1323. this.min.copy( point );
  1324. this.max.copy( point );
  1325. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1326. point = points[ i ];
  1327. if ( point.x < this.min.x ) {
  1328. this.min.x = point.x;
  1329. } else if ( point.x > this.max.x ) {
  1330. this.max.x = point.x;
  1331. }
  1332. if ( point.y < this.min.y ) {
  1333. this.min.y = point.y;
  1334. } else if ( point.y > this.max.y ) {
  1335. this.max.y = point.y;
  1336. }
  1337. }
  1338. } else {
  1339. this.makeEmpty();
  1340. }
  1341. return this;
  1342. },
  1343. setFromCenterAndSize: function ( center, size ) {
  1344. var halfSize = THREE.Box2.__v1.copy( size ).multiplyScalar( 0.5 );
  1345. this.min.copy( center ).sub( halfSize );
  1346. this.max.copy( center ).add( halfSize );
  1347. return this;
  1348. },
  1349. copy: function ( box ) {
  1350. this.min.copy( box.min );
  1351. this.max.copy( box.max );
  1352. return this;
  1353. },
  1354. makeEmpty: function () {
  1355. this.min.x = this.min.y = Infinity;
  1356. this.max.x = this.max.y = -Infinity;
  1357. return this;
  1358. },
  1359. empty: function () {
  1360. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1361. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  1362. },
  1363. center: function ( optionalTarget ) {
  1364. var result = optionalTarget || new THREE.Vector2();
  1365. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1366. },
  1367. size: function ( optionalTarget ) {
  1368. var result = optionalTarget || new THREE.Vector2();
  1369. return result.subVectors( this.max, this.min );
  1370. },
  1371. expandByPoint: function ( point ) {
  1372. this.min.min( point );
  1373. this.max.max( point );
  1374. return this;
  1375. },
  1376. expandByVector: function ( vector ) {
  1377. this.min.sub( vector );
  1378. this.max.add( vector );
  1379. return this;
  1380. },
  1381. expandByScalar: function ( scalar ) {
  1382. this.min.addScalar( -scalar );
  1383. this.max.addScalar( scalar );
  1384. return this;
  1385. },
  1386. containsPoint: function ( point ) {
  1387. if ( ( this.min.x <= point.x ) && ( point.x <= this.max.x ) &&
  1388. ( this.min.y <= point.y ) && ( point.y <= this.max.y ) ) {
  1389. return true;
  1390. }
  1391. return false;
  1392. },
  1393. containsBox: function ( box ) {
  1394. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1395. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  1396. return true;
  1397. }
  1398. return false;
  1399. },
  1400. getParameter: function ( point ) {
  1401. // This can potentially have a divide by zero if the box
  1402. // has a size dimension of 0.
  1403. return new THREE.Vector2(
  1404. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1405. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  1406. );
  1407. },
  1408. isIntersectionBox: function ( box ) {
  1409. // using 6 splitting planes to rule out intersections.
  1410. if ( ( box.max.x < this.min.x ) ||
  1411. ( box.min.x > this.max.x ) ||
  1412. ( box.max.y < this.min.y ) ||
  1413. ( box.min.y > this.max.y ) ) {
  1414. return false;
  1415. }
  1416. return true;
  1417. },
  1418. clampPoint: function ( point, optionalTarget ) {
  1419. var result = optionalTarget || new THREE.Vector2();
  1420. return result.copy( point ).clamp( this.min, this.max );
  1421. },
  1422. distanceToPoint: function ( point ) {
  1423. var clampedPoint = THREE.Box2.__v1.copy( point ).clamp( this.min, this.max );
  1424. return clampedPoint.sub( point ).length();
  1425. },
  1426. intersect: function ( box ) {
  1427. this.min.max( box.min );
  1428. this.max.min( box.max );
  1429. return this;
  1430. },
  1431. union: function ( box ) {
  1432. this.min.min( box.min );
  1433. this.max.max( box.max );
  1434. return this;
  1435. },
  1436. translate: function ( offset ) {
  1437. this.min.add( offset );
  1438. this.max.add( offset );
  1439. return this;
  1440. },
  1441. equals: function ( box ) {
  1442. return box.min.equals( this.min ) && box.max.equals( this.max );
  1443. },
  1444. clone: function () {
  1445. return new THREE.Box2().copy( this );
  1446. }
  1447. };
  1448. THREE.Box2.__v1 = new THREE.Vector2();
  1449. /**
  1450. * @author bhouston / http://exocortex.com
  1451. */
  1452. THREE.Box3 = function ( min, max ) {
  1453. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  1454. this.max = ( max !== undefined ) ? max : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  1455. };
  1456. THREE.Box3.prototype = {
  1457. constructor: THREE.Box3,
  1458. set: function ( min, max ) {
  1459. this.min.copy( min );
  1460. this.max.copy( max );
  1461. return this;
  1462. },
  1463. setFromPoints: function ( points ) {
  1464. if ( points.length > 0 ) {
  1465. var p = points[ 0 ];
  1466. this.min.copy( p );
  1467. this.max.copy( p );
  1468. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1469. p = points[ i ];
  1470. if ( p.x < this.min.x ) {
  1471. this.min.x = p.x;
  1472. } else if ( p.x > this.max.x ) {
  1473. this.max.x = p.x;
  1474. }
  1475. if ( p.y < this.min.y ) {
  1476. this.min.y = p.y;
  1477. } else if ( p.y > this.max.y ) {
  1478. this.max.y = p.y;
  1479. }
  1480. if ( p.z < this.min.z ) {
  1481. this.min.z = p.z;
  1482. } else if ( p.z > this.max.z ) {
  1483. this.max.z = p.z;
  1484. }
  1485. }
  1486. } else {
  1487. this.makeEmpty();
  1488. }
  1489. return this;
  1490. },
  1491. setFromCenterAndSize: function ( center, size ) {
  1492. var halfSize = THREE.Box3.__v1.copy( size ).multiplyScalar( 0.5 );
  1493. this.min.copy( center ).sub( halfSize );
  1494. this.max.copy( center ).add( halfSize );
  1495. return this;
  1496. },
  1497. copy: function ( box ) {
  1498. this.min.copy( box.min );
  1499. this.max.copy( box.max );
  1500. return this;
  1501. },
  1502. makeEmpty: function () {
  1503. this.min.x = this.min.y = this.min.z = Infinity;
  1504. this.max.x = this.max.y = this.max.z = -Infinity;
  1505. return this;
  1506. },
  1507. empty: function () {
  1508. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1509. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  1510. },
  1511. center: function ( optionalTarget ) {
  1512. var result = optionalTarget || new THREE.Vector3();
  1513. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1514. },
  1515. size: function ( optionalTarget ) {
  1516. var result = optionalTarget || new THREE.Vector3();
  1517. return result.subVectors( this.max, this.min );
  1518. },
  1519. expandByPoint: function ( point ) {
  1520. this.min.min( point );
  1521. this.max.max( point );
  1522. return this;
  1523. },
  1524. expandByVector: function ( vector ) {
  1525. this.min.sub( vector );
  1526. this.max.add( vector );
  1527. return this;
  1528. },
  1529. expandByScalar: function ( scalar ) {
  1530. this.min.addScalar( -scalar );
  1531. this.max.addScalar( scalar );
  1532. return this;
  1533. },
  1534. containsPoint: function ( point ) {
  1535. if ( ( this.min.x <= point.x ) && ( point.x <= this.max.x ) &&
  1536. ( this.min.y <= point.y ) && ( point.y <= this.max.y ) &&
  1537. ( this.min.z <= point.z ) && ( point.z <= this.max.z ) ) {
  1538. return true;
  1539. }
  1540. return false;
  1541. },
  1542. containsBox: function ( box ) {
  1543. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1544. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  1545. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  1546. return true;
  1547. }
  1548. return false;
  1549. },
  1550. getParameter: function ( point ) {
  1551. // This can potentially have a divide by zero if the box
  1552. // has a size dimension of 0.
  1553. return new THREE.Vector3(
  1554. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1555. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  1556. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  1557. );
  1558. },
  1559. isIntersectionBox: function ( box ) {
  1560. // using 6 splitting planes to rule out intersections.
  1561. if ( ( box.max.x < this.min.x ) || ( box.min.x > this.max.x ) ||
  1562. ( box.max.y < this.min.y ) || ( box.min.y > this.max.y ) ||
  1563. ( box.max.z < this.min.z ) || ( box.min.z > this.max.z ) ) {
  1564. return false;
  1565. }
  1566. return true;
  1567. },
  1568. clampPoint: function ( point, optionalTarget ) {
  1569. var result = optionalTarget || new THREE.Vector3();
  1570. return new THREE.Vector3().copy( point ).clamp( this.min, this.max );
  1571. },
  1572. distanceToPoint: function ( point ) {
  1573. var clampedPoint = THREE.Box3.__v1.copy( point ).clamp( this.min, this.max );
  1574. return clampedPoint.sub( point ).length();
  1575. },
  1576. getBoundingSphere: function ( optionalTarget ) {
  1577. var result = optionalTarget || new THREE.Sphere();
  1578. result.center = this.center();
  1579. result.radius = this.size( THREE.Box3.__v0 ).length() * 0.5;
  1580. return result;
  1581. },
  1582. intersect: function ( box ) {
  1583. this.min.max( box.min );
  1584. this.max.min( box.max );
  1585. return this;
  1586. },
  1587. union: function ( box ) {
  1588. this.min.min( box.min );
  1589. this.max.max( box.max );
  1590. return this;
  1591. },
  1592. transform: function ( matrix ) {
  1593. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  1594. var newPoints = [
  1595. THREE.Box3.__v0.set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ),
  1596. THREE.Box3.__v0.set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ), // 000
  1597. THREE.Box3.__v1.set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ), // 001
  1598. THREE.Box3.__v2.set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ), // 010
  1599. THREE.Box3.__v3.set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ), // 011
  1600. THREE.Box3.__v4.set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ), // 100
  1601. THREE.Box3.__v5.set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ), // 101
  1602. THREE.Box3.__v6.set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ), // 110
  1603. THREE.Box3.__v7.set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ) // 111
  1604. ];
  1605. this.makeEmpty();
  1606. this.setFromPoints( newPoints );
  1607. return this;
  1608. },
  1609. translate: function ( offset ) {
  1610. this.min.add( offset );
  1611. this.max.add( offset );
  1612. return this;
  1613. },
  1614. equals: function ( box ) {
  1615. return box.min.equals( this.min ) && box.max.equals( this.max );
  1616. },
  1617. clone: function () {
  1618. return new THREE.Box3().copy( this );
  1619. }
  1620. };
  1621. THREE.Box3.__v0 = new THREE.Vector3();
  1622. THREE.Box3.__v1 = new THREE.Vector3();
  1623. THREE.Box3.__v2 = new THREE.Vector3();
  1624. THREE.Box3.__v3 = new THREE.Vector3();
  1625. THREE.Box3.__v4 = new THREE.Vector3();
  1626. THREE.Box3.__v5 = new THREE.Vector3();
  1627. THREE.Box3.__v6 = new THREE.Vector3();
  1628. THREE.Box3.__v7 = new THREE.Vector3();
  1629. /**
  1630. * @author alteredq / http://alteredqualia.com/
  1631. * @author WestLangley / http://github.com/WestLangley
  1632. * @author bhouston / http://exocortex.com
  1633. */
  1634. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  1635. this.elements = new Float32Array(9);
  1636. this.set(
  1637. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0,
  1638. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0,
  1639. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1
  1640. );
  1641. };
  1642. THREE.Matrix3.prototype = {
  1643. constructor: THREE.Matrix3,
  1644. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  1645. var te = this.elements;
  1646. te[0] = n11; te[3] = n12; te[6] = n13;
  1647. te[1] = n21; te[4] = n22; te[7] = n23;
  1648. te[2] = n31; te[5] = n32; te[8] = n33;
  1649. return this;
  1650. },
  1651. identity: function () {
  1652. this.set(
  1653. 1, 0, 0,
  1654. 0, 1, 0,
  1655. 0, 0, 1
  1656. );
  1657. return this;
  1658. },
  1659. copy: function ( m ) {
  1660. var me = m.elements;
  1661. this.set(
  1662. me[0], me[3], me[6],
  1663. me[1], me[4], me[7],
  1664. me[2], me[5], me[8]
  1665. );
  1666. return this;
  1667. },
  1668. multiplyVector3: function ( vector ) {
  1669. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use is now vector.applyMatrix3( matrix ) instead.' );
  1670. return vector.applyMatrix3( this );
  1671. },
  1672. multiplyVector3Array: function ( a ) {
  1673. var tmp = THREE.Matrix3.__v1;
  1674. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  1675. tmp.x = a[ i ];
  1676. tmp.y = a[ i + 1 ];
  1677. tmp.z = a[ i + 2 ];
  1678. tmp.applyMatrix3(this);
  1679. a[ i ] = tmp.x;
  1680. a[ i + 1 ] = tmp.y;
  1681. a[ i + 2 ] = tmp.z;
  1682. }
  1683. return a;
  1684. },
  1685. multiplyScalar: function ( s ) {
  1686. var te = this.elements;
  1687. te[0] *= s; te[3] *= s; te[6] *= s;
  1688. te[1] *= s; te[4] *= s; te[7] *= s;
  1689. te[2] *= s; te[5] *= s; te[8] *= s;
  1690. return this;
  1691. },
  1692. determinant: function () {
  1693. var te = this.elements;
  1694. var a = te[0], b = te[1], c = te[2],
  1695. d = te[3], e = te[4], f = te[5],
  1696. g = te[6], h = te[7], i = te[8];
  1697. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  1698. },
  1699. getInverse: function ( matrix, throwOnInvertible ) {
  1700. // input: THREE.Matrix4
  1701. // ( based on http://code.google.com/p/webgl-mjs/ )
  1702. var me = matrix.elements;
  1703. var te = this.elements;
  1704. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  1705. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  1706. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  1707. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  1708. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  1709. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  1710. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  1711. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  1712. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  1713. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  1714. // no inverse
  1715. if ( det === 0 ) {
  1716. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  1717. if ( throwOnInvertible || false ) {
  1718. throw new Error( msg );
  1719. } else {
  1720. console.warn( msg );
  1721. }
  1722. this.identity();
  1723. return this;
  1724. }
  1725. this.multiplyScalar( 1.0 / det );
  1726. return this;
  1727. },
  1728. transpose: function () {
  1729. var tmp, m = this.elements;
  1730. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  1731. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  1732. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  1733. return this;
  1734. },
  1735. transposeIntoArray: function ( r ) {
  1736. var m = this.elements;
  1737. r[ 0 ] = m[ 0 ];
  1738. r[ 1 ] = m[ 3 ];
  1739. r[ 2 ] = m[ 6 ];
  1740. r[ 3 ] = m[ 1 ];
  1741. r[ 4 ] = m[ 4 ];
  1742. r[ 5 ] = m[ 7 ];
  1743. r[ 6 ] = m[ 2 ];
  1744. r[ 7 ] = m[ 5 ];
  1745. r[ 8 ] = m[ 8 ];
  1746. return this;
  1747. },
  1748. clone: function () {
  1749. var te = this.elements;
  1750. return new THREE.Matrix3(
  1751. te[0], te[3], te[6],
  1752. te[1], te[4], te[7],
  1753. te[2], te[5], te[8]
  1754. );
  1755. }
  1756. };
  1757. THREE.Matrix3.__v1 = new THREE.Vector3();
  1758. /**
  1759. * @author mrdoob / http://mrdoob.com/
  1760. * @author supereggbert / http://www.paulbrunt.co.uk/
  1761. * @author philogb / http://blog.thejit.org/
  1762. * @author jordi_ros / http://plattsoft.com
  1763. * @author D1plo1d / http://github.com/D1plo1d
  1764. * @author alteredq / http://alteredqualia.com/
  1765. * @author mikael emtinger / http://gomo.se/
  1766. * @author timknip / http://www.floorplanner.com/
  1767. * @author bhouston / http://exocortex.com
  1768. */
  1769. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1770. this.elements = new Float32Array( 16 );
  1771. this.set(
  1772. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0, n14 || 0,
  1773. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0, n24 || 0,
  1774. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1, n34 || 0,
  1775. n41 || 0, n42 || 0, n43 || 0, ( n44 !== undefined ) ? n44 : 1
  1776. );
  1777. };
  1778. THREE.Matrix4.prototype = {
  1779. constructor: THREE.Matrix4,
  1780. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1781. var te = this.elements;
  1782. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  1783. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  1784. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  1785. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  1786. return this;
  1787. },
  1788. identity: function () {
  1789. this.set(
  1790. 1, 0, 0, 0,
  1791. 0, 1, 0, 0,
  1792. 0, 0, 1, 0,
  1793. 0, 0, 0, 1
  1794. );
  1795. return this;
  1796. },
  1797. copy: function ( m ) {
  1798. var me = m.elements;
  1799. this.set(
  1800. me[0], me[4], me[8], me[12],
  1801. me[1], me[5], me[9], me[13],
  1802. me[2], me[6], me[10], me[14],
  1803. me[3], me[7], me[11], me[15]
  1804. );
  1805. return this;
  1806. },
  1807. setRotationFromEuler: function ( v, order ) {
  1808. var te = this.elements;
  1809. var x = v.x, y = v.y, z = v.z;
  1810. var a = Math.cos( x ), b = Math.sin( x );
  1811. var c = Math.cos( y ), d = Math.sin( y );
  1812. var e = Math.cos( z ), f = Math.sin( z );
  1813. if ( order === undefined || order === 'XYZ' ) {
  1814. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1815. te[0] = c * e;
  1816. te[4] = - c * f;
  1817. te[8] = d;
  1818. te[1] = af + be * d;
  1819. te[5] = ae - bf * d;
  1820. te[9] = - b * c;
  1821. te[2] = bf - ae * d;
  1822. te[6] = be + af * d;
  1823. te[10] = a * c;
  1824. } else if ( order === 'YXZ' ) {
  1825. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1826. te[0] = ce + df * b;
  1827. te[4] = de * b - cf;
  1828. te[8] = a * d;
  1829. te[1] = a * f;
  1830. te[5] = a * e;
  1831. te[9] = - b;
  1832. te[2] = cf * b - de;
  1833. te[6] = df + ce * b;
  1834. te[10] = a * c;
  1835. } else if ( order === 'ZXY' ) {
  1836. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1837. te[0] = ce - df * b;
  1838. te[4] = - a * f;
  1839. te[8] = de + cf * b;
  1840. te[1] = cf + de * b;
  1841. te[5] = a * e;
  1842. te[9] = df - ce * b;
  1843. te[2] = - a * d;
  1844. te[6] = b;
  1845. te[10] = a * c;
  1846. } else if ( order === 'ZYX' ) {
  1847. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1848. te[0] = c * e;
  1849. te[4] = be * d - af;
  1850. te[8] = ae * d + bf;
  1851. te[1] = c * f;
  1852. te[5] = bf * d + ae;
  1853. te[9] = af * d - be;
  1854. te[2] = - d;
  1855. te[6] = b * c;
  1856. te[10] = a * c;
  1857. } else if ( order === 'YZX' ) {
  1858. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1859. te[0] = c * e;
  1860. te[4] = bd - ac * f;
  1861. te[8] = bc * f + ad;
  1862. te[1] = f;
  1863. te[5] = a * e;
  1864. te[9] = - b * e;
  1865. te[2] = - d * e;
  1866. te[6] = ad * f + bc;
  1867. te[10] = ac - bd * f;
  1868. } else if ( order === 'XZY' ) {
  1869. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1870. te[0] = c * e;
  1871. te[4] = - f;
  1872. te[8] = d * e;
  1873. te[1] = ac * f + bd;
  1874. te[5] = a * e;
  1875. te[9] = ad * f - bc;
  1876. te[2] = bc * f - ad;
  1877. te[6] = b * e;
  1878. te[10] = bd * f + ac;
  1879. }
  1880. return this;
  1881. },
  1882. setRotationFromQuaternion: function ( q ) {
  1883. var te = this.elements;
  1884. var x = q.x, y = q.y, z = q.z, w = q.w;
  1885. var x2 = x + x, y2 = y + y, z2 = z + z;
  1886. var xx = x * x2, xy = x * y2, xz = x * z2;
  1887. var yy = y * y2, yz = y * z2, zz = z * z2;
  1888. var wx = w * x2, wy = w * y2, wz = w * z2;
  1889. te[0] = 1 - ( yy + zz );
  1890. te[4] = xy - wz;
  1891. te[8] = xz + wy;
  1892. te[1] = xy + wz;
  1893. te[5] = 1 - ( xx + zz );
  1894. te[9] = yz - wx;
  1895. te[2] = xz - wy;
  1896. te[6] = yz + wx;
  1897. te[10] = 1 - ( xx + yy );
  1898. return this;
  1899. },
  1900. lookAt: function ( eye, target, up ) {
  1901. var te = this.elements;
  1902. var x = THREE.Matrix4.__v1;
  1903. var y = THREE.Matrix4.__v2;
  1904. var z = THREE.Matrix4.__v3;
  1905. z.subVectors( eye, target ).normalize();
  1906. if ( z.length() === 0 ) {
  1907. z.z = 1;
  1908. }
  1909. x.crossVectors( up, z ).normalize();
  1910. if ( x.length() === 0 ) {
  1911. z.x += 0.0001;
  1912. x.crossVectors( up, z ).normalize();
  1913. }
  1914. y.crossVectors( z, x );
  1915. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  1916. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  1917. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  1918. return this;
  1919. },
  1920. multiply: function ( m, n ) {
  1921. if ( n !== undefined ) {
  1922. console.warn( 'DEPRECATED: Matrix4\'s .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  1923. return this.multiplyMatrices( m, n );
  1924. }
  1925. return this.multiplyMatrices( this, m );
  1926. },
  1927. multiplyMatrices: function ( a, b ) {
  1928. var ae = a.elements;
  1929. var be = b.elements;
  1930. var te = this.elements;
  1931. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  1932. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  1933. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  1934. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  1935. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  1936. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  1937. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  1938. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  1939. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  1940. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  1941. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  1942. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  1943. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  1944. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  1945. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  1946. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  1947. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  1948. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  1949. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  1950. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  1951. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  1952. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  1953. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  1954. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  1955. return this;
  1956. },
  1957. multiplyToArray: function ( a, b, r ) {
  1958. var te = this.elements;
  1959. this.multiplyMatrices( a, b );
  1960. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  1961. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  1962. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  1963. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  1964. return this;
  1965. },
  1966. multiplyScalar: function ( s ) {
  1967. var te = this.elements;
  1968. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  1969. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  1970. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  1971. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  1972. return this;
  1973. },
  1974. multiplyVector3: function ( vector ) {
  1975. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3() has been removed. Use is now vector.applyMatrix4( matrix ) instead.' );
  1976. return vector.applyMatrix4( this );
  1977. },
  1978. multiplyVector4: function ( vector ) {
  1979. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector4() has been removed. Use is now vector.applyMatrix4( matrix ) instead.' );
  1980. return vector.applyMatrix4( this );
  1981. },
  1982. multiplyVector3Array: function ( a ) {
  1983. var tmp = THREE.Matrix4.__v1;
  1984. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  1985. tmp.x = a[ i ];
  1986. tmp.y = a[ i + 1 ];
  1987. tmp.z = a[ i + 2 ];
  1988. tmp.applyMatrix4(this);
  1989. a[ i ] = tmp.x;
  1990. a[ i + 1 ] = tmp.y;
  1991. a[ i + 2 ] = tmp.z;
  1992. }
  1993. return a;
  1994. },
  1995. rotateAxis: function ( v ) {
  1996. var te = this.elements;
  1997. var vx = v.x, vy = v.y, vz = v.z;
  1998. v.x = vx * te[0] + vy * te[4] + vz * te[8];
  1999. v.y = vx * te[1] + vy * te[5] + vz * te[9];
  2000. v.z = vx * te[2] + vy * te[6] + vz * te[10];
  2001. v.normalize();
  2002. return v;
  2003. },
  2004. crossVector: function ( a ) {
  2005. var te = this.elements;
  2006. var v = new THREE.Vector4();
  2007. v.x = te[0] * a.x + te[4] * a.y + te[8] * a.z + te[12] * a.w;
  2008. v.y = te[1] * a.x + te[5] * a.y + te[9] * a.z + te[13] * a.w;
  2009. v.z = te[2] * a.x + te[6] * a.y + te[10] * a.z + te[14] * a.w;
  2010. v.w = ( a.w ) ? te[3] * a.x + te[7] * a.y + te[11] * a.z + te[15] * a.w : 1;
  2011. return v;
  2012. },
  2013. determinant: function () {
  2014. var te = this.elements;
  2015. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  2016. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  2017. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  2018. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  2019. //TODO: make this more efficient
  2020. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2021. return (
  2022. n41 * (
  2023. +n14 * n23 * n32
  2024. -n13 * n24 * n32
  2025. -n14 * n22 * n33
  2026. +n12 * n24 * n33
  2027. +n13 * n22 * n34
  2028. -n12 * n23 * n34
  2029. ) +
  2030. n42 * (
  2031. +n11 * n23 * n34
  2032. -n11 * n24 * n33
  2033. +n14 * n21 * n33
  2034. -n13 * n21 * n34
  2035. +n13 * n24 * n31
  2036. -n14 * n23 * n31
  2037. ) +
  2038. n43 * (
  2039. +n11 * n24 * n32
  2040. -n11 * n22 * n34
  2041. -n14 * n21 * n32
  2042. +n12 * n21 * n34
  2043. +n14 * n22 * n31
  2044. -n12 * n24 * n31
  2045. ) +
  2046. n44 * (
  2047. -n13 * n22 * n31
  2048. -n11 * n23 * n32
  2049. +n11 * n22 * n33
  2050. +n13 * n21 * n32
  2051. -n12 * n21 * n33
  2052. +n12 * n23 * n31
  2053. )
  2054. );
  2055. },
  2056. transpose: function () {
  2057. var te = this.elements;
  2058. var tmp;
  2059. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  2060. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  2061. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  2062. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  2063. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  2064. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  2065. return this;
  2066. },
  2067. flattenToArray: function ( flat ) {
  2068. var te = this.elements;
  2069. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  2070. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  2071. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  2072. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  2073. return flat;
  2074. },
  2075. flattenToArrayOffset: function( flat, offset ) {
  2076. var te = this.elements;
  2077. flat[ offset ] = te[0];
  2078. flat[ offset + 1 ] = te[1];
  2079. flat[ offset + 2 ] = te[2];
  2080. flat[ offset + 3 ] = te[3];
  2081. flat[ offset + 4 ] = te[4];
  2082. flat[ offset + 5 ] = te[5];
  2083. flat[ offset + 6 ] = te[6];
  2084. flat[ offset + 7 ] = te[7];
  2085. flat[ offset + 8 ] = te[8];
  2086. flat[ offset + 9 ] = te[9];
  2087. flat[ offset + 10 ] = te[10];
  2088. flat[ offset + 11 ] = te[11];
  2089. flat[ offset + 12 ] = te[12];
  2090. flat[ offset + 13 ] = te[13];
  2091. flat[ offset + 14 ] = te[14];
  2092. flat[ offset + 15 ] = te[15];
  2093. return flat;
  2094. },
  2095. getPosition: function () {
  2096. var te = this.elements;
  2097. return THREE.Matrix4.__v1.set( te[12], te[13], te[14] );
  2098. },
  2099. setPosition: function ( v ) {
  2100. var te = this.elements;
  2101. te[12] = v.x;
  2102. te[13] = v.y;
  2103. te[14] = v.z;
  2104. return this;
  2105. },
  2106. getColumnX: function () {
  2107. var te = this.elements;
  2108. return THREE.Matrix4.__v1.set( te[0], te[1], te[2] );
  2109. },
  2110. getColumnY: function () {
  2111. var te = this.elements;
  2112. return THREE.Matrix4.__v1.set( te[4], te[5], te[6] );
  2113. },
  2114. getColumnZ: function() {
  2115. var te = this.elements;
  2116. return THREE.Matrix4.__v1.set( te[8], te[9], te[10] );
  2117. },
  2118. getInverse: function ( m, throwOnInvertible ) {
  2119. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2120. var te = this.elements;
  2121. var me = m.elements;
  2122. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2123. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2124. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2125. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2126. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2127. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2128. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2129. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2130. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2131. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2132. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2133. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2134. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2135. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2136. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2137. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2138. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2139. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2140. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2141. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2142. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 4 ] + me[ 2 ] * te[ 8 ] + me[ 3 ] * te[ 12 ];
  2143. if ( det == 0 ) {
  2144. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2145. if ( throwOnInvertible || false ) {
  2146. throw new Error( msg );
  2147. } else {
  2148. console.warn( msg );
  2149. }
  2150. this.identity();
  2151. return this;
  2152. }
  2153. this.multiplyScalar( 1 / det );
  2154. return this;
  2155. },
  2156. compose: function ( translation, rotation, scale ) {
  2157. var te = this.elements;
  2158. var mRotation = THREE.Matrix4.__m1;
  2159. var mScale = THREE.Matrix4.__m2;
  2160. mRotation.identity();
  2161. mRotation.setRotationFromQuaternion( rotation );
  2162. mScale.makeScale( scale );
  2163. this.multiplyMatrices( mRotation, mScale );
  2164. te[12] = translation.x;
  2165. te[13] = translation.y;
  2166. te[14] = translation.z;
  2167. return this;
  2168. },
  2169. decompose: function ( translation, rotation, scale ) {
  2170. var te = this.elements;
  2171. // grab the axis vectors
  2172. var x = THREE.Matrix4.__v1;
  2173. var y = THREE.Matrix4.__v2;
  2174. var z = THREE.Matrix4.__v3;
  2175. x.set( te[0], te[1], te[2] );
  2176. y.set( te[4], te[5], te[6] );
  2177. z.set( te[8], te[9], te[10] );
  2178. translation = ( translation instanceof THREE.Vector3 ) ? translation : new THREE.Vector3();
  2179. rotation = ( rotation instanceof THREE.Quaternion ) ? rotation : new THREE.Quaternion();
  2180. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  2181. scale.x = x.length();
  2182. scale.y = y.length();
  2183. scale.z = z.length();
  2184. translation.x = te[12];
  2185. translation.y = te[13];
  2186. translation.z = te[14];
  2187. // scale the rotation part
  2188. var matrix = THREE.Matrix4.__m1;
  2189. matrix.copy( this );
  2190. matrix.elements[0] /= scale.x;
  2191. matrix.elements[1] /= scale.x;
  2192. matrix.elements[2] /= scale.x;
  2193. matrix.elements[4] /= scale.y;
  2194. matrix.elements[5] /= scale.y;
  2195. matrix.elements[6] /= scale.y;
  2196. matrix.elements[8] /= scale.z;
  2197. matrix.elements[9] /= scale.z;
  2198. matrix.elements[10] /= scale.z;
  2199. rotation.setFromRotationMatrix( matrix );
  2200. return [ translation, rotation, scale ];
  2201. },
  2202. extractPosition: function ( m ) {
  2203. var te = this.elements;
  2204. var me = m.elements;
  2205. te[12] = me[12];
  2206. te[13] = me[13];
  2207. te[14] = me[14];
  2208. return this;
  2209. },
  2210. extractRotation: function ( m ) {
  2211. var te = this.elements;
  2212. var me = m.elements;
  2213. var vector = THREE.Matrix4.__v1;
  2214. var scaleX = 1 / vector.set( me[0], me[1], me[2] ).length();
  2215. var scaleY = 1 / vector.set( me[4], me[5], me[6] ).length();
  2216. var scaleZ = 1 / vector.set( me[8], me[9], me[10] ).length();
  2217. te[0] = me[0] * scaleX;
  2218. te[1] = me[1] * scaleX;
  2219. te[2] = me[2] * scaleX;
  2220. te[4] = me[4] * scaleY;
  2221. te[5] = me[5] * scaleY;
  2222. te[6] = me[6] * scaleY;
  2223. te[8] = me[8] * scaleZ;
  2224. te[9] = me[9] * scaleZ;
  2225. te[10] = me[10] * scaleZ;
  2226. return this;
  2227. },
  2228. //
  2229. translate: function ( v ) {
  2230. var te = this.elements;
  2231. var x = v.x, y = v.y, z = v.z;
  2232. te[12] = te[0] * x + te[4] * y + te[8] * z + te[12];
  2233. te[13] = te[1] * x + te[5] * y + te[9] * z + te[13];
  2234. te[14] = te[2] * x + te[6] * y + te[10] * z + te[14];
  2235. te[15] = te[3] * x + te[7] * y + te[11] * z + te[15];
  2236. return this;
  2237. },
  2238. rotateX: function ( angle ) {
  2239. var te = this.elements;
  2240. var m12 = te[4];
  2241. var m22 = te[5];
  2242. var m32 = te[6];
  2243. var m42 = te[7];
  2244. var m13 = te[8];
  2245. var m23 = te[9];
  2246. var m33 = te[10];
  2247. var m43 = te[11];
  2248. var c = Math.cos( angle );
  2249. var s = Math.sin( angle );
  2250. te[4] = c * m12 + s * m13;
  2251. te[5] = c * m22 + s * m23;
  2252. te[6] = c * m32 + s * m33;
  2253. te[7] = c * m42 + s * m43;
  2254. te[8] = c * m13 - s * m12;
  2255. te[9] = c * m23 - s * m22;
  2256. te[10] = c * m33 - s * m32;
  2257. te[11] = c * m43 - s * m42;
  2258. return this;
  2259. },
  2260. rotateY: function ( angle ) {
  2261. var te = this.elements;
  2262. var m11 = te[0];
  2263. var m21 = te[1];
  2264. var m31 = te[2];
  2265. var m41 = te[3];
  2266. var m13 = te[8];
  2267. var m23 = te[9];
  2268. var m33 = te[10];
  2269. var m43 = te[11];
  2270. var c = Math.cos( angle );
  2271. var s = Math.sin( angle );
  2272. te[0] = c * m11 - s * m13;
  2273. te[1] = c * m21 - s * m23;
  2274. te[2] = c * m31 - s * m33;
  2275. te[3] = c * m41 - s * m43;
  2276. te[8] = c * m13 + s * m11;
  2277. te[9] = c * m23 + s * m21;
  2278. te[10] = c * m33 + s * m31;
  2279. te[11] = c * m43 + s * m41;
  2280. return this;
  2281. },
  2282. rotateZ: function ( angle ) {
  2283. var te = this.elements;
  2284. var m11 = te[0];
  2285. var m21 = te[1];
  2286. var m31 = te[2];
  2287. var m41 = te[3];
  2288. var m12 = te[4];
  2289. var m22 = te[5];
  2290. var m32 = te[6];
  2291. var m42 = te[7];
  2292. var c = Math.cos( angle );
  2293. var s = Math.sin( angle );
  2294. te[0] = c * m11 + s * m12;
  2295. te[1] = c * m21 + s * m22;
  2296. te[2] = c * m31 + s * m32;
  2297. te[3] = c * m41 + s * m42;
  2298. te[4] = c * m12 - s * m11;
  2299. te[5] = c * m22 - s * m21;
  2300. te[6] = c * m32 - s * m31;
  2301. te[7] = c * m42 - s * m41;
  2302. return this;
  2303. },
  2304. rotateByAxis: function ( axis, angle ) {
  2305. var te = this.elements;
  2306. // optimize by checking axis
  2307. if ( axis.x === 1 && axis.y === 0 && axis.z === 0 ) {
  2308. return this.rotateX( angle );
  2309. } else if ( axis.x === 0 && axis.y === 1 && axis.z === 0 ) {
  2310. return this.rotateY( angle );
  2311. } else if ( axis.x === 0 && axis.y === 0 && axis.z === 1 ) {
  2312. return this.rotateZ( angle );
  2313. }
  2314. var x = axis.x, y = axis.y, z = axis.z;
  2315. var n = Math.sqrt(x * x + y * y + z * z);
  2316. x /= n;
  2317. y /= n;
  2318. z /= n;
  2319. var xx = x * x, yy = y * y, zz = z * z;
  2320. var c = Math.cos( angle );
  2321. var s = Math.sin( angle );
  2322. var oneMinusCosine = 1 - c;
  2323. var xy = x * y * oneMinusCosine;
  2324. var xz = x * z * oneMinusCosine;
  2325. var yz = y * z * oneMinusCosine;
  2326. var xs = x * s;
  2327. var ys = y * s;
  2328. var zs = z * s;
  2329. var r11 = xx + (1 - xx) * c;
  2330. var r21 = xy + zs;
  2331. var r31 = xz - ys;
  2332. var r12 = xy - zs;
  2333. var r22 = yy + (1 - yy) * c;
  2334. var r32 = yz + xs;
  2335. var r13 = xz + ys;
  2336. var r23 = yz - xs;
  2337. var r33 = zz + (1 - zz) * c;
  2338. var m11 = te[0], m21 = te[1], m31 = te[2], m41 = te[3];
  2339. var m12 = te[4], m22 = te[5], m32 = te[6], m42 = te[7];
  2340. var m13 = te[8], m23 = te[9], m33 = te[10], m43 = te[11];
  2341. var m14 = te[12], m24 = te[13], m34 = te[14], m44 = te[15];
  2342. te[0] = r11 * m11 + r21 * m12 + r31 * m13;
  2343. te[1] = r11 * m21 + r21 * m22 + r31 * m23;
  2344. te[2] = r11 * m31 + r21 * m32 + r31 * m33;
  2345. te[3] = r11 * m41 + r21 * m42 + r31 * m43;
  2346. te[4] = r12 * m11 + r22 * m12 + r32 * m13;
  2347. te[5] = r12 * m21 + r22 * m22 + r32 * m23;
  2348. te[6] = r12 * m31 + r22 * m32 + r32 * m33;
  2349. te[7] = r12 * m41 + r22 * m42 + r32 * m43;
  2350. te[8] = r13 * m11 + r23 * m12 + r33 * m13;
  2351. te[9] = r13 * m21 + r23 * m22 + r33 * m23;
  2352. te[10] = r13 * m31 + r23 * m32 + r33 * m33;
  2353. te[11] = r13 * m41 + r23 * m42 + r33 * m43;
  2354. return this;
  2355. },
  2356. scale: function ( v ) {
  2357. var te = this.elements;
  2358. var x = v.x, y = v.y, z = v.z;
  2359. te[0] *= x; te[4] *= y; te[8] *= z;
  2360. te[1] *= x; te[5] *= y; te[9] *= z;
  2361. te[2] *= x; te[6] *= y; te[10] *= z;
  2362. te[3] *= x; te[7] *= y; te[11] *= z;
  2363. return this;
  2364. },
  2365. getMaxScaleOnAxis: function () {
  2366. var te = this.elements;
  2367. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2368. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2369. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2370. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2371. },
  2372. //
  2373. makeTranslation: function ( offset ) {
  2374. this.set(
  2375. 1, 0, 0, offset.x,
  2376. 0, 1, 0, offset.y,
  2377. 0, 0, 1, offset.z,
  2378. 0, 0, 0, 1
  2379. );
  2380. return this;
  2381. },
  2382. makeRotationX: function ( theta ) {
  2383. var c = Math.cos( theta ), s = Math.sin( theta );
  2384. this.set(
  2385. 1, 0, 0, 0,
  2386. 0, c, -s, 0,
  2387. 0, s, c, 0,
  2388. 0, 0, 0, 1
  2389. );
  2390. return this;
  2391. },
  2392. makeRotationY: function ( theta ) {
  2393. var c = Math.cos( theta ), s = Math.sin( theta );
  2394. this.set(
  2395. c, 0, s, 0,
  2396. 0, 1, 0, 0,
  2397. -s, 0, c, 0,
  2398. 0, 0, 0, 1
  2399. );
  2400. return this;
  2401. },
  2402. makeRotationZ: function ( theta ) {
  2403. var c = Math.cos( theta ), s = Math.sin( theta );
  2404. this.set(
  2405. c, -s, 0, 0,
  2406. s, c, 0, 0,
  2407. 0, 0, 1, 0,
  2408. 0, 0, 0, 1
  2409. );
  2410. return this;
  2411. },
  2412. makeRotationAxis: function ( axis, angle ) {
  2413. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2414. var c = Math.cos( angle );
  2415. var s = Math.sin( angle );
  2416. var t = 1 - c;
  2417. var x = axis.x, y = axis.y, z = axis.z;
  2418. var tx = t * x, ty = t * y;
  2419. this.set(
  2420. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2421. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2422. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2423. 0, 0, 0, 1
  2424. );
  2425. return this;
  2426. },
  2427. makeScale: function ( factor ) {
  2428. this.set(
  2429. factor.x, 0, 0, 0,
  2430. 0, factor.y, 0, 0,
  2431. 0, 0, factor.z, 0,
  2432. 0, 0, 0, 1
  2433. );
  2434. return this;
  2435. },
  2436. makeFrustum: function ( left, right, bottom, top, near, far ) {
  2437. var te = this.elements;
  2438. var x = 2 * near / ( right - left );
  2439. var y = 2 * near / ( top - bottom );
  2440. var a = ( right + left ) / ( right - left );
  2441. var b = ( top + bottom ) / ( top - bottom );
  2442. var c = - ( far + near ) / ( far - near );
  2443. var d = - 2 * far * near / ( far - near );
  2444. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  2445. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  2446. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  2447. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  2448. return this;
  2449. },
  2450. makePerspective: function ( fov, aspect, near, far ) {
  2451. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  2452. var ymin = - ymax;
  2453. var xmin = ymin * aspect;
  2454. var xmax = ymax * aspect;
  2455. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  2456. },
  2457. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2458. var te = this.elements;
  2459. var w = right - left;
  2460. var h = top - bottom;
  2461. var p = far - near;
  2462. var x = ( right + left ) / w;
  2463. var y = ( top + bottom ) / h;
  2464. var z = ( far + near ) / p;
  2465. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  2466. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  2467. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  2468. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  2469. return this;
  2470. },
  2471. clone: function () {
  2472. var te = this.elements;
  2473. return new THREE.Matrix4(
  2474. te[0], te[4], te[8], te[12],
  2475. te[1], te[5], te[9], te[13],
  2476. te[2], te[6], te[10], te[14],
  2477. te[3], te[7], te[11], te[15]
  2478. );
  2479. }
  2480. };
  2481. THREE.Matrix4.__v1 = new THREE.Vector3();
  2482. THREE.Matrix4.__v2 = new THREE.Vector3();
  2483. THREE.Matrix4.__v3 = new THREE.Vector3();
  2484. THREE.Matrix4.__m1 = new THREE.Matrix4();
  2485. THREE.Matrix4.__m2 = new THREE.Matrix4();
  2486. /**
  2487. * @author bhouston / http://exocortex.com
  2488. */
  2489. THREE.Ray = function ( origin, direction ) {
  2490. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  2491. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  2492. };
  2493. THREE.Ray.prototype = {
  2494. constructor: THREE.Ray,
  2495. set: function ( origin, direction ) {
  2496. this.origin.copy( origin );
  2497. this.direction.copy( direction );
  2498. return this;
  2499. },
  2500. copy: function ( ray ) {
  2501. this.origin.copy( ray.origin );
  2502. this.direction.copy( ray.direction );
  2503. return this;
  2504. },
  2505. at: function( t, optionalTarget ) {
  2506. var result = optionalTarget || new THREE.Vector3();
  2507. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  2508. },
  2509. recast: function ( t ) {
  2510. this.origin.copy( this.at( t, THREE.Ray.__v1 ) );
  2511. return this;
  2512. },
  2513. closestPointToPoint: function ( point, optionalTarget ) {
  2514. var result = optionalTarget || new THREE.Vector3();
  2515. result.subVectors( point, this.origin );
  2516. var directionDistance = result.dot( this.direction );
  2517. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2518. },
  2519. distanceToPoint: function ( point ) {
  2520. var directionDistance = THREE.Ray.__v1.subVectors( point, this.origin ).dot( this.direction );
  2521. THREE.Ray.__v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2522. return THREE.Ray.__v1.distanceTo( point );
  2523. },
  2524. isIntersectionSphere: function( sphere ) {
  2525. return ( this.distanceToPoint( sphere.center ) <= sphere.radius );
  2526. },
  2527. isIntersectionPlane: function ( plane ) {
  2528. // check if the line and plane are non-perpendicular, if they
  2529. // eventually they will intersect.
  2530. var denominator = plane.normal.dot( this.direction );
  2531. if ( denominator != 0 ) {
  2532. return true;
  2533. }
  2534. // line is coplanar, return origin
  2535. if( plane.distanceToPoint( this.origin ) == 0 ) {
  2536. return true;
  2537. }
  2538. return false;
  2539. },
  2540. distanceToPlane: function ( plane ) {
  2541. var denominator = plane.normal.dot( this.direction );
  2542. if ( denominator == 0 ) {
  2543. // line is coplanar, return origin
  2544. if( plane.distanceToPoint( this.origin ) == 0 ) {
  2545. return 0;
  2546. }
  2547. // Unsure if this is the correct method to handle this case.
  2548. return undefined;
  2549. }
  2550. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  2551. return t;
  2552. },
  2553. intersectPlane: function ( plane, optionalTarget ) {
  2554. var t = this.distanceToPlane( plane );
  2555. if( t === undefined ) {
  2556. return undefined;
  2557. }
  2558. return this.at( t, optionalTarget );
  2559. },
  2560. transform: function ( matrix4 ) {
  2561. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  2562. this.origin.applyMatrix4( matrix4 );
  2563. this.direction.sub( this.origin );
  2564. return this;
  2565. },
  2566. equals: function ( ray ) {
  2567. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  2568. },
  2569. clone: function () {
  2570. return new THREE.Ray().copy( this );
  2571. }
  2572. };
  2573. THREE.Ray.__v1 = new THREE.Vector3();
  2574. THREE.Ray.__v2 = new THREE.Vector3();
  2575. /**
  2576. * @author bhouston / http://exocortex.com
  2577. * @author mrdoob / http://mrdoob.com/
  2578. */
  2579. THREE.Sphere = function ( center, radius ) {
  2580. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  2581. this.radius = ( radius !== undefined ) ? radius : 0;
  2582. };
  2583. THREE.Sphere.prototype = {
  2584. constructor: THREE.Sphere,
  2585. set: function ( center, radius ) {
  2586. this.center.copy( center );
  2587. this.radius = radius;
  2588. return this;
  2589. },
  2590. setFromCenterAndPoints: function ( center, points ) {
  2591. var maxRadiusSq = 0;
  2592. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2593. var radiusSq = center.distanceToSquared( points[ i ] );
  2594. maxRadiusSq = Math.max( maxRadiusSq, radiusSq );
  2595. }
  2596. this.center = center;
  2597. this.radius = Math.sqrt( maxRadiusSq );
  2598. return this;
  2599. },
  2600. copy: function ( sphere ) {
  2601. this.center.copy( sphere.center );
  2602. this.radius = sphere.radius;
  2603. return this;
  2604. },
  2605. empty: function () {
  2606. return ( this.radius <= 0 );
  2607. },
  2608. containsPoint: function ( point ) {
  2609. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  2610. },
  2611. distanceToPoint: function ( point ) {
  2612. return ( point.distanceTo( this.center ) - this.radius );
  2613. },
  2614. intersectsSphere: function ( sphere ) {
  2615. var radiusSum = this.radius + sphere.radius;
  2616. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  2617. },
  2618. clampPoint: function ( point, optionalTarget ) {
  2619. var deltaLengthSq = this.center.distanceToSquared( point );
  2620. var result = optionalTarget || new THREE.Vector3();
  2621. result.copy( point );
  2622. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  2623. result.sub( this.center ).normalize();
  2624. result.multiplyScalar( this.radius ).add( this.center );
  2625. }
  2626. return result;
  2627. },
  2628. getBoundingBox: function ( optionalTarget ) {
  2629. var box = optionalTarget || new THREE.Box3();
  2630. box.set( this.center, this.center );
  2631. box.expandByScalar( this.radius );
  2632. return box;
  2633. },
  2634. transform: function ( matrix ) {
  2635. this.center.applyMatrix4( matrix );
  2636. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  2637. return this;
  2638. },
  2639. translate: function ( offset ) {
  2640. this.center.add( offset );
  2641. return this;
  2642. },
  2643. equals: function ( sphere ) {
  2644. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  2645. },
  2646. clone: function () {
  2647. return new THREE.Sphere().copy( this );
  2648. }
  2649. };
  2650. /**
  2651. * @author mrdoob / http://mrdoob.com/
  2652. * @author alteredq / http://alteredqualia.com/
  2653. * @author bhouston / http://exocortex.com
  2654. */
  2655. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  2656. this.planes = [
  2657. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  2658. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  2659. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  2660. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  2661. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  2662. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  2663. ];
  2664. };
  2665. THREE.Frustum.prototype = {
  2666. set: function ( p0, p1, p2, p3, p4, p5 ) {
  2667. var planes = this.planes;
  2668. planes[0].copy( p0 );
  2669. planes[1].copy( p1 );
  2670. planes[2].copy( p2 );
  2671. planes[3].copy( p3 );
  2672. planes[4].copy( p4 );
  2673. planes[5].copy( p5 );
  2674. return this;
  2675. },
  2676. copy: function ( frustum ) {
  2677. var planes = this.planes;
  2678. for( var i = 0; i < 6; i ++ ) {
  2679. planes[i].copy( frustum.planes[i] );
  2680. }
  2681. return this;
  2682. },
  2683. setFromMatrix: function ( m ) {
  2684. var planes = this.planes;
  2685. var me = m.elements;
  2686. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  2687. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  2688. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  2689. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  2690. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  2691. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  2692. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  2693. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  2694. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  2695. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  2696. return this;
  2697. },
  2698. intersectsObject: function ( object ) {
  2699. // this method is expanded inlined for performance reasons.
  2700. var matrix = object.matrixWorld;
  2701. var planes = this.planes;
  2702. var center = matrix.getPosition();
  2703. var negRadius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  2704. for ( var i = 0; i < 6; i ++ ) {
  2705. var distance = planes[ i ].distanceToPoint( center );
  2706. if( distance < negRadius ) {
  2707. return false;
  2708. }
  2709. }
  2710. return true;
  2711. },
  2712. intersectsSphere: function ( sphere ) {
  2713. var planes = this.planes;
  2714. var center = sphere.center;
  2715. var negRadius = -sphere.radius;
  2716. for ( var i = 0; i < 6; i ++ ) {
  2717. var distance = planes[ i ].distanceToPoint( center );
  2718. if( distance < negRadius ) {
  2719. return false;
  2720. }
  2721. }
  2722. return true;
  2723. },
  2724. containsPoint: function ( point ) {
  2725. var planes = this.planes;
  2726. for ( var i = 0; i < 6; i ++ ) {
  2727. if( planes[ i ].distanceToPoint( point ) < 0 ) {
  2728. return false;
  2729. }
  2730. }
  2731. return true;
  2732. },
  2733. clone: function () {
  2734. return new THREE.Frustum().copy( this );
  2735. }
  2736. };
  2737. /**
  2738. * @author bhouston / http://exocortex.com
  2739. */
  2740. THREE.Plane = function ( normal, constant ) {
  2741. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  2742. this.constant = ( constant !== undefined ) ? constant : 0;
  2743. };
  2744. THREE.Plane.prototype = {
  2745. constructor: THREE.Plane,
  2746. set: function ( normal, constant ) {
  2747. this.normal.copy( normal );
  2748. this.constant = constant;
  2749. return this;
  2750. },
  2751. setComponents: function ( x, y, z, w ) {
  2752. this.normal.set( x, y, z );
  2753. this.constant = w;
  2754. return this;
  2755. },
  2756. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  2757. this.normal.copy( normal ).normalize();
  2758. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  2759. return this;
  2760. },
  2761. setFromCoplanarPoints: function ( a, b, c ) {
  2762. var normal = THREE.Plane.__v1.subVectors( c, b ).cross( THREE.Plane.__v2.subVectors( a, b ) ).normalize();
  2763. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  2764. this.setFromNormalAndCoplanarPoint( normal, a );
  2765. return this;
  2766. },
  2767. copy: function ( plane ) {
  2768. this.normal.copy( plane.normal );
  2769. this.constant = plane.constant;
  2770. return this;
  2771. },
  2772. normalize: function () {
  2773. // Note: will lead to a divide by zero if the plane is invalid.
  2774. var inverseNormalLength = 1.0 / this.normal.length();
  2775. this.normal.multiplyScalar( inverseNormalLength );
  2776. this.constant *= inverseNormalLength;
  2777. return this;
  2778. },
  2779. negate: function () {
  2780. this.constant *= -1;
  2781. this.normal.negate();
  2782. return this;
  2783. },
  2784. distanceToPoint: function ( point ) {
  2785. return this.normal.dot( point ) + this.constant;
  2786. },
  2787. distanceToSphere: function ( sphere ) {
  2788. return this.distanceToPoint( sphere.center ) - sphere.radius;
  2789. },
  2790. projectPoint: function ( point, optionalTarget ) {
  2791. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  2792. },
  2793. orthoPoint: function ( point, optionalTarget ) {
  2794. var perpendicularMagnitude = this.distanceToPoint( point );
  2795. var result = optionalTarget || new THREE.Vector3();
  2796. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  2797. },
  2798. isIntersectionLine: function ( startPoint, endPoint ) {
  2799. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  2800. var startSign = this.distanceToPoint( startPoint );
  2801. var endSign = this.distanceToPoint( endPoint );
  2802. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  2803. },
  2804. intersectLine: function ( startPoint, endPoint, optionalTarget ) {
  2805. var result = optionalTarget || new THREE.Vector3();
  2806. var direction = THREE.Plane.__v1.subVectors( endPoint, startPoint );
  2807. var denominator = this.normal.dot( direction );
  2808. if ( denominator == 0 ) {
  2809. // line is coplanar, return origin
  2810. if( this.distanceToPoint( startPoint ) == 0 ) {
  2811. return result.copy( startPoint );
  2812. }
  2813. // Unsure if this is the correct method to handle this case.
  2814. return undefined;
  2815. }
  2816. var t = - ( startPoint.dot( this.normal ) + this.constant ) / denominator;
  2817. if( t < 0 || t > 1 ) {
  2818. return undefined;
  2819. }
  2820. return result.copy( direction ).multiplyScalar( t ).add( startPoint );
  2821. },
  2822. coplanarPoint: function ( optionalTarget ) {
  2823. var result = optionalTarget || new THREE.Vector3();
  2824. return result.copy( this.normal ).multiplyScalar( - this.constant );
  2825. },
  2826. transform: function ( matrix, optionalNormalMatrix ) {
  2827. // compute new normal based on theory here:
  2828. // http://www.songho.ca/opengl/gl_normaltransform.html
  2829. optionalNormalMatrix = optionalNormalMatrix || new THREE.Matrix3().getInverse( matrix ).transpose();
  2830. var newNormal = THREE.Plane.__v1.copy( this.normal ).applyMatrix3( optionalNormalMatrix );
  2831. var newCoplanarPoint = this.coplanarPoint( THREE.Plane.__v2 );
  2832. newCoplanarPoint.applyMatrix4( matrix );
  2833. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  2834. return this;
  2835. },
  2836. translate: function ( offset ) {
  2837. this.constant = this.constant - offset.dot( this.normal );
  2838. return this;
  2839. },
  2840. equals: function ( plane ) {
  2841. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  2842. },
  2843. clone: function () {
  2844. return new THREE.Plane().copy( this );
  2845. }
  2846. };
  2847. THREE.Plane.__vZero = new THREE.Vector3( 0, 0, 0 );
  2848. THREE.Plane.__v1 = new THREE.Vector3();
  2849. THREE.Plane.__v2 = new THREE.Vector3();
  2850. /**
  2851. * @author alteredq / http://alteredqualia.com/
  2852. */
  2853. THREE.Math = {
  2854. // Clamp value to range <a, b>
  2855. clamp: function ( x, a, b ) {
  2856. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  2857. },
  2858. // Clamp value to range <a, inf)
  2859. clampBottom: function ( x, a ) {
  2860. return x < a ? a : x;
  2861. },
  2862. // Linear mapping from range <a1, a2> to range <b1, b2>
  2863. mapLinear: function ( x, a1, a2, b1, b2 ) {
  2864. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  2865. },
  2866. // Random float from <0, 1> with 16 bits of randomness
  2867. // (standard Math.random() creates repetitive patterns when applied over larger space)
  2868. random16: function () {
  2869. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  2870. },
  2871. // Random integer from <low, high> interval
  2872. randInt: function ( low, high ) {
  2873. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  2874. },
  2875. // Random float from <low, high> interval
  2876. randFloat: function ( low, high ) {
  2877. return low + Math.random() * ( high - low );
  2878. },
  2879. // Random float from <-range/2, range/2> interval
  2880. randFloatSpread: function ( range ) {
  2881. return range * ( 0.5 - Math.random() );
  2882. },
  2883. sign: function ( x ) {
  2884. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  2885. },
  2886. degToRad: function ( degrees ) {
  2887. return degrees * THREE.Math.__d2r;
  2888. },
  2889. radToDeg: function ( radians ) {
  2890. return radians * THREE.Math.__r2d;
  2891. }
  2892. };
  2893. THREE.Math.__d2r = Math.PI / 180;
  2894. THREE.Math.__r2d = 180 / Math.PI;
  2895. /**
  2896. * @author mikael emtinger / http://gomo.se/
  2897. * @author alteredq / http://alteredqualia.com/
  2898. * @author WestLangley / http://github.com/WestLangley
  2899. * @author bhouston / http://exocortex.com
  2900. */
  2901. THREE.Quaternion = function( x, y, z, w ) {
  2902. this.x = x || 0;
  2903. this.y = y || 0;
  2904. this.z = z || 0;
  2905. this.w = ( w !== undefined ) ? w : 1;
  2906. };
  2907. THREE.Quaternion.prototype = {
  2908. constructor: THREE.Quaternion,
  2909. set: function ( x, y, z, w ) {
  2910. this.x = x;
  2911. this.y = y;
  2912. this.z = z;
  2913. this.w = w;
  2914. return this;
  2915. },
  2916. copy: function ( q ) {
  2917. this.x = q.x;
  2918. this.y = q.y;
  2919. this.z = q.z;
  2920. this.w = q.w;
  2921. return this;
  2922. },
  2923. setFromEuler: function ( v, order ) {
  2924. // http://www.mathworks.com/matlabcentral/fileexchange/
  2925. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2926. // content/SpinCalc.m
  2927. var c1 = Math.cos( v.x / 2 );
  2928. var c2 = Math.cos( v.y / 2 );
  2929. var c3 = Math.cos( v.z / 2 );
  2930. var s1 = Math.sin( v.x / 2 );
  2931. var s2 = Math.sin( v.y / 2 );
  2932. var s3 = Math.sin( v.z / 2 );
  2933. if ( order === undefined || order === 'XYZ' ) {
  2934. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2935. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2936. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2937. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2938. } else if ( order === 'YXZ' ) {
  2939. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2940. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2941. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2942. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2943. } else if ( order === 'ZXY' ) {
  2944. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2945. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2946. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2947. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2948. } else if ( order === 'ZYX' ) {
  2949. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2950. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2951. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2952. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2953. } else if ( order === 'YZX' ) {
  2954. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2955. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2956. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2957. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2958. } else if ( order === 'XZY' ) {
  2959. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2960. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2961. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2962. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2963. }
  2964. return this;
  2965. },
  2966. setFromAxisAngle: function ( axis, angle ) {
  2967. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2968. // axis have to be normalized
  2969. var halfAngle = angle / 2,
  2970. s = Math.sin( halfAngle );
  2971. this.x = axis.x * s;
  2972. this.y = axis.y * s;
  2973. this.z = axis.z * s;
  2974. this.w = Math.cos( halfAngle );
  2975. return this;
  2976. },
  2977. setFromRotationMatrix: function ( m ) {
  2978. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2979. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2980. var te = m.elements,
  2981. m11 = te[0], m12 = te[4], m13 = te[8],
  2982. m21 = te[1], m22 = te[5], m23 = te[9],
  2983. m31 = te[2], m32 = te[6], m33 = te[10],
  2984. trace = m11 + m22 + m33,
  2985. s;
  2986. if ( trace > 0 ) {
  2987. s = 0.5 / Math.sqrt( trace + 1.0 );
  2988. this.w = 0.25 / s;
  2989. this.x = ( m32 - m23 ) * s;
  2990. this.y = ( m13 - m31 ) * s;
  2991. this.z = ( m21 - m12 ) * s;
  2992. } else if ( m11 > m22 && m11 > m33 ) {
  2993. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2994. this.w = (m32 - m23 ) / s;
  2995. this.x = 0.25 * s;
  2996. this.y = (m12 + m21 ) / s;
  2997. this.z = (m13 + m31 ) / s;
  2998. } else if ( m22 > m33 ) {
  2999. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  3000. this.w = (m13 - m31 ) / s;
  3001. this.x = (m12 + m21 ) / s;
  3002. this.y = 0.25 * s;
  3003. this.z = (m23 + m32 ) / s;
  3004. } else {
  3005. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  3006. this.w = ( m21 - m12 ) / s;
  3007. this.x = ( m13 + m31 ) / s;
  3008. this.y = ( m23 + m32 ) / s;
  3009. this.z = 0.25 * s;
  3010. }
  3011. return this;
  3012. },
  3013. inverse: function () {
  3014. this.conjugate().normalize();
  3015. return this;
  3016. },
  3017. conjugate: function () {
  3018. this.x *= -1;
  3019. this.y *= -1;
  3020. this.z *= -1;
  3021. return this;
  3022. },
  3023. lengthSq: function () {
  3024. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  3025. },
  3026. length: function () {
  3027. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  3028. },
  3029. normalize: function () {
  3030. var l = this.length();
  3031. if ( l === 0 ) {
  3032. this.x = 0;
  3033. this.y = 0;
  3034. this.z = 0;
  3035. this.w = 1;
  3036. } else {
  3037. l = 1 / l;
  3038. this.x = this.x * l;
  3039. this.y = this.y * l;
  3040. this.z = this.z * l;
  3041. this.w = this.w * l;
  3042. }
  3043. return this;
  3044. },
  3045. multiply: function ( q, p ) {
  3046. if ( p !== undefined ) {
  3047. console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  3048. return this.multiplyQuaternions( q, p );
  3049. }
  3050. return this.multiplyQuaternions( this, q );
  3051. },
  3052. multiplyQuaternions: function ( a, b ) {
  3053. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  3054. var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w;
  3055. var qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  3056. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  3057. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  3058. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  3059. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  3060. return this;
  3061. },
  3062. multiplyVector3: function ( vector ) {
  3063. console.warn( 'DEPRECATED: Quaternion\'s .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  3064. return vector.applyQuaternion( this );
  3065. },
  3066. slerp: function ( qb, t ) {
  3067. var x = this.x, y = this.y, z = this.z, w = this.w;
  3068. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  3069. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  3070. if ( cosHalfTheta < 0 ) {
  3071. this.w = -qb.w;
  3072. this.x = -qb.x;
  3073. this.y = -qb.y;
  3074. this.z = -qb.z;
  3075. cosHalfTheta = -cosHalfTheta;
  3076. } else {
  3077. this.copy( qb );
  3078. }
  3079. if ( cosHalfTheta >= 1.0 ) {
  3080. this.w = w;
  3081. this.x = x;
  3082. this.y = y;
  3083. this.z = z;
  3084. return this;
  3085. }
  3086. var halfTheta = Math.acos( cosHalfTheta );
  3087. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  3088. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  3089. this.w = 0.5 * ( w + this.w );
  3090. this.x = 0.5 * ( x + this.x );
  3091. this.y = 0.5 * ( y + this.y );
  3092. this.z = 0.5 * ( z + this.z );
  3093. return this;
  3094. }
  3095. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  3096. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  3097. this.w = ( w * ratioA + this.w * ratioB );
  3098. this.x = ( x * ratioA + this.x * ratioB );
  3099. this.y = ( y * ratioA + this.y * ratioB );
  3100. this.z = ( z * ratioA + this.z * ratioB );
  3101. return this;
  3102. },
  3103. equals: function ( v ) {
  3104. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  3105. },
  3106. clone: function () {
  3107. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  3108. }
  3109. }
  3110. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  3111. return qm.copy( qa ).slerp( qb, t );
  3112. }
  3113. /**
  3114. * Spline from Tween.js, slightly optimized (and trashed)
  3115. * http://sole.github.com/tween.js/examples/05_spline.html
  3116. *
  3117. * @author mrdoob / http://mrdoob.com/
  3118. * @author alteredq / http://alteredqualia.com/
  3119. */
  3120. THREE.Spline = function ( points ) {
  3121. this.points = points;
  3122. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3123. point, intPoint, weight, w2, w3,
  3124. pa, pb, pc, pd;
  3125. this.initFromArray = function( a ) {
  3126. this.points = [];
  3127. for ( var i = 0; i < a.length; i++ ) {
  3128. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3129. }
  3130. };
  3131. this.getPoint = function ( k ) {
  3132. point = ( this.points.length - 1 ) * k;
  3133. intPoint = Math.floor( point );
  3134. weight = point - intPoint;
  3135. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3136. c[ 1 ] = intPoint;
  3137. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3138. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3139. pa = this.points[ c[ 0 ] ];
  3140. pb = this.points[ c[ 1 ] ];
  3141. pc = this.points[ c[ 2 ] ];
  3142. pd = this.points[ c[ 3 ] ];
  3143. w2 = weight * weight;
  3144. w3 = weight * w2;
  3145. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3146. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3147. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3148. return v3;
  3149. };
  3150. this.getControlPointsArray = function () {
  3151. var i, p, l = this.points.length,
  3152. coords = [];
  3153. for ( i = 0; i < l; i ++ ) {
  3154. p = this.points[ i ];
  3155. coords[ i ] = [ p.x, p.y, p.z ];
  3156. }
  3157. return coords;
  3158. };
  3159. // approximate length by summing linear segments
  3160. this.getLength = function ( nSubDivisions ) {
  3161. var i, index, nSamples, position,
  3162. point = 0, intPoint = 0, oldIntPoint = 0,
  3163. oldPosition = new THREE.Vector3(),
  3164. tmpVec = new THREE.Vector3(),
  3165. chunkLengths = [],
  3166. totalLength = 0;
  3167. // first point has 0 length
  3168. chunkLengths[ 0 ] = 0;
  3169. if ( !nSubDivisions ) nSubDivisions = 100;
  3170. nSamples = this.points.length * nSubDivisions;
  3171. oldPosition.copy( this.points[ 0 ] );
  3172. for ( i = 1; i < nSamples; i ++ ) {
  3173. index = i / nSamples;
  3174. position = this.getPoint( index );
  3175. tmpVec.copy( position );
  3176. totalLength += tmpVec.distanceTo( oldPosition );
  3177. oldPosition.copy( position );
  3178. point = ( this.points.length - 1 ) * index;
  3179. intPoint = Math.floor( point );
  3180. if ( intPoint != oldIntPoint ) {
  3181. chunkLengths[ intPoint ] = totalLength;
  3182. oldIntPoint = intPoint;
  3183. }
  3184. }
  3185. // last point ends with total length
  3186. chunkLengths[ chunkLengths.length ] = totalLength;
  3187. return { chunks: chunkLengths, total: totalLength };
  3188. };
  3189. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3190. var i, j,
  3191. index, indexCurrent, indexNext,
  3192. linearDistance, realDistance,
  3193. sampling, position,
  3194. newpoints = [],
  3195. tmpVec = new THREE.Vector3(),
  3196. sl = this.getLength();
  3197. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3198. for ( i = 1; i < this.points.length; i++ ) {
  3199. //tmpVec.copy( this.points[ i - 1 ] );
  3200. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3201. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3202. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3203. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3204. indexNext = i / ( this.points.length - 1 );
  3205. for ( j = 1; j < sampling - 1; j++ ) {
  3206. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3207. position = this.getPoint( index );
  3208. newpoints.push( tmpVec.copy( position ).clone() );
  3209. }
  3210. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3211. }
  3212. this.points = newpoints;
  3213. };
  3214. // Catmull-Rom
  3215. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3216. var v0 = ( p2 - p0 ) * 0.5,
  3217. v1 = ( p3 - p1 ) * 0.5;
  3218. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3219. };
  3220. };
  3221. /**
  3222. * @author bhouston / http://exocortex.com
  3223. * @author mrdoob / http://mrdoob.com/
  3224. */
  3225. THREE.Triangle = function ( a, b, c ) {
  3226. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3227. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3228. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3229. };
  3230. THREE.Triangle.normal = function( a, b, c, optionalTarget ) {
  3231. var result = optionalTarget || new THREE.Vector3();
  3232. result.subVectors( c, b );
  3233. THREE.Triangle.__v0.subVectors( a, b );
  3234. result.cross( THREE.Triangle.__v0 );
  3235. var resultLengthSq = result.lengthSq();
  3236. if( resultLengthSq > 0 ) {
  3237. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3238. }
  3239. return result.set( 0, 0, 0 );
  3240. };
  3241. // static/instance method to calculate barycoordinates
  3242. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3243. THREE.Triangle.barycoordFromPoint = function ( point, a, b, c, optionalTarget ) {
  3244. THREE.Triangle.__v0.subVectors( c, a );
  3245. THREE.Triangle.__v1.subVectors( b, a );
  3246. THREE.Triangle.__v2.subVectors( point, a );
  3247. var dot00 = THREE.Triangle.__v0.dot( THREE.Triangle.__v0 );
  3248. var dot01 = THREE.Triangle.__v0.dot( THREE.Triangle.__v1 );
  3249. var dot02 = THREE.Triangle.__v0.dot( THREE.Triangle.__v2 );
  3250. var dot11 = THREE.Triangle.__v1.dot( THREE.Triangle.__v1 );
  3251. var dot12 = THREE.Triangle.__v1.dot( THREE.Triangle.__v2 );
  3252. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3253. var result = optionalTarget || new THREE.Vector3();
  3254. // colinear or singular triangle
  3255. if( denom == 0 ) {
  3256. // arbitrary location outside of triangle?
  3257. // not sure if this is the best idea, maybe should be returning undefined
  3258. return result.set( -2, -1, -1 );
  3259. }
  3260. var invDenom = 1 / denom;
  3261. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3262. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3263. // barycoordinates must always sum to 1
  3264. return result.set( 1 - u - v, v, u );
  3265. };
  3266. THREE.Triangle.containsPoint = function ( point, a, b, c ) {
  3267. // NOTE: need to use __v3 here because __v0, __v1 and __v2 are used in barycoordFromPoint.
  3268. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, THREE.Triangle.__v3 );
  3269. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3270. };
  3271. THREE.Triangle.prototype = {
  3272. constructor: THREE.Triangle,
  3273. set: function ( a, b, c ) {
  3274. this.a.copy( a );
  3275. this.b.copy( b );
  3276. this.c.copy( c );
  3277. return this;
  3278. },
  3279. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3280. this.a.copy( points[i0] );
  3281. this.b.copy( points[i1] );
  3282. this.c.copy( points[i2] );
  3283. return this;
  3284. },
  3285. copy: function ( triangle ) {
  3286. this.a.copy( triangle.a );
  3287. this.b.copy( triangle.b );
  3288. this.c.copy( triangle.c );
  3289. return this;
  3290. },
  3291. area: function () {
  3292. THREE.Triangle.__v0.subVectors( this.c, this.b );
  3293. THREE.Triangle.__v1.subVectors( this.a, this.b );
  3294. return THREE.Triangle.__v0.cross( THREE.Triangle.__v1 ).length() * 0.5;
  3295. },
  3296. midpoint: function ( optionalTarget ) {
  3297. var result = optionalTarget || new THREE.Vector3();
  3298. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  3299. },
  3300. normal: function ( optionalTarget ) {
  3301. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3302. },
  3303. plane: function ( optionalTarget ) {
  3304. var result = optionalTarget || new THREE.Plane();
  3305. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  3306. },
  3307. barycoordFromPoint: function ( point, optionalTarget ) {
  3308. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  3309. },
  3310. containsPoint: function ( point ) {
  3311. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  3312. },
  3313. equals: function ( triangle ) {
  3314. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  3315. },
  3316. clone: function () {
  3317. return new THREE.Triangle().copy( this );
  3318. }
  3319. };
  3320. THREE.Triangle.__v0 = new THREE.Vector3();
  3321. THREE.Triangle.__v1 = new THREE.Vector3();
  3322. THREE.Triangle.__v2 = new THREE.Vector3();
  3323. THREE.Triangle.__v3 = new THREE.Vector3();
  3324. /**
  3325. * @author mrdoob / http://mrdoob.com/
  3326. */
  3327. THREE.Vertex = function ( v ) {
  3328. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  3329. return v;
  3330. };
  3331. /**
  3332. * @author mrdoob / http://mrdoob.com/
  3333. */
  3334. THREE.UV = function ( u, v ) {
  3335. console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
  3336. return new THREE.Vector2( u, v );
  3337. };
  3338. /**
  3339. * @author alteredq / http://alteredqualia.com/
  3340. */
  3341. THREE.Clock = function ( autoStart ) {
  3342. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  3343. this.startTime = 0;
  3344. this.oldTime = 0;
  3345. this.elapsedTime = 0;
  3346. this.running = false;
  3347. };
  3348. THREE.Clock.prototype.start = function () {
  3349. this.startTime = Date.now();
  3350. this.oldTime = this.startTime;
  3351. this.running = true;
  3352. };
  3353. THREE.Clock.prototype.stop = function () {
  3354. this.getElapsedTime();
  3355. this.running = false;
  3356. };
  3357. THREE.Clock.prototype.getElapsedTime = function () {
  3358. this.getDelta();
  3359. return this.elapsedTime;
  3360. };
  3361. THREE.Clock.prototype.getDelta = function () {
  3362. var diff = 0;
  3363. if ( this.autoStart && ! this.running ) {
  3364. this.start();
  3365. }
  3366. if ( this.running ) {
  3367. var newTime = Date.now();
  3368. diff = 0.001 * ( newTime - this.oldTime );
  3369. this.oldTime = newTime;
  3370. this.elapsedTime += diff;
  3371. }
  3372. return diff;
  3373. };/**
  3374. * https://github.com/mrdoob/eventdispatcher.js/
  3375. */
  3376. THREE.EventDispatcher = function () {
  3377. var listeners = {};
  3378. this.addEventListener = function ( type, listener ) {
  3379. if ( listeners[ type ] === undefined ) {
  3380. listeners[ type ] = [];
  3381. }
  3382. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  3383. listeners[ type ].push( listener );
  3384. }
  3385. };
  3386. this.removeEventListener = function ( type, listener ) {
  3387. var index = listeners[ type ].indexOf( listener );
  3388. if ( index !== - 1 ) {
  3389. listeners[ type ].splice( index, 1 );
  3390. }
  3391. };
  3392. this.dispatchEvent = function ( event ) {
  3393. var listenerArray = listeners[ event.type ];
  3394. if ( listenerArray !== undefined ) {
  3395. event.target = this;
  3396. for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
  3397. listenerArray[ i ].call( this, event );
  3398. }
  3399. }
  3400. };
  3401. };
  3402. /**
  3403. * @author mrdoob / http://mrdoob.com/
  3404. * @author bhouston / http://exocortex.com/
  3405. */
  3406. ( function ( THREE ) {
  3407. THREE.Raycaster = function ( origin, direction, near, far ) {
  3408. this.ray = new THREE.Ray( origin, direction );
  3409. // normalized ray.direction required for accurate distance calculations
  3410. if( this.ray.direction.length() > 0 ) {
  3411. this.ray.direction.normalize();
  3412. }
  3413. this.near = near || 0;
  3414. this.far = far || Infinity;
  3415. };
  3416. var sphere = new THREE.Sphere();
  3417. var localRay = new THREE.Ray();
  3418. var facePlane = new THREE.Plane();
  3419. var intersectPoint = new THREE.Vector3();
  3420. var inverseMatrix = new THREE.Matrix4();
  3421. var descSort = function ( a, b ) {
  3422. return a.distance - b.distance;
  3423. };
  3424. var intersectObject = function ( object, raycaster, intersects ) {
  3425. if ( object instanceof THREE.Particle ) {
  3426. var distance = raycaster.ray.distanceToPoint( object.matrixWorld.getPosition() );
  3427. if ( distance > object.scale.x ) {
  3428. return intersects;
  3429. }
  3430. intersects.push( {
  3431. distance: distance,
  3432. point: object.position,
  3433. face: null,
  3434. object: object
  3435. } );
  3436. } else if ( object instanceof THREE.Mesh ) {
  3437. // Checking boundingSphere distance to ray
  3438. sphere.set(
  3439. object.matrixWorld.getPosition(),
  3440. object.geometry.boundingSphere.radius* object.matrixWorld.getMaxScaleOnAxis() );
  3441. if ( ! raycaster.ray.isIntersectionSphere( sphere ) ) {
  3442. return intersects;
  3443. }
  3444. // Checking faces
  3445. var geometry = object.geometry;
  3446. var vertices = geometry.vertices;
  3447. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3448. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  3449. var side = object.material.side;
  3450. var a, b, c, d;
  3451. var precision = raycaster.precision;
  3452. object.matrixRotationWorld.extractRotation( object.matrixWorld );
  3453. inverseMatrix.getInverse( object.matrixWorld );
  3454. localRay.copy( raycaster.ray ).transform( inverseMatrix );
  3455. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  3456. var face = geometry.faces[ f ];
  3457. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  3458. if ( material === undefined ) continue;
  3459. facePlane.setFromNormalAndCoplanarPoint( face.normal, vertices[face.a] );
  3460. var planeDistance = localRay.distanceToPlane( facePlane );
  3461. // bail if raycaster and plane are parallel
  3462. if ( Math.abs( planeDistance ) < precision ) continue;
  3463. // if negative distance, then plane is behind raycaster
  3464. if ( planeDistance < 0 ) continue;
  3465. // check if we hit the wrong side of a single sided face
  3466. side = material.side;
  3467. if( side !== THREE.DoubleSide ) {
  3468. var planeSign = localRay.direction.dot( facePlane.normal );
  3469. if( ! ( side === THREE.FrontSide ? planeSign < 0 : planeSign > 0 ) ) continue;
  3470. }
  3471. // this can be done using the planeDistance from localRay because localRay wasn't normalized, but ray was
  3472. if ( planeDistance < raycaster.near || planeDistance > raycaster.far ) continue;
  3473. intersectPoint = localRay.at( planeDistance, intersectPoint ); // passing in intersectPoint avoids a copy
  3474. if ( face instanceof THREE.Face3 ) {
  3475. a = vertices[ face.a ];
  3476. b = vertices[ face.b ];
  3477. c = vertices[ face.c ];
  3478. if ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, c ) ) continue;
  3479. } else if ( face instanceof THREE.Face4 ) {
  3480. a = vertices[ face.a ];
  3481. b = vertices[ face.b ];
  3482. c = vertices[ face.c ];
  3483. d = vertices[ face.d ];
  3484. if ( ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, d ) ) &&
  3485. ( ! THREE.Triangle.containsPoint( intersectPoint, b, c, d ) ) ) continue;
  3486. } else {
  3487. // This is added because if we call out of this if/else group when none of the cases
  3488. // match it will add a point to the intersection list erroneously.
  3489. throw Error( "face type not supported" );
  3490. }
  3491. intersects.push( {
  3492. distance: planeDistance, // this works because the original ray was normalized, and the transformed localRay wasn't
  3493. point: raycaster.ray.at( planeDistance ),
  3494. face: face,
  3495. faceIndex: f,
  3496. object: object
  3497. } );
  3498. }
  3499. }
  3500. };
  3501. var intersectDescendants = function ( object, raycaster, intersects ) {
  3502. var descendants = object.getDescendants();
  3503. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  3504. intersectObject( descendants[ i ], raycaster, intersects );
  3505. }
  3506. };
  3507. //
  3508. THREE.Raycaster.prototype.precision = 0.0001;
  3509. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  3510. this.ray.set( origin, direction );
  3511. // normalized ray.direction required for accurate distance calculations
  3512. if( this.ray.direction.length() > 0 ) {
  3513. this.ray.direction.normalize();
  3514. }
  3515. };
  3516. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  3517. var intersects = [];
  3518. if ( recursive === true ) {
  3519. intersectDescendants( object, this, intersects );
  3520. }
  3521. intersectObject( object, this, intersects );
  3522. intersects.sort( descSort );
  3523. return intersects;
  3524. };
  3525. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  3526. var intersects = [];
  3527. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  3528. intersectObject( objects[ i ], this, intersects );
  3529. if ( recursive === true ) {
  3530. intersectDescendants( objects[ i ], this, intersects );
  3531. }
  3532. }
  3533. intersects.sort( descSort );
  3534. return intersects;
  3535. };
  3536. }( THREE ) );
  3537. /**
  3538. * @author mrdoob / http://mrdoob.com/
  3539. * @author mikael emtinger / http://gomo.se/
  3540. * @author alteredq / http://alteredqualia.com/
  3541. */
  3542. THREE.Object3D = function () {
  3543. this.id = THREE.Object3DIdCount ++;
  3544. this.name = '';
  3545. this.properties = {};
  3546. this.parent = undefined;
  3547. this.children = [];
  3548. this.up = new THREE.Vector3( 0, 1, 0 );
  3549. this.position = new THREE.Vector3();
  3550. this.rotation = new THREE.Vector3();
  3551. this.eulerOrder = THREE.Object3D.defaultEulerOrder;
  3552. this.scale = new THREE.Vector3( 1, 1, 1 );
  3553. this.renderDepth = null;
  3554. this.rotationAutoUpdate = true;
  3555. this.matrix = new THREE.Matrix4();
  3556. this.matrixWorld = new THREE.Matrix4();
  3557. this.matrixRotationWorld = new THREE.Matrix4();
  3558. this.matrixAutoUpdate = true;
  3559. this.matrixWorldNeedsUpdate = true;
  3560. this.quaternion = new THREE.Quaternion();
  3561. this.useQuaternion = false;
  3562. this.visible = true;
  3563. this.castShadow = false;
  3564. this.receiveShadow = false;
  3565. this.frustumCulled = true;
  3566. this._vector = new THREE.Vector3();
  3567. };
  3568. THREE.Object3D.prototype = {
  3569. constructor: THREE.Object3D,
  3570. applyMatrix: function ( matrix ) {
  3571. this.matrix.multiplyMatrices( matrix, this.matrix );
  3572. this.scale.getScaleFromMatrix( this.matrix );
  3573. var mat = new THREE.Matrix4().extractRotation( this.matrix );
  3574. this.rotation.setEulerFromRotationMatrix( mat, this.eulerOrder );
  3575. this.position.getPositionFromMatrix( this.matrix );
  3576. },
  3577. translate: function ( distance, axis ) {
  3578. this.matrix.rotateAxis( axis );
  3579. this.position.add( axis.multiplyScalar( distance ) );
  3580. },
  3581. translateX: function ( distance ) {
  3582. this.translate( distance, this._vector.set( 1, 0, 0 ) );
  3583. },
  3584. translateY: function ( distance ) {
  3585. this.translate( distance, this._vector.set( 0, 1, 0 ) );
  3586. },
  3587. translateZ: function ( distance ) {
  3588. this.translate( distance, this._vector.set( 0, 0, 1 ) );
  3589. },
  3590. localToWorld: function ( vector ) {
  3591. return vector.applyMatrix4( this.matrixWorld );
  3592. },
  3593. worldToLocal: function ( vector ) {
  3594. return vector.applyMatrix4( THREE.Object3D.__m1.getInverse( this.matrixWorld ) );
  3595. },
  3596. lookAt: function ( vector ) {
  3597. // TODO: Add hierarchy support.
  3598. this.matrix.lookAt( vector, this.position, this.up );
  3599. if ( this.rotationAutoUpdate ) {
  3600. if ( this.useQuaternion === false ) {
  3601. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  3602. } else {
  3603. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  3604. }
  3605. }
  3606. },
  3607. add: function ( object ) {
  3608. if ( object === this ) {
  3609. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  3610. return;
  3611. }
  3612. if ( object instanceof THREE.Object3D ) {
  3613. if ( object.parent !== undefined ) {
  3614. object.parent.remove( object );
  3615. }
  3616. object.parent = this;
  3617. this.children.push( object );
  3618. // add to scene
  3619. var scene = this;
  3620. while ( scene.parent !== undefined ) {
  3621. scene = scene.parent;
  3622. }
  3623. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  3624. scene.__addObject( object );
  3625. }
  3626. }
  3627. },
  3628. remove: function ( object ) {
  3629. var index = this.children.indexOf( object );
  3630. if ( index !== - 1 ) {
  3631. object.parent = undefined;
  3632. this.children.splice( index, 1 );
  3633. // remove from scene
  3634. var scene = this;
  3635. while ( scene.parent !== undefined ) {
  3636. scene = scene.parent;
  3637. }
  3638. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  3639. scene.__removeObject( object );
  3640. }
  3641. }
  3642. },
  3643. traverse: function ( callback ) {
  3644. callback( this );
  3645. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3646. this.children[ i ].traverse( callback );
  3647. }
  3648. },
  3649. getChildByName: function ( name, recursive ) {
  3650. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3651. var child = this.children[ i ];
  3652. if ( child.name === name ) {
  3653. return child;
  3654. }
  3655. if ( recursive === true ) {
  3656. child = child.getChildByName( name, recursive );
  3657. if ( child !== undefined ) {
  3658. return child;
  3659. }
  3660. }
  3661. }
  3662. return undefined;
  3663. },
  3664. getDescendants: function ( array ) {
  3665. if ( array === undefined ) array = [];
  3666. Array.prototype.push.apply( array, this.children );
  3667. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3668. this.children[ i ].getDescendants( array );
  3669. }
  3670. return array;
  3671. },
  3672. updateMatrix: function () {
  3673. this.matrix.setPosition( this.position );
  3674. if ( this.useQuaternion === false ) {
  3675. this.matrix.setRotationFromEuler( this.rotation, this.eulerOrder );
  3676. } else {
  3677. this.matrix.setRotationFromQuaternion( this.quaternion );
  3678. }
  3679. if ( this.scale.x !== 1 || this.scale.y !== 1 || this.scale.z !== 1 ) {
  3680. this.matrix.scale( this.scale );
  3681. }
  3682. this.matrixWorldNeedsUpdate = true;
  3683. },
  3684. updateMatrixWorld: function ( force ) {
  3685. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  3686. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  3687. if ( this.parent === undefined ) {
  3688. this.matrixWorld.copy( this.matrix );
  3689. } else {
  3690. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  3691. }
  3692. this.matrixWorldNeedsUpdate = false;
  3693. force = true;
  3694. }
  3695. // update children
  3696. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3697. this.children[ i ].updateMatrixWorld( force );
  3698. }
  3699. },
  3700. clone: function ( object ) {
  3701. if ( object === undefined ) object = new THREE.Object3D();
  3702. object.name = this.name;
  3703. object.up.copy( this.up );
  3704. object.position.copy( this.position );
  3705. if ( object.rotation instanceof THREE.Vector3 ) object.rotation.copy( this.rotation ); // because of Sprite madness
  3706. object.eulerOrder = this.eulerOrder;
  3707. object.scale.copy( this.scale );
  3708. object.renderDepth = this.renderDepth;
  3709. object.rotationAutoUpdate = this.rotationAutoUpdate;
  3710. object.matrix.copy( this.matrix );
  3711. object.matrixWorld.copy( this.matrixWorld );
  3712. object.matrixRotationWorld.copy( this.matrixRotationWorld );
  3713. object.matrixAutoUpdate = this.matrixAutoUpdate;
  3714. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  3715. object.quaternion.copy( this.quaternion );
  3716. object.useQuaternion = this.useQuaternion;
  3717. object.visible = this.visible;
  3718. object.castShadow = this.castShadow;
  3719. object.receiveShadow = this.receiveShadow;
  3720. object.frustumCulled = this.frustumCulled;
  3721. for ( var i = 0; i < this.children.length; i ++ ) {
  3722. var child = this.children[ i ];
  3723. object.add( child.clone() );
  3724. }
  3725. return object;
  3726. }
  3727. };
  3728. THREE.Object3D.__m1 = new THREE.Matrix4();
  3729. THREE.Object3D.defaultEulerOrder = 'XYZ',
  3730. THREE.Object3DIdCount = 0;
  3731. /**
  3732. * @author mrdoob / http://mrdoob.com/
  3733. * @author supereggbert / http://www.paulbrunt.co.uk/
  3734. * @author julianwa / https://github.com/julianwa
  3735. */
  3736. THREE.Projector = function() {
  3737. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  3738. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  3739. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  3740. _face4Count, _face4Pool = [], _face4PoolLength = 0,
  3741. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  3742. _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
  3743. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  3744. _vector3 = new THREE.Vector3(),
  3745. _vector4 = new THREE.Vector4(),
  3746. _viewMatrix = new THREE.Matrix4(),
  3747. _viewProjectionMatrix = new THREE.Matrix4(),
  3748. _modelMatrix,
  3749. _modelViewProjectionMatrix = new THREE.Matrix4(),
  3750. _normalMatrix = new THREE.Matrix3(),
  3751. _normalViewMatrix = new THREE.Matrix3(),
  3752. _centroid = new THREE.Vector3(),
  3753. _frustum = new THREE.Frustum(),
  3754. _clippedVertex1PositionScreen = new THREE.Vector4(),
  3755. _clippedVertex2PositionScreen = new THREE.Vector4(),
  3756. _face3VertexNormals;
  3757. this.projectVector = function ( vector, camera ) {
  3758. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  3759. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  3760. return vector.applyMatrix4( _viewProjectionMatrix );
  3761. };
  3762. this.unprojectVector = function ( vector, camera ) {
  3763. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  3764. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, camera.projectionMatrixInverse );
  3765. return vector.applyMatrix4( _viewProjectionMatrix );
  3766. };
  3767. this.pickingRay = function ( vector, camera ) {
  3768. // set two vectors with opposing z values
  3769. vector.z = -1.0;
  3770. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  3771. this.unprojectVector( vector, camera );
  3772. this.unprojectVector( end, camera );
  3773. // find direction from vector to end
  3774. end.sub( vector ).normalize();
  3775. return new THREE.Raycaster( vector, end );
  3776. };
  3777. var projectGraph = function ( root, sortObjects ) {
  3778. _objectCount = 0;
  3779. _renderData.objects.length = 0;
  3780. _renderData.sprites.length = 0;
  3781. _renderData.lights.length = 0;
  3782. var projectObject = function ( parent ) {
  3783. for ( var c = 0, cl = parent.children.length; c < cl; c ++ ) {
  3784. var object = parent.children[ c ];
  3785. if ( object.visible === false ) continue;
  3786. if ( object instanceof THREE.Light ) {
  3787. _renderData.lights.push( object );
  3788. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  3789. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  3790. _object = getNextObjectInPool();
  3791. _object.object = object;
  3792. if ( object.renderDepth !== null ) {
  3793. _object.z = object.renderDepth;
  3794. } else {
  3795. _vector3.copy( object.matrixWorld.getPosition() );
  3796. _vector3.applyMatrix4( _viewProjectionMatrix );
  3797. _object.z = _vector3.z;
  3798. }
  3799. _renderData.objects.push( _object );
  3800. }
  3801. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  3802. _object = getNextObjectInPool();
  3803. _object.object = object;
  3804. // TODO: Find an elegant and performant solution and remove this dupe code.
  3805. if ( object.renderDepth !== null ) {
  3806. _object.z = object.renderDepth;
  3807. } else {
  3808. _vector3.copy( object.matrixWorld.getPosition() );
  3809. _vector3.applyMatrix4( _viewProjectionMatrix );
  3810. _object.z = _vector3.z;
  3811. }
  3812. _renderData.sprites.push( _object );
  3813. } else {
  3814. _object = getNextObjectInPool();
  3815. _object.object = object;
  3816. if ( object.renderDepth !== null ) {
  3817. _object.z = object.renderDepth;
  3818. } else {
  3819. _vector3.copy( object.matrixWorld.getPosition() );
  3820. _vector3.applyMatrix4( _viewProjectionMatrix );
  3821. _object.z = _vector3.z;
  3822. }
  3823. _renderData.objects.push( _object );
  3824. }
  3825. projectObject( object );
  3826. }
  3827. };
  3828. projectObject( root );
  3829. if ( sortObjects === true ) _renderData.objects.sort( painterSort );
  3830. return _renderData;
  3831. };
  3832. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  3833. var visible = false,
  3834. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  3835. geometry, vertices, vertex, vertexPositionScreen,
  3836. faces, face, faceVertexNormals, faceVertexUvs, uvs,
  3837. v1, v2, v3, v4, isFaceMaterial, objectMaterials;
  3838. _face3Count = 0;
  3839. _face4Count = 0;
  3840. _lineCount = 0;
  3841. _particleCount = 0;
  3842. _renderData.elements.length = 0;
  3843. scene.updateMatrixWorld();
  3844. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  3845. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  3846. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  3847. _normalViewMatrix.getInverse( _viewMatrix );
  3848. _normalViewMatrix.transpose();
  3849. _frustum.setFromMatrix( _viewProjectionMatrix );
  3850. _renderData = projectGraph( scene, sortObjects );
  3851. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  3852. object = _renderData.objects[ o ].object;
  3853. _modelMatrix = object.matrixWorld;
  3854. _vertexCount = 0;
  3855. if ( object instanceof THREE.Mesh ) {
  3856. geometry = object.geometry;
  3857. vertices = geometry.vertices;
  3858. faces = geometry.faces;
  3859. faceVertexUvs = geometry.faceVertexUvs;
  3860. _normalMatrix.getInverse( _modelMatrix );
  3861. _normalMatrix.transpose();
  3862. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3863. objectMaterials = isFaceMaterial === true ? object.material : null;
  3864. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  3865. _vertex = getNextVertexInPool();
  3866. _vertex.positionWorld.copy( vertices[ v ] );
  3867. _vertex.positionWorld.applyMatrix4( _modelMatrix );
  3868. _vertex.positionScreen.copy( _vertex.positionWorld );
  3869. _vertex.positionScreen.applyMatrix4( _viewProjectionMatrix );
  3870. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  3871. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  3872. _vertex.positionScreen.z /= _vertex.positionScreen.w;
  3873. _vertex.visible = _vertex.positionScreen.z > -1 && _vertex.positionScreen.z < 1;
  3874. }
  3875. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  3876. face = faces[ f ];
  3877. var material = isFaceMaterial === true
  3878. ? objectMaterials.materials[ face.materialIndex ]
  3879. : object.material;
  3880. if ( material === undefined ) continue;
  3881. var side = material.side;
  3882. if ( face instanceof THREE.Face3 ) {
  3883. v1 = _vertexPool[ face.a ];
  3884. v2 = _vertexPool[ face.b ];
  3885. v3 = _vertexPool[ face.c ];
  3886. if ( v1.visible === true && v2.visible === true && v3.visible === true ) {
  3887. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  3888. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  3889. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  3890. _face = getNextFace3InPool();
  3891. _face.v1.copy( v1 );
  3892. _face.v2.copy( v2 );
  3893. _face.v3.copy( v3 );
  3894. } else {
  3895. continue;
  3896. }
  3897. } else {
  3898. continue;
  3899. }
  3900. } else if ( face instanceof THREE.Face4 ) {
  3901. v1 = _vertexPool[ face.a ];
  3902. v2 = _vertexPool[ face.b ];
  3903. v3 = _vertexPool[ face.c ];
  3904. v4 = _vertexPool[ face.d ];
  3905. if ( v1.visible === true && v2.visible === true && v3.visible === true && v4.visible === true ) {
  3906. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  3907. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  3908. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  3909. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  3910. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  3911. _face = getNextFace4InPool();
  3912. _face.v1.copy( v1 );
  3913. _face.v2.copy( v2 );
  3914. _face.v3.copy( v3 );
  3915. _face.v4.copy( v4 );
  3916. } else {
  3917. continue;
  3918. }
  3919. } else {
  3920. continue;
  3921. }
  3922. }
  3923. _face.normalModel.copy( face.normal );
  3924. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  3925. _face.normalModel.negate();
  3926. }
  3927. _face.normalModel.applyMatrix3( _normalMatrix );
  3928. _face.normalModel.normalize();
  3929. _face.normalModelView.copy( _face.normalModel );
  3930. _face.normalModelView.applyMatrix3( _normalViewMatrix );
  3931. _face.centroidModel.copy( face.centroid );
  3932. _face.centroidModel.applyMatrix4( _modelMatrix );
  3933. faceVertexNormals = face.vertexNormals;
  3934. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  3935. var normalModel = _face.vertexNormalsModel[ n ];
  3936. normalModel.copy( faceVertexNormals[ n ] );
  3937. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  3938. normalModel.negate();
  3939. }
  3940. normalModel.applyMatrix3( _normalMatrix );
  3941. normalModel.normalize();
  3942. var normalModelView = _face.vertexNormalsModelView[ n ];
  3943. normalModelView.copy( normalModel );
  3944. normalModelView.applyMatrix3( _normalViewMatrix );
  3945. }
  3946. _face.vertexNormalsLength = faceVertexNormals.length;
  3947. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  3948. uvs = faceVertexUvs[ c ][ f ];
  3949. if ( uvs === undefined ) continue;
  3950. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  3951. _face.uvs[ c ][ u ] = uvs[ u ];
  3952. }
  3953. }
  3954. _face.color = face.color;
  3955. _face.material = material;
  3956. _centroid.copy( _face.centroidModel )
  3957. _centroid.applyMatrix4( _viewProjectionMatrix );
  3958. _face.z = _centroid.z;
  3959. _renderData.elements.push( _face );
  3960. }
  3961. } else if ( object instanceof THREE.Line ) {
  3962. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  3963. vertices = object.geometry.vertices;
  3964. v1 = getNextVertexInPool();
  3965. v1.positionScreen.copy( vertices[ 0 ] );
  3966. v1.positionScreen.applyMatrix4( _modelViewProjectionMatrix );
  3967. // Handle LineStrip and LinePieces
  3968. var step = object.type === THREE.LinePieces ? 2 : 1;
  3969. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  3970. v1 = getNextVertexInPool();
  3971. v1.positionScreen.copy( vertices[ v ] );
  3972. v1.positionScreen.applyMatrix4( _modelViewProjectionMatrix );
  3973. if ( ( v + 1 ) % step > 0 ) continue;
  3974. v2 = _vertexPool[ _vertexCount - 2 ];
  3975. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  3976. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  3977. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  3978. // Perform the perspective divide
  3979. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  3980. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  3981. _line = getNextLineInPool();
  3982. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  3983. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  3984. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  3985. _line.material = object.material;
  3986. _renderData.elements.push( _line );
  3987. }
  3988. }
  3989. }
  3990. }
  3991. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  3992. object = _renderData.sprites[ o ].object;
  3993. _modelMatrix = object.matrixWorld;
  3994. if ( object instanceof THREE.Particle ) {
  3995. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  3996. _vector4.applyMatrix4( _viewProjectionMatrix );
  3997. _vector4.z /= _vector4.w;
  3998. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  3999. _particle = getNextParticleInPool();
  4000. _particle.object = object;
  4001. _particle.x = _vector4.x / _vector4.w;
  4002. _particle.y = _vector4.y / _vector4.w;
  4003. _particle.z = _vector4.z;
  4004. _particle.rotation = object.rotation.z;
  4005. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  4006. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  4007. _particle.material = object.material;
  4008. _renderData.elements.push( _particle );
  4009. }
  4010. }
  4011. }
  4012. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  4013. return _renderData;
  4014. };
  4015. // Pools
  4016. function getNextObjectInPool() {
  4017. if ( _objectCount === _objectPoolLength ) {
  4018. var object = new THREE.RenderableObject();
  4019. _objectPool.push( object );
  4020. _objectPoolLength ++;
  4021. _objectCount ++;
  4022. return object;
  4023. }
  4024. return _objectPool[ _objectCount ++ ];
  4025. }
  4026. function getNextVertexInPool() {
  4027. if ( _vertexCount === _vertexPoolLength ) {
  4028. var vertex = new THREE.RenderableVertex();
  4029. _vertexPool.push( vertex );
  4030. _vertexPoolLength ++;
  4031. _vertexCount ++;
  4032. return vertex;
  4033. }
  4034. return _vertexPool[ _vertexCount ++ ];
  4035. }
  4036. function getNextFace3InPool() {
  4037. if ( _face3Count === _face3PoolLength ) {
  4038. var face = new THREE.RenderableFace3();
  4039. _face3Pool.push( face );
  4040. _face3PoolLength ++;
  4041. _face3Count ++;
  4042. return face;
  4043. }
  4044. return _face3Pool[ _face3Count ++ ];
  4045. }
  4046. function getNextFace4InPool() {
  4047. if ( _face4Count === _face4PoolLength ) {
  4048. var face = new THREE.RenderableFace4();
  4049. _face4Pool.push( face );
  4050. _face4PoolLength ++;
  4051. _face4Count ++;
  4052. return face;
  4053. }
  4054. return _face4Pool[ _face4Count ++ ];
  4055. }
  4056. function getNextLineInPool() {
  4057. if ( _lineCount === _linePoolLength ) {
  4058. var line = new THREE.RenderableLine();
  4059. _linePool.push( line );
  4060. _linePoolLength ++;
  4061. _lineCount ++
  4062. return line;
  4063. }
  4064. return _linePool[ _lineCount ++ ];
  4065. }
  4066. function getNextParticleInPool() {
  4067. if ( _particleCount === _particlePoolLength ) {
  4068. var particle = new THREE.RenderableParticle();
  4069. _particlePool.push( particle );
  4070. _particlePoolLength ++;
  4071. _particleCount ++
  4072. return particle;
  4073. }
  4074. return _particlePool[ _particleCount ++ ];
  4075. }
  4076. //
  4077. function painterSort( a, b ) {
  4078. return b.z - a.z;
  4079. }
  4080. function clipLine( s1, s2 ) {
  4081. var alpha1 = 0, alpha2 = 1,
  4082. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  4083. // Z = -1 and Z = +1, respectively.
  4084. bc1near = s1.z + s1.w,
  4085. bc2near = s2.z + s2.w,
  4086. bc1far = - s1.z + s1.w,
  4087. bc2far = - s2.z + s2.w;
  4088. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  4089. // Both vertices lie entirely within all clip planes.
  4090. return true;
  4091. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  4092. // Both vertices lie entirely outside one of the clip planes.
  4093. return false;
  4094. } else {
  4095. // The line segment spans at least one clip plane.
  4096. if ( bc1near < 0 ) {
  4097. // v1 lies outside the near plane, v2 inside
  4098. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  4099. } else if ( bc2near < 0 ) {
  4100. // v2 lies outside the near plane, v1 inside
  4101. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  4102. }
  4103. if ( bc1far < 0 ) {
  4104. // v1 lies outside the far plane, v2 inside
  4105. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  4106. } else if ( bc2far < 0 ) {
  4107. // v2 lies outside the far plane, v2 inside
  4108. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  4109. }
  4110. if ( alpha2 < alpha1 ) {
  4111. // The line segment spans two boundaries, but is outside both of them.
  4112. // (This can't happen when we're only clipping against just near/far but good
  4113. // to leave the check here for future usage if other clip planes are added.)
  4114. return false;
  4115. } else {
  4116. // Update the s1 and s2 vertices to match the clipped line segment.
  4117. s1.lerp( s2, alpha1 );
  4118. s2.lerp( s1, 1 - alpha2 );
  4119. return true;
  4120. }
  4121. }
  4122. }
  4123. };
  4124. /**
  4125. * @author mrdoob / http://mrdoob.com/
  4126. * @author alteredq / http://alteredqualia.com/
  4127. */
  4128. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  4129. this.a = a;
  4130. this.b = b;
  4131. this.c = c;
  4132. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4133. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4134. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4135. this.vertexColors = color instanceof Array ? color : [];
  4136. this.vertexTangents = [];
  4137. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4138. this.centroid = new THREE.Vector3();
  4139. };
  4140. THREE.Face3.prototype = {
  4141. constructor: THREE.Face3,
  4142. clone: function () {
  4143. var face = new THREE.Face3( this.a, this.b, this.c );
  4144. face.normal.copy( this.normal );
  4145. face.color.copy( this.color );
  4146. face.centroid.copy( this.centroid );
  4147. face.materialIndex = this.materialIndex;
  4148. var i, il;
  4149. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4150. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4151. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4152. return face;
  4153. }
  4154. };
  4155. /**
  4156. * @author mrdoob / http://mrdoob.com/
  4157. * @author alteredq / http://alteredqualia.com/
  4158. */
  4159. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  4160. this.a = a;
  4161. this.b = b;
  4162. this.c = c;
  4163. this.d = d;
  4164. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4165. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4166. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4167. this.vertexColors = color instanceof Array ? color : [];
  4168. this.vertexTangents = [];
  4169. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4170. this.centroid = new THREE.Vector3();
  4171. };
  4172. THREE.Face4.prototype = {
  4173. constructor: THREE.Face4,
  4174. clone: function () {
  4175. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  4176. face.normal.copy( this.normal );
  4177. face.color.copy( this.color );
  4178. face.centroid.copy( this.centroid );
  4179. face.materialIndex = this.materialIndex;
  4180. var i, il;
  4181. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4182. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4183. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4184. return face;
  4185. }
  4186. };
  4187. /**
  4188. * @author mrdoob / http://mrdoob.com/
  4189. * @author kile / http://kile.stravaganza.org/
  4190. * @author alteredq / http://alteredqualia.com/
  4191. * @author mikael emtinger / http://gomo.se/
  4192. * @author zz85 / http://www.lab4games.net/zz85/blog
  4193. * @author bhouston / http://exocortex.com
  4194. */
  4195. THREE.Geometry = function () {
  4196. THREE.EventDispatcher.call( this );
  4197. this.id = THREE.GeometryIdCount ++;
  4198. this.name = '';
  4199. this.vertices = [];
  4200. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  4201. this.normals = []; // one-to-one vertex normals, used in Ribbon
  4202. this.faces = [];
  4203. this.faceUvs = [[]];
  4204. this.faceVertexUvs = [[]];
  4205. this.morphTargets = [];
  4206. this.morphColors = [];
  4207. this.morphNormals = [];
  4208. this.skinWeights = [];
  4209. this.skinIndices = [];
  4210. this.lineDistances = [];
  4211. this.boundingBox = null;
  4212. this.boundingSphere = null;
  4213. this.hasTangents = false;
  4214. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  4215. // update flags
  4216. this.verticesNeedUpdate = false;
  4217. this.elementsNeedUpdate = false;
  4218. this.uvsNeedUpdate = false;
  4219. this.normalsNeedUpdate = false;
  4220. this.tangentsNeedUpdate = false;
  4221. this.colorsNeedUpdate = false;
  4222. this.lineDistancesNeedUpdate = false;
  4223. this.buffersNeedUpdate = false;
  4224. };
  4225. THREE.Geometry.prototype = {
  4226. constructor: THREE.Geometry,
  4227. applyMatrix: function ( matrix ) {
  4228. var normalMatrix = new THREE.Matrix3().getInverse( matrix ).transpose();
  4229. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  4230. var vertex = this.vertices[ i ];
  4231. vertex.applyMatrix4( matrix );
  4232. }
  4233. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  4234. var face = this.faces[ i ];
  4235. face.normal.applyMatrix3( normalMatrix ).normalize();
  4236. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  4237. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  4238. }
  4239. face.centroid.applyMatrix4( matrix );
  4240. }
  4241. },
  4242. computeCentroids: function () {
  4243. var f, fl, face;
  4244. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4245. face = this.faces[ f ];
  4246. face.centroid.set( 0, 0, 0 );
  4247. if ( face instanceof THREE.Face3 ) {
  4248. face.centroid.add( this.vertices[ face.a ] );
  4249. face.centroid.add( this.vertices[ face.b ] );
  4250. face.centroid.add( this.vertices[ face.c ] );
  4251. face.centroid.divideScalar( 3 );
  4252. } else if ( face instanceof THREE.Face4 ) {
  4253. face.centroid.add( this.vertices[ face.a ] );
  4254. face.centroid.add( this.vertices[ face.b ] );
  4255. face.centroid.add( this.vertices[ face.c ] );
  4256. face.centroid.add( this.vertices[ face.d ] );
  4257. face.centroid.divideScalar( 4 );
  4258. }
  4259. }
  4260. },
  4261. computeFaceNormals: function () {
  4262. var n, nl, v, vl, vertex, f, fl, face, vA, vB, vC,
  4263. cb = new THREE.Vector3(), ab = new THREE.Vector3();
  4264. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4265. face = this.faces[ f ];
  4266. vA = this.vertices[ face.a ];
  4267. vB = this.vertices[ face.b ];
  4268. vC = this.vertices[ face.c ];
  4269. cb.subVectors( vC, vB );
  4270. ab.subVectors( vA, vB );
  4271. cb.cross( ab );
  4272. cb.normalize();
  4273. face.normal.copy( cb );
  4274. }
  4275. },
  4276. computeVertexNormals: function ( areaWeighted ) {
  4277. var v, vl, f, fl, face, vertices;
  4278. // create internal buffers for reuse when calling this method repeatedly
  4279. // (otherwise memory allocation / deallocation every frame is big resource hog)
  4280. if ( this.__tmpVertices === undefined ) {
  4281. this.__tmpVertices = new Array( this.vertices.length );
  4282. vertices = this.__tmpVertices;
  4283. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4284. vertices[ v ] = new THREE.Vector3();
  4285. }
  4286. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4287. face = this.faces[ f ];
  4288. if ( face instanceof THREE.Face3 ) {
  4289. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4290. } else if ( face instanceof THREE.Face4 ) {
  4291. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4292. }
  4293. }
  4294. } else {
  4295. vertices = this.__tmpVertices;
  4296. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4297. vertices[ v ].set( 0, 0, 0 );
  4298. }
  4299. }
  4300. if ( areaWeighted ) {
  4301. // vertex normals weighted by triangle areas
  4302. // http://www.iquilezles.org/www/articles/normals/normals.htm
  4303. var vA, vB, vC, vD;
  4304. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  4305. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  4306. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4307. face = this.faces[ f ];
  4308. if ( face instanceof THREE.Face3 ) {
  4309. vA = this.vertices[ face.a ];
  4310. vB = this.vertices[ face.b ];
  4311. vC = this.vertices[ face.c ];
  4312. cb.subVectors( vC, vB );
  4313. ab.subVectors( vA, vB );
  4314. cb.cross( ab );
  4315. vertices[ face.a ].add( cb );
  4316. vertices[ face.b ].add( cb );
  4317. vertices[ face.c ].add( cb );
  4318. } else if ( face instanceof THREE.Face4 ) {
  4319. vA = this.vertices[ face.a ];
  4320. vB = this.vertices[ face.b ];
  4321. vC = this.vertices[ face.c ];
  4322. vD = this.vertices[ face.d ];
  4323. // abd
  4324. db.subVectors( vD, vB );
  4325. ab.subVectors( vA, vB );
  4326. db.cross( ab );
  4327. vertices[ face.a ].add( db );
  4328. vertices[ face.b ].add( db );
  4329. vertices[ face.d ].add( db );
  4330. // bcd
  4331. dc.subVectors( vD, vC );
  4332. bc.subVectors( vB, vC );
  4333. dc.cross( bc );
  4334. vertices[ face.b ].add( dc );
  4335. vertices[ face.c ].add( dc );
  4336. vertices[ face.d ].add( dc );
  4337. }
  4338. }
  4339. } else {
  4340. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4341. face = this.faces[ f ];
  4342. if ( face instanceof THREE.Face3 ) {
  4343. vertices[ face.a ].add( face.normal );
  4344. vertices[ face.b ].add( face.normal );
  4345. vertices[ face.c ].add( face.normal );
  4346. } else if ( face instanceof THREE.Face4 ) {
  4347. vertices[ face.a ].add( face.normal );
  4348. vertices[ face.b ].add( face.normal );
  4349. vertices[ face.c ].add( face.normal );
  4350. vertices[ face.d ].add( face.normal );
  4351. }
  4352. }
  4353. }
  4354. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4355. vertices[ v ].normalize();
  4356. }
  4357. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4358. face = this.faces[ f ];
  4359. if ( face instanceof THREE.Face3 ) {
  4360. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4361. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4362. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4363. } else if ( face instanceof THREE.Face4 ) {
  4364. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4365. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4366. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4367. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  4368. }
  4369. }
  4370. },
  4371. computeMorphNormals: function () {
  4372. var i, il, f, fl, face;
  4373. // save original normals
  4374. // - create temp variables on first access
  4375. // otherwise just copy (for faster repeated calls)
  4376. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4377. face = this.faces[ f ];
  4378. if ( ! face.__originalFaceNormal ) {
  4379. face.__originalFaceNormal = face.normal.clone();
  4380. } else {
  4381. face.__originalFaceNormal.copy( face.normal );
  4382. }
  4383. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  4384. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  4385. if ( ! face.__originalVertexNormals[ i ] ) {
  4386. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  4387. } else {
  4388. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  4389. }
  4390. }
  4391. }
  4392. // use temp geometry to compute face and vertex normals for each morph
  4393. var tmpGeo = new THREE.Geometry();
  4394. tmpGeo.faces = this.faces;
  4395. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  4396. // create on first access
  4397. if ( ! this.morphNormals[ i ] ) {
  4398. this.morphNormals[ i ] = {};
  4399. this.morphNormals[ i ].faceNormals = [];
  4400. this.morphNormals[ i ].vertexNormals = [];
  4401. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  4402. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  4403. var faceNormal, vertexNormals;
  4404. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4405. face = this.faces[ f ];
  4406. faceNormal = new THREE.Vector3();
  4407. if ( face instanceof THREE.Face3 ) {
  4408. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  4409. } else {
  4410. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  4411. }
  4412. dstNormalsFace.push( faceNormal );
  4413. dstNormalsVertex.push( vertexNormals );
  4414. }
  4415. }
  4416. var morphNormals = this.morphNormals[ i ];
  4417. // set vertices to morph target
  4418. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  4419. // compute morph normals
  4420. tmpGeo.computeFaceNormals();
  4421. tmpGeo.computeVertexNormals();
  4422. // store morph normals
  4423. var faceNormal, vertexNormals;
  4424. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4425. face = this.faces[ f ];
  4426. faceNormal = morphNormals.faceNormals[ f ];
  4427. vertexNormals = morphNormals.vertexNormals[ f ];
  4428. faceNormal.copy( face.normal );
  4429. if ( face instanceof THREE.Face3 ) {
  4430. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4431. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4432. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4433. } else {
  4434. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4435. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4436. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4437. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  4438. }
  4439. }
  4440. }
  4441. // restore original normals
  4442. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4443. face = this.faces[ f ];
  4444. face.normal = face.__originalFaceNormal;
  4445. face.vertexNormals = face.__originalVertexNormals;
  4446. }
  4447. },
  4448. computeTangents: function () {
  4449. // based on http://www.terathon.com/code/tangent.html
  4450. // tangents go to vertices
  4451. var f, fl, v, vl, i, il, vertexIndex,
  4452. face, uv, vA, vB, vC, uvA, uvB, uvC,
  4453. x1, x2, y1, y2, z1, z2,
  4454. s1, s2, t1, t2, r, t, test,
  4455. tan1 = [], tan2 = [],
  4456. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  4457. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  4458. n = new THREE.Vector3(), w;
  4459. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4460. tan1[ v ] = new THREE.Vector3();
  4461. tan2[ v ] = new THREE.Vector3();
  4462. }
  4463. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  4464. vA = context.vertices[ a ];
  4465. vB = context.vertices[ b ];
  4466. vC = context.vertices[ c ];
  4467. uvA = uv[ ua ];
  4468. uvB = uv[ ub ];
  4469. uvC = uv[ uc ];
  4470. x1 = vB.x - vA.x;
  4471. x2 = vC.x - vA.x;
  4472. y1 = vB.y - vA.y;
  4473. y2 = vC.y - vA.y;
  4474. z1 = vB.z - vA.z;
  4475. z2 = vC.z - vA.z;
  4476. s1 = uvB.x - uvA.x;
  4477. s2 = uvC.x - uvA.x;
  4478. t1 = uvB.y - uvA.y;
  4479. t2 = uvC.y - uvA.y;
  4480. r = 1.0 / ( s1 * t2 - s2 * t1 );
  4481. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  4482. ( t2 * y1 - t1 * y2 ) * r,
  4483. ( t2 * z1 - t1 * z2 ) * r );
  4484. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  4485. ( s1 * y2 - s2 * y1 ) * r,
  4486. ( s1 * z2 - s2 * z1 ) * r );
  4487. tan1[ a ].add( sdir );
  4488. tan1[ b ].add( sdir );
  4489. tan1[ c ].add( sdir );
  4490. tan2[ a ].add( tdir );
  4491. tan2[ b ].add( tdir );
  4492. tan2[ c ].add( tdir );
  4493. }
  4494. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4495. face = this.faces[ f ];
  4496. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  4497. if ( face instanceof THREE.Face3 ) {
  4498. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  4499. } else if ( face instanceof THREE.Face4 ) {
  4500. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  4501. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  4502. }
  4503. }
  4504. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  4505. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4506. face = this.faces[ f ];
  4507. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  4508. n.copy( face.vertexNormals[ i ] );
  4509. vertexIndex = face[ faceIndex[ i ] ];
  4510. t = tan1[ vertexIndex ];
  4511. // Gram-Schmidt orthogonalize
  4512. tmp.copy( t );
  4513. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  4514. // Calculate handedness
  4515. tmp2.crossVectors( face.vertexNormals[ i ], t );
  4516. test = tmp2.dot( tan2[ vertexIndex ] );
  4517. w = (test < 0.0) ? -1.0 : 1.0;
  4518. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  4519. }
  4520. }
  4521. this.hasTangents = true;
  4522. },
  4523. computeLineDistances: function ( ) {
  4524. var d = 0;
  4525. var vertices = this.vertices;
  4526. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4527. if ( i > 0 ) {
  4528. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  4529. }
  4530. this.lineDistances[ i ] = d;
  4531. }
  4532. },
  4533. computeBoundingBox: function () {
  4534. if ( this.boundingBox === null ) {
  4535. this.boundingBox = new THREE.Box3();
  4536. }
  4537. this.boundingBox.setFromPoints( this.vertices );
  4538. },
  4539. computeBoundingSphere: function () {
  4540. if ( this.boundingSphere === null ) {
  4541. this.boundingSphere = new THREE.Sphere();
  4542. }
  4543. this.boundingSphere.setFromCenterAndPoints( this.boundingSphere.center, this.vertices );
  4544. },
  4545. /*
  4546. * Checks for duplicate vertices with hashmap.
  4547. * Duplicated vertices are removed
  4548. * and faces' vertices are updated.
  4549. */
  4550. mergeVertices: function () {
  4551. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  4552. var unique = [], changes = [];
  4553. var v, key;
  4554. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  4555. var precision = Math.pow( 10, precisionPoints );
  4556. var i,il, face;
  4557. var indices, k, j, jl, u;
  4558. // reset cache of vertices as it now will be changing.
  4559. this.__tmpVertices = undefined;
  4560. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  4561. v = this.vertices[ i ];
  4562. key = [ Math.round( v.x * precision ), Math.round( v.y * precision ), Math.round( v.z * precision ) ].join( '_' );
  4563. if ( verticesMap[ key ] === undefined ) {
  4564. verticesMap[ key ] = i;
  4565. unique.push( this.vertices[ i ] );
  4566. changes[ i ] = unique.length - 1;
  4567. } else {
  4568. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  4569. changes[ i ] = changes[ verticesMap[ key ] ];
  4570. }
  4571. };
  4572. // if faces are completely degenerate after merging vertices, we
  4573. // have to remove them from the geometry.
  4574. var faceIndicesToRemove = [];
  4575. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  4576. face = this.faces[ i ];
  4577. if ( face instanceof THREE.Face3 ) {
  4578. face.a = changes[ face.a ];
  4579. face.b = changes[ face.b ];
  4580. face.c = changes[ face.c ];
  4581. indices = [ face.a, face.b, face.c ];
  4582. var dupIndex = -1;
  4583. // if any duplicate vertices are found in a Face3
  4584. // we have to remove the face as nothing can be saved
  4585. for ( var n = 0; n < 3; n ++ ) {
  4586. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  4587. dupIndex = n;
  4588. faceIndicesToRemove.push( i );
  4589. break;
  4590. }
  4591. }
  4592. } else if ( face instanceof THREE.Face4 ) {
  4593. face.a = changes[ face.a ];
  4594. face.b = changes[ face.b ];
  4595. face.c = changes[ face.c ];
  4596. face.d = changes[ face.d ];
  4597. // check dups in (a, b, c, d) and convert to -> face3
  4598. indices = [ face.a, face.b, face.c, face.d ];
  4599. var dupIndex = -1;
  4600. for ( var n = 0; n < 4; n ++ ) {
  4601. if ( indices[ n ] == indices[ ( n + 1 ) % 4 ] ) {
  4602. // if more than one duplicated vertex is found
  4603. // we can't generate any valid Face3's, thus
  4604. // we need to remove this face complete.
  4605. if ( dupIndex >= 0 ) {
  4606. faceIndicesToRemove.push( i );
  4607. }
  4608. dupIndex = n;
  4609. }
  4610. }
  4611. if ( dupIndex >= 0 ) {
  4612. indices.splice( dupIndex, 1 );
  4613. var newFace = new THREE.Face3( indices[0], indices[1], indices[2], face.normal, face.color, face.materialIndex );
  4614. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  4615. u = this.faceVertexUvs[ j ][ i ];
  4616. if ( u ) {
  4617. u.splice( dupIndex, 1 );
  4618. }
  4619. }
  4620. if( face.vertexNormals && face.vertexNormals.length > 0) {
  4621. newFace.vertexNormals = face.vertexNormals;
  4622. newFace.vertexNormals.splice( dupIndex, 1 );
  4623. }
  4624. if( face.vertexColors && face.vertexColors.length > 0 ) {
  4625. newFace.vertexColors = face.vertexColors;
  4626. newFace.vertexColors.splice( dupIndex, 1 );
  4627. }
  4628. this.faces[ i ] = newFace;
  4629. }
  4630. }
  4631. }
  4632. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  4633. this.faces.splice( i, 1 );
  4634. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  4635. this.faceVertexUvs[ j ].splice( i, 1 );
  4636. }
  4637. }
  4638. // Use unique set of vertices
  4639. var diff = this.vertices.length - unique.length;
  4640. this.vertices = unique;
  4641. return diff;
  4642. },
  4643. clone: function () {
  4644. var geometry = new THREE.Geometry();
  4645. var vertices = this.vertices;
  4646. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4647. geometry.vertices.push( vertices[ i ].clone() );
  4648. }
  4649. var faces = this.faces;
  4650. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  4651. geometry.faces.push( faces[ i ].clone() );
  4652. }
  4653. var uvs = this.faceVertexUvs[ 0 ];
  4654. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  4655. var uv = uvs[ i ], uvCopy = [];
  4656. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  4657. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  4658. }
  4659. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  4660. }
  4661. return geometry;
  4662. },
  4663. dispose: function () {
  4664. this.dispatchEvent( { type: 'dispose' } );
  4665. }
  4666. };
  4667. THREE.GeometryIdCount = 0;
  4668. /**
  4669. * @author alteredq / http://alteredqualia.com/
  4670. */
  4671. THREE.BufferGeometry = function () {
  4672. THREE.EventDispatcher.call( this );
  4673. this.id = THREE.GeometryIdCount ++;
  4674. // attributes
  4675. this.attributes = {};
  4676. // attributes typed arrays are kept only if dynamic flag is set
  4677. this.dynamic = false;
  4678. // offsets for chunks when using indexed elements
  4679. this.offsets = [];
  4680. // boundings
  4681. this.boundingBox = null;
  4682. this.boundingSphere = null;
  4683. this.hasTangents = false;
  4684. // for compatibility
  4685. this.morphTargets = [];
  4686. };
  4687. THREE.BufferGeometry.prototype = {
  4688. constructor : THREE.BufferGeometry,
  4689. applyMatrix: function ( matrix ) {
  4690. var positionArray;
  4691. var normalArray;
  4692. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  4693. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  4694. if ( positionArray !== undefined ) {
  4695. matrix.multiplyVector3Array( positionArray );
  4696. this.verticesNeedUpdate = true;
  4697. }
  4698. if ( normalArray !== undefined ) {
  4699. var normalMatrix = new THREE.Matrix3();
  4700. normalMatrix.getInverse( matrix ).transpose();
  4701. normalMatrix.multiplyVector3Array( normalArray );
  4702. this.normalizeNormals();
  4703. this.normalsNeedUpdate = true;
  4704. }
  4705. },
  4706. computeBoundingBox: function () {
  4707. if ( this.boundingBox === null ) {
  4708. this.boundingBox = new THREE.Box3();
  4709. }
  4710. var positions = this.attributes[ "position" ].array;
  4711. if ( positions ) {
  4712. var bb = this.boundingBox;
  4713. var x, y, z;
  4714. if( positions.length >= 3 ) {
  4715. bb.min.x = bb.max.x = positions[ 0 ];
  4716. bb.min.y = bb.max.y = positions[ 1 ];
  4717. bb.min.z = bb.max.z = positions[ 2 ];
  4718. }
  4719. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  4720. x = positions[ i ];
  4721. y = positions[ i + 1 ];
  4722. z = positions[ i + 2 ];
  4723. // bounding box
  4724. if ( x < bb.min.x ) {
  4725. bb.min.x = x;
  4726. } else if ( x > bb.max.x ) {
  4727. bb.max.x = x;
  4728. }
  4729. if ( y < bb.min.y ) {
  4730. bb.min.y = y;
  4731. } else if ( y > bb.max.y ) {
  4732. bb.max.y = y;
  4733. }
  4734. if ( z < bb.min.z ) {
  4735. bb.min.z = z;
  4736. } else if ( z > bb.max.z ) {
  4737. bb.max.z = z;
  4738. }
  4739. }
  4740. }
  4741. if ( positions === undefined || positions.length === 0 ) {
  4742. this.boundingBox.min.set( 0, 0, 0 );
  4743. this.boundingBox.max.set( 0, 0, 0 );
  4744. }
  4745. },
  4746. computeBoundingSphere: function () {
  4747. if ( this.boundingSphere === null ) {
  4748. this.boundingSphere = new THREE.Sphere();
  4749. }
  4750. var positions = this.attributes[ "position" ].array;
  4751. if ( positions ) {
  4752. var radiusSq, maxRadiusSq = 0;
  4753. var x, y, z;
  4754. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  4755. x = positions[ i ];
  4756. y = positions[ i + 1 ];
  4757. z = positions[ i + 2 ];
  4758. radiusSq = x * x + y * y + z * z;
  4759. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  4760. }
  4761. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  4762. }
  4763. },
  4764. computeVertexNormals: function () {
  4765. if ( this.attributes[ "position" ] ) {
  4766. var i, il;
  4767. var j, jl;
  4768. var nVertexElements = this.attributes[ "position" ].array.length;
  4769. if ( this.attributes[ "normal" ] === undefined ) {
  4770. this.attributes[ "normal" ] = {
  4771. itemSize: 3,
  4772. array: new Float32Array( nVertexElements ),
  4773. numItems: nVertexElements
  4774. };
  4775. } else {
  4776. // reset existing normals to zero
  4777. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  4778. this.attributes[ "normal" ].array[ i ] = 0;
  4779. }
  4780. }
  4781. var positions = this.attributes[ "position" ].array;
  4782. var normals = this.attributes[ "normal" ].array;
  4783. var vA, vB, vC, x, y, z,
  4784. pA = new THREE.Vector3(),
  4785. pB = new THREE.Vector3(),
  4786. pC = new THREE.Vector3(),
  4787. cb = new THREE.Vector3(),
  4788. ab = new THREE.Vector3();
  4789. // indexed elements
  4790. if ( this.attributes[ "index" ] ) {
  4791. var indices = this.attributes[ "index" ].array;
  4792. var offsets = this.offsets;
  4793. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  4794. var start = offsets[ j ].start;
  4795. var count = offsets[ j ].count;
  4796. var index = offsets[ j ].index;
  4797. for ( i = start, il = start + count; i < il; i += 3 ) {
  4798. vA = index + indices[ i ];
  4799. vB = index + indices[ i + 1 ];
  4800. vC = index + indices[ i + 2 ];
  4801. x = positions[ vA * 3 ];
  4802. y = positions[ vA * 3 + 1 ];
  4803. z = positions[ vA * 3 + 2 ];
  4804. pA.set( x, y, z );
  4805. x = positions[ vB * 3 ];
  4806. y = positions[ vB * 3 + 1 ];
  4807. z = positions[ vB * 3 + 2 ];
  4808. pB.set( x, y, z );
  4809. x = positions[ vC * 3 ];
  4810. y = positions[ vC * 3 + 1 ];
  4811. z = positions[ vC * 3 + 2 ];
  4812. pC.set( x, y, z );
  4813. cb.subVectors( pC, pB );
  4814. ab.subVectors( pA, pB );
  4815. cb.cross( ab );
  4816. normals[ vA * 3 ] += cb.x;
  4817. normals[ vA * 3 + 1 ] += cb.y;
  4818. normals[ vA * 3 + 2 ] += cb.z;
  4819. normals[ vB * 3 ] += cb.x;
  4820. normals[ vB * 3 + 1 ] += cb.y;
  4821. normals[ vB * 3 + 2 ] += cb.z;
  4822. normals[ vC * 3 ] += cb.x;
  4823. normals[ vC * 3 + 1 ] += cb.y;
  4824. normals[ vC * 3 + 2 ] += cb.z;
  4825. }
  4826. }
  4827. // non-indexed elements (unconnected triangle soup)
  4828. } else {
  4829. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  4830. x = positions[ i ];
  4831. y = positions[ i + 1 ];
  4832. z = positions[ i + 2 ];
  4833. pA.set( x, y, z );
  4834. x = positions[ i + 3 ];
  4835. y = positions[ i + 4 ];
  4836. z = positions[ i + 5 ];
  4837. pB.set( x, y, z );
  4838. x = positions[ i + 6 ];
  4839. y = positions[ i + 7 ];
  4840. z = positions[ i + 8 ];
  4841. pC.set( x, y, z );
  4842. cb.subVectors( pC, pB );
  4843. ab.subVectors( pA, pB );
  4844. cb.cross( ab );
  4845. normals[ i ] = cb.x;
  4846. normals[ i + 1 ] = cb.y;
  4847. normals[ i + 2 ] = cb.z;
  4848. normals[ i + 3 ] = cb.x;
  4849. normals[ i + 4 ] = cb.y;
  4850. normals[ i + 5 ] = cb.z;
  4851. normals[ i + 6 ] = cb.x;
  4852. normals[ i + 7 ] = cb.y;
  4853. normals[ i + 8 ] = cb.z;
  4854. }
  4855. }
  4856. this.normalizeNormals();
  4857. this.normalsNeedUpdate = true;
  4858. }
  4859. },
  4860. normalizeNormals: function () {
  4861. var normals = this.attributes[ "normal" ].array;
  4862. var x, y, z, n;
  4863. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  4864. x = normals[ i ];
  4865. y = normals[ i + 1 ];
  4866. z = normals[ i + 2 ];
  4867. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  4868. normals[ i ] *= n;
  4869. normals[ i + 1 ] *= n;
  4870. normals[ i + 2 ] *= n;
  4871. }
  4872. },
  4873. computeTangents: function () {
  4874. // based on http://www.terathon.com/code/tangent.html
  4875. // (per vertex tangents)
  4876. if ( this.attributes[ "index" ] === undefined ||
  4877. this.attributes[ "position" ] === undefined ||
  4878. this.attributes[ "normal" ] === undefined ||
  4879. this.attributes[ "uv" ] === undefined ) {
  4880. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  4881. return;
  4882. }
  4883. var indices = this.attributes[ "index" ].array;
  4884. var positions = this.attributes[ "position" ].array;
  4885. var normals = this.attributes[ "normal" ].array;
  4886. var uvs = this.attributes[ "uv" ].array;
  4887. var nVertices = positions.length / 3;
  4888. if ( this.attributes[ "tangent" ] === undefined ) {
  4889. var nTangentElements = 4 * nVertices;
  4890. this.attributes[ "tangent" ] = {
  4891. itemSize: 4,
  4892. array: new Float32Array( nTangentElements ),
  4893. numItems: nTangentElements
  4894. };
  4895. }
  4896. var tangents = this.attributes[ "tangent" ].array;
  4897. var tan1 = [], tan2 = [];
  4898. for ( var k = 0; k < nVertices; k ++ ) {
  4899. tan1[ k ] = new THREE.Vector3();
  4900. tan2[ k ] = new THREE.Vector3();
  4901. }
  4902. var xA, yA, zA,
  4903. xB, yB, zB,
  4904. xC, yC, zC,
  4905. uA, vA,
  4906. uB, vB,
  4907. uC, vC,
  4908. x1, x2, y1, y2, z1, z2,
  4909. s1, s2, t1, t2, r;
  4910. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  4911. function handleTriangle( a, b, c ) {
  4912. xA = positions[ a * 3 ];
  4913. yA = positions[ a * 3 + 1 ];
  4914. zA = positions[ a * 3 + 2 ];
  4915. xB = positions[ b * 3 ];
  4916. yB = positions[ b * 3 + 1 ];
  4917. zB = positions[ b * 3 + 2 ];
  4918. xC = positions[ c * 3 ];
  4919. yC = positions[ c * 3 + 1 ];
  4920. zC = positions[ c * 3 + 2 ];
  4921. uA = uvs[ a * 2 ];
  4922. vA = uvs[ a * 2 + 1 ];
  4923. uB = uvs[ b * 2 ];
  4924. vB = uvs[ b * 2 + 1 ];
  4925. uC = uvs[ c * 2 ];
  4926. vC = uvs[ c * 2 + 1 ];
  4927. x1 = xB - xA;
  4928. x2 = xC - xA;
  4929. y1 = yB - yA;
  4930. y2 = yC - yA;
  4931. z1 = zB - zA;
  4932. z2 = zC - zA;
  4933. s1 = uB - uA;
  4934. s2 = uC - uA;
  4935. t1 = vB - vA;
  4936. t2 = vC - vA;
  4937. r = 1.0 / ( s1 * t2 - s2 * t1 );
  4938. sdir.set(
  4939. ( t2 * x1 - t1 * x2 ) * r,
  4940. ( t2 * y1 - t1 * y2 ) * r,
  4941. ( t2 * z1 - t1 * z2 ) * r
  4942. );
  4943. tdir.set(
  4944. ( s1 * x2 - s2 * x1 ) * r,
  4945. ( s1 * y2 - s2 * y1 ) * r,
  4946. ( s1 * z2 - s2 * z1 ) * r
  4947. );
  4948. tan1[ a ].add( sdir );
  4949. tan1[ b ].add( sdir );
  4950. tan1[ c ].add( sdir );
  4951. tan2[ a ].add( tdir );
  4952. tan2[ b ].add( tdir );
  4953. tan2[ c ].add( tdir );
  4954. }
  4955. var i, il;
  4956. var j, jl;
  4957. var iA, iB, iC;
  4958. var offsets = this.offsets;
  4959. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  4960. var start = offsets[ j ].start;
  4961. var count = offsets[ j ].count;
  4962. var index = offsets[ j ].index;
  4963. for ( i = start, il = start + count; i < il; i += 3 ) {
  4964. iA = index + indices[ i ];
  4965. iB = index + indices[ i + 1 ];
  4966. iC = index + indices[ i + 2 ];
  4967. handleTriangle( iA, iB, iC );
  4968. }
  4969. }
  4970. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  4971. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  4972. var w, t, test;
  4973. var nx, ny, nz;
  4974. function handleVertex( v ) {
  4975. n.x = normals[ v * 3 ];
  4976. n.y = normals[ v * 3 + 1 ];
  4977. n.z = normals[ v * 3 + 2 ];
  4978. n2.copy( n );
  4979. t = tan1[ v ];
  4980. // Gram-Schmidt orthogonalize
  4981. tmp.copy( t );
  4982. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  4983. // Calculate handedness
  4984. tmp2.crossVectors( n2, t );
  4985. test = tmp2.dot( tan2[ v ] );
  4986. w = ( test < 0.0 ) ? -1.0 : 1.0;
  4987. tangents[ v * 4 ] = tmp.x;
  4988. tangents[ v * 4 + 1 ] = tmp.y;
  4989. tangents[ v * 4 + 2 ] = tmp.z;
  4990. tangents[ v * 4 + 3 ] = w;
  4991. }
  4992. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  4993. var start = offsets[ j ].start;
  4994. var count = offsets[ j ].count;
  4995. var index = offsets[ j ].index;
  4996. for ( i = start, il = start + count; i < il; i += 3 ) {
  4997. iA = index + indices[ i ];
  4998. iB = index + indices[ i + 1 ];
  4999. iC = index + indices[ i + 2 ];
  5000. handleVertex( iA );
  5001. handleVertex( iB );
  5002. handleVertex( iC );
  5003. }
  5004. }
  5005. this.hasTangents = true;
  5006. this.tangentsNeedUpdate = true;
  5007. },
  5008. dispose: function () {
  5009. this.dispatchEvent( { type: 'dispose' } );
  5010. }
  5011. };
  5012. /**
  5013. * @author mrdoob / http://mrdoob.com/
  5014. * @author mikael emtinger / http://gomo.se/
  5015. */
  5016. THREE.Camera = function () {
  5017. THREE.Object3D.call( this );
  5018. this.matrixWorldInverse = new THREE.Matrix4();
  5019. this.projectionMatrix = new THREE.Matrix4();
  5020. this.projectionMatrixInverse = new THREE.Matrix4();
  5021. };
  5022. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  5023. THREE.Camera.prototype.lookAt = function ( vector ) {
  5024. // TODO: Add hierarchy support.
  5025. this.matrix.lookAt( this.position, vector, this.up );
  5026. if ( this.rotationAutoUpdate === true ) {
  5027. if ( this.useQuaternion === false ) {
  5028. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  5029. } else {
  5030. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  5031. }
  5032. }
  5033. };
  5034. /**
  5035. * @author alteredq / http://alteredqualia.com/
  5036. */
  5037. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  5038. THREE.Camera.call( this );
  5039. this.left = left;
  5040. this.right = right;
  5041. this.top = top;
  5042. this.bottom = bottom;
  5043. this.near = ( near !== undefined ) ? near : 0.1;
  5044. this.far = ( far !== undefined ) ? far : 2000;
  5045. this.updateProjectionMatrix();
  5046. };
  5047. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  5048. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  5049. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  5050. };
  5051. /**
  5052. * @author mrdoob / http://mrdoob.com/
  5053. * @author greggman / http://games.greggman.com/
  5054. * @author zz85 / http://www.lab4games.net/zz85/blog
  5055. */
  5056. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  5057. THREE.Camera.call( this );
  5058. this.fov = fov !== undefined ? fov : 50;
  5059. this.aspect = aspect !== undefined ? aspect : 1;
  5060. this.near = near !== undefined ? near : 0.1;
  5061. this.far = far !== undefined ? far : 2000;
  5062. this.updateProjectionMatrix();
  5063. };
  5064. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  5065. /**
  5066. * Uses Focal Length (in mm) to estimate and set FOV
  5067. * 35mm (fullframe) camera is used if frame size is not specified;
  5068. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  5069. */
  5070. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  5071. if ( frameHeight === undefined ) frameHeight = 24;
  5072. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  5073. this.updateProjectionMatrix();
  5074. }
  5075. /**
  5076. * Sets an offset in a larger frustum. This is useful for multi-window or
  5077. * multi-monitor/multi-machine setups.
  5078. *
  5079. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  5080. * the monitors are in grid like this
  5081. *
  5082. * +---+---+---+
  5083. * | A | B | C |
  5084. * +---+---+---+
  5085. * | D | E | F |
  5086. * +---+---+---+
  5087. *
  5088. * then for each monitor you would call it like this
  5089. *
  5090. * var w = 1920;
  5091. * var h = 1080;
  5092. * var fullWidth = w * 3;
  5093. * var fullHeight = h * 2;
  5094. *
  5095. * --A--
  5096. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  5097. * --B--
  5098. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  5099. * --C--
  5100. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  5101. * --D--
  5102. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  5103. * --E--
  5104. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  5105. * --F--
  5106. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  5107. *
  5108. * Note there is no reason monitors have to be the same size or in a grid.
  5109. */
  5110. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  5111. this.fullWidth = fullWidth;
  5112. this.fullHeight = fullHeight;
  5113. this.x = x;
  5114. this.y = y;
  5115. this.width = width;
  5116. this.height = height;
  5117. this.updateProjectionMatrix();
  5118. };
  5119. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  5120. if ( this.fullWidth ) {
  5121. var aspect = this.fullWidth / this.fullHeight;
  5122. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  5123. var bottom = -top;
  5124. var left = aspect * bottom;
  5125. var right = aspect * top;
  5126. var width = Math.abs( right - left );
  5127. var height = Math.abs( top - bottom );
  5128. this.projectionMatrix.makeFrustum(
  5129. left + this.x * width / this.fullWidth,
  5130. left + ( this.x + this.width ) * width / this.fullWidth,
  5131. top - ( this.y + this.height ) * height / this.fullHeight,
  5132. top - this.y * height / this.fullHeight,
  5133. this.near,
  5134. this.far
  5135. );
  5136. } else {
  5137. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  5138. }
  5139. };
  5140. /**
  5141. * @author mrdoob / http://mrdoob.com/
  5142. * @author alteredq / http://alteredqualia.com/
  5143. */
  5144. THREE.Light = function ( hex ) {
  5145. THREE.Object3D.call( this );
  5146. this.color = new THREE.Color( hex );
  5147. };
  5148. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  5149. /**
  5150. * @author mrdoob / http://mrdoob.com/
  5151. */
  5152. THREE.AmbientLight = function ( hex ) {
  5153. THREE.Light.call( this, hex );
  5154. };
  5155. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  5156. /**
  5157. * @author MPanknin / http://www.redplant.de/
  5158. * @author alteredq / http://alteredqualia.com/
  5159. */
  5160. THREE.AreaLight = function ( hex, intensity ) {
  5161. THREE.Light.call( this, hex );
  5162. this.normal = new THREE.Vector3( 0, -1, 0 );
  5163. this.right = new THREE.Vector3( 1, 0, 0 );
  5164. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5165. this.width = 1.0;
  5166. this.height = 1.0;
  5167. this.constantAttenuation = 1.5;
  5168. this.linearAttenuation = 0.5;
  5169. this.quadraticAttenuation = 0.1;
  5170. };
  5171. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  5172. /**
  5173. * @author mrdoob / http://mrdoob.com/
  5174. * @author alteredq / http://alteredqualia.com/
  5175. */
  5176. THREE.DirectionalLight = function ( hex, intensity ) {
  5177. THREE.Light.call( this, hex );
  5178. this.position = new THREE.Vector3( 0, 1, 0 );
  5179. this.target = new THREE.Object3D();
  5180. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5181. this.castShadow = false;
  5182. this.onlyShadow = false;
  5183. //
  5184. this.shadowCameraNear = 50;
  5185. this.shadowCameraFar = 5000;
  5186. this.shadowCameraLeft = -500;
  5187. this.shadowCameraRight = 500;
  5188. this.shadowCameraTop = 500;
  5189. this.shadowCameraBottom = -500;
  5190. this.shadowCameraVisible = false;
  5191. this.shadowBias = 0;
  5192. this.shadowDarkness = 0.5;
  5193. this.shadowMapWidth = 512;
  5194. this.shadowMapHeight = 512;
  5195. //
  5196. this.shadowCascade = false;
  5197. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  5198. this.shadowCascadeCount = 2;
  5199. this.shadowCascadeBias = [ 0, 0, 0 ];
  5200. this.shadowCascadeWidth = [ 512, 512, 512 ];
  5201. this.shadowCascadeHeight = [ 512, 512, 512 ];
  5202. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  5203. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  5204. this.shadowCascadeArray = [];
  5205. //
  5206. this.shadowMap = null;
  5207. this.shadowMapSize = null;
  5208. this.shadowCamera = null;
  5209. this.shadowMatrix = null;
  5210. };
  5211. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  5212. /**
  5213. * @author alteredq / http://alteredqualia.com/
  5214. */
  5215. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  5216. THREE.Light.call( this, skyColorHex );
  5217. this.groundColor = new THREE.Color( groundColorHex );
  5218. this.position = new THREE.Vector3( 0, 100, 0 );
  5219. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5220. };
  5221. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  5222. /**
  5223. * @author mrdoob / http://mrdoob.com/
  5224. */
  5225. THREE.PointLight = function ( hex, intensity, distance ) {
  5226. THREE.Light.call( this, hex );
  5227. this.position = new THREE.Vector3( 0, 0, 0 );
  5228. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5229. this.distance = ( distance !== undefined ) ? distance : 0;
  5230. };
  5231. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  5232. /**
  5233. * @author alteredq / http://alteredqualia.com/
  5234. */
  5235. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  5236. THREE.Light.call( this, hex );
  5237. this.position = new THREE.Vector3( 0, 1, 0 );
  5238. this.target = new THREE.Object3D();
  5239. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5240. this.distance = ( distance !== undefined ) ? distance : 0;
  5241. this.angle = ( angle !== undefined ) ? angle : Math.PI / 2;
  5242. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  5243. this.castShadow = false;
  5244. this.onlyShadow = false;
  5245. //
  5246. this.shadowCameraNear = 50;
  5247. this.shadowCameraFar = 5000;
  5248. this.shadowCameraFov = 50;
  5249. this.shadowCameraVisible = false;
  5250. this.shadowBias = 0;
  5251. this.shadowDarkness = 0.5;
  5252. this.shadowMapWidth = 512;
  5253. this.shadowMapHeight = 512;
  5254. //
  5255. this.shadowMap = null;
  5256. this.shadowMapSize = null;
  5257. this.shadowCamera = null;
  5258. this.shadowMatrix = null;
  5259. };
  5260. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  5261. /**
  5262. * @author alteredq / http://alteredqualia.com/
  5263. */
  5264. THREE.Loader = function ( showStatus ) {
  5265. this.showStatus = showStatus;
  5266. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  5267. this.onLoadStart = function () {};
  5268. this.onLoadProgress = function () {};
  5269. this.onLoadComplete = function () {};
  5270. };
  5271. THREE.Loader.prototype = {
  5272. constructor: THREE.Loader,
  5273. crossOrigin: 'anonymous',
  5274. addStatusElement: function () {
  5275. var e = document.createElement( "div" );
  5276. e.style.position = "absolute";
  5277. e.style.right = "0px";
  5278. e.style.top = "0px";
  5279. e.style.fontSize = "0.8em";
  5280. e.style.textAlign = "left";
  5281. e.style.background = "rgba(0,0,0,0.25)";
  5282. e.style.color = "#fff";
  5283. e.style.width = "120px";
  5284. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  5285. e.style.zIndex = 1000;
  5286. e.innerHTML = "Loading ...";
  5287. return e;
  5288. },
  5289. updateProgress: function ( progress ) {
  5290. var message = "Loaded ";
  5291. if ( progress.total ) {
  5292. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  5293. } else {
  5294. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  5295. }
  5296. this.statusDomElement.innerHTML = message;
  5297. },
  5298. extractUrlBase: function ( url ) {
  5299. var parts = url.split( '/' );
  5300. parts.pop();
  5301. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  5302. },
  5303. initMaterials: function ( materials, texturePath ) {
  5304. var array = [];
  5305. for ( var i = 0; i < materials.length; ++ i ) {
  5306. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  5307. }
  5308. return array;
  5309. },
  5310. needsTangents: function ( materials ) {
  5311. for( var i = 0, il = materials.length; i < il; i ++ ) {
  5312. var m = materials[ i ];
  5313. if ( m instanceof THREE.ShaderMaterial ) return true;
  5314. }
  5315. return false;
  5316. },
  5317. createMaterial: function ( m, texturePath ) {
  5318. var _this = this;
  5319. function is_pow2( n ) {
  5320. var l = Math.log( n ) / Math.LN2;
  5321. return Math.floor( l ) == l;
  5322. }
  5323. function nearest_pow2( n ) {
  5324. var l = Math.log( n ) / Math.LN2;
  5325. return Math.pow( 2, Math.round( l ) );
  5326. }
  5327. function load_image( where, url ) {
  5328. var image = new Image();
  5329. image.onload = function () {
  5330. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  5331. var width = nearest_pow2( this.width );
  5332. var height = nearest_pow2( this.height );
  5333. where.image.width = width;
  5334. where.image.height = height;
  5335. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  5336. } else {
  5337. where.image = this;
  5338. }
  5339. where.needsUpdate = true;
  5340. };
  5341. image.crossOrigin = _this.crossOrigin;
  5342. image.src = url;
  5343. }
  5344. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  5345. var isCompressed = sourceFile.toLowerCase().endsWith( ".dds" );
  5346. var fullPath = texturePath + "/" + sourceFile;
  5347. if ( isCompressed ) {
  5348. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  5349. where[ name ] = texture;
  5350. } else {
  5351. var texture = document.createElement( 'canvas' );
  5352. where[ name ] = new THREE.Texture( texture );
  5353. }
  5354. where[ name ].sourceFile = sourceFile;
  5355. if( repeat ) {
  5356. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  5357. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  5358. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  5359. }
  5360. if ( offset ) {
  5361. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  5362. }
  5363. if ( wrap ) {
  5364. var wrapMap = {
  5365. "repeat": THREE.RepeatWrapping,
  5366. "mirror": THREE.MirroredRepeatWrapping
  5367. }
  5368. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  5369. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  5370. }
  5371. if ( anisotropy ) {
  5372. where[ name ].anisotropy = anisotropy;
  5373. }
  5374. if ( ! isCompressed ) {
  5375. load_image( where[ name ], fullPath );
  5376. }
  5377. }
  5378. function rgb2hex( rgb ) {
  5379. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  5380. }
  5381. // defaults
  5382. var mtype = "MeshLambertMaterial";
  5383. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  5384. // parameters from model file
  5385. if ( m.shading ) {
  5386. var shading = m.shading.toLowerCase();
  5387. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  5388. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  5389. }
  5390. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  5391. mpars.blending = THREE[ m.blending ];
  5392. }
  5393. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  5394. mpars.transparent = m.transparent;
  5395. }
  5396. if ( m.depthTest !== undefined ) {
  5397. mpars.depthTest = m.depthTest;
  5398. }
  5399. if ( m.depthWrite !== undefined ) {
  5400. mpars.depthWrite = m.depthWrite;
  5401. }
  5402. if ( m.visible !== undefined ) {
  5403. mpars.visible = m.visible;
  5404. }
  5405. if ( m.flipSided !== undefined ) {
  5406. mpars.side = THREE.BackSide;
  5407. }
  5408. if ( m.doubleSided !== undefined ) {
  5409. mpars.side = THREE.DoubleSide;
  5410. }
  5411. if ( m.wireframe !== undefined ) {
  5412. mpars.wireframe = m.wireframe;
  5413. }
  5414. if ( m.vertexColors !== undefined ) {
  5415. if ( m.vertexColors === "face" ) {
  5416. mpars.vertexColors = THREE.FaceColors;
  5417. } else if ( m.vertexColors ) {
  5418. mpars.vertexColors = THREE.VertexColors;
  5419. }
  5420. }
  5421. // colors
  5422. if ( m.colorDiffuse ) {
  5423. mpars.color = rgb2hex( m.colorDiffuse );
  5424. } else if ( m.DbgColor ) {
  5425. mpars.color = m.DbgColor;
  5426. }
  5427. if ( m.colorSpecular ) {
  5428. mpars.specular = rgb2hex( m.colorSpecular );
  5429. }
  5430. if ( m.colorAmbient ) {
  5431. mpars.ambient = rgb2hex( m.colorAmbient );
  5432. }
  5433. // modifiers
  5434. if ( m.transparency ) {
  5435. mpars.opacity = m.transparency;
  5436. }
  5437. if ( m.specularCoef ) {
  5438. mpars.shininess = m.specularCoef;
  5439. }
  5440. // textures
  5441. if ( m.mapDiffuse && texturePath ) {
  5442. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  5443. }
  5444. if ( m.mapLight && texturePath ) {
  5445. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  5446. }
  5447. if ( m.mapBump && texturePath ) {
  5448. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  5449. }
  5450. if ( m.mapNormal && texturePath ) {
  5451. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  5452. }
  5453. if ( m.mapSpecular && texturePath ) {
  5454. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  5455. }
  5456. //
  5457. if ( m.mapBumpScale ) {
  5458. mpars.bumpScale = m.mapBumpScale;
  5459. }
  5460. // special case for normal mapped material
  5461. if ( m.mapNormal ) {
  5462. var shader = THREE.ShaderUtils.lib[ "normal" ];
  5463. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5464. uniforms[ "tNormal" ].value = mpars.normalMap;
  5465. if ( m.mapNormalFactor ) {
  5466. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  5467. }
  5468. if ( mpars.map ) {
  5469. uniforms[ "tDiffuse" ].value = mpars.map;
  5470. uniforms[ "enableDiffuse" ].value = true;
  5471. }
  5472. if ( mpars.specularMap ) {
  5473. uniforms[ "tSpecular" ].value = mpars.specularMap;
  5474. uniforms[ "enableSpecular" ].value = true;
  5475. }
  5476. if ( mpars.lightMap ) {
  5477. uniforms[ "tAO" ].value = mpars.lightMap;
  5478. uniforms[ "enableAO" ].value = true;
  5479. }
  5480. // for the moment don't handle displacement texture
  5481. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  5482. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  5483. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  5484. uniforms[ "uShininess" ].value = mpars.shininess;
  5485. if ( mpars.opacity !== undefined ) {
  5486. uniforms[ "uOpacity" ].value = mpars.opacity;
  5487. }
  5488. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5489. var material = new THREE.ShaderMaterial( parameters );
  5490. if ( mpars.transparent ) {
  5491. material.transparent = true;
  5492. }
  5493. } else {
  5494. var material = new THREE[ mtype ]( mpars );
  5495. }
  5496. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  5497. return material;
  5498. }
  5499. };
  5500. /**
  5501. * @author mrdoob / http://mrdoob.com/
  5502. */
  5503. THREE.ImageLoader = function () {
  5504. THREE.EventDispatcher.call( this );
  5505. this.crossOrigin = null;
  5506. };
  5507. THREE.ImageLoader.prototype = {
  5508. constructor: THREE.ImageLoader,
  5509. load: function ( url, image ) {
  5510. var scope = this;
  5511. if ( image === undefined ) image = new Image();
  5512. image.addEventListener( 'load', function () {
  5513. scope.dispatchEvent( { type: 'load', content: image } );
  5514. }, false );
  5515. image.addEventListener( 'error', function () {
  5516. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  5517. }, false );
  5518. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  5519. image.src = url;
  5520. }
  5521. }
  5522. /**
  5523. * @author mrdoob / http://mrdoob.com/
  5524. * @author alteredq / http://alteredqualia.com/
  5525. */
  5526. THREE.JSONLoader = function ( showStatus ) {
  5527. THREE.Loader.call( this, showStatus );
  5528. this.withCredentials = false;
  5529. };
  5530. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  5531. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  5532. var scope = this;
  5533. // todo: unify load API to for easier SceneLoader use
  5534. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  5535. this.onLoadStart();
  5536. this.loadAjaxJSON( this, url, callback, texturePath );
  5537. };
  5538. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  5539. var xhr = new XMLHttpRequest();
  5540. var length = 0;
  5541. xhr.withCredentials = this.withCredentials;
  5542. xhr.onreadystatechange = function () {
  5543. if ( xhr.readyState === xhr.DONE ) {
  5544. if ( xhr.status === 200 || xhr.status === 0 ) {
  5545. if ( xhr.responseText ) {
  5546. var json = JSON.parse( xhr.responseText );
  5547. context.createModel( json, callback, texturePath );
  5548. } else {
  5549. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  5550. }
  5551. // in context of more complex asset initialization
  5552. // do not block on single failed file
  5553. // maybe should go even one more level up
  5554. context.onLoadComplete();
  5555. } else {
  5556. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5557. }
  5558. } else if ( xhr.readyState === xhr.LOADING ) {
  5559. if ( callbackProgress ) {
  5560. if ( length === 0 ) {
  5561. length = xhr.getResponseHeader( "Content-Length" );
  5562. }
  5563. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  5564. }
  5565. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  5566. length = xhr.getResponseHeader( "Content-Length" );
  5567. }
  5568. };
  5569. xhr.open( "GET", url, true );
  5570. xhr.send( null );
  5571. };
  5572. THREE.JSONLoader.prototype.createModel = function ( json, callback, texturePath ) {
  5573. var scope = this,
  5574. geometry = new THREE.Geometry(),
  5575. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  5576. parseModel( scale );
  5577. parseSkin();
  5578. parseMorphing( scale );
  5579. geometry.computeCentroids();
  5580. geometry.computeFaceNormals();
  5581. function parseModel( scale ) {
  5582. function isBitSet( value, position ) {
  5583. return value & ( 1 << position );
  5584. }
  5585. var i, j, fi,
  5586. offset, zLength, nVertices,
  5587. colorIndex, normalIndex, uvIndex, materialIndex,
  5588. type,
  5589. isQuad,
  5590. hasMaterial,
  5591. hasFaceUv, hasFaceVertexUv,
  5592. hasFaceNormal, hasFaceVertexNormal,
  5593. hasFaceColor, hasFaceVertexColor,
  5594. vertex, face, color, normal,
  5595. uvLayer, uvs, u, v,
  5596. faces = json.faces,
  5597. vertices = json.vertices,
  5598. normals = json.normals,
  5599. colors = json.colors,
  5600. nUvLayers = 0;
  5601. // disregard empty arrays
  5602. for ( i = 0; i < json.uvs.length; i++ ) {
  5603. if ( json.uvs[ i ].length ) nUvLayers ++;
  5604. }
  5605. for ( i = 0; i < nUvLayers; i++ ) {
  5606. geometry.faceUvs[ i ] = [];
  5607. geometry.faceVertexUvs[ i ] = [];
  5608. }
  5609. offset = 0;
  5610. zLength = vertices.length;
  5611. while ( offset < zLength ) {
  5612. vertex = new THREE.Vector3();
  5613. vertex.x = vertices[ offset ++ ] * scale;
  5614. vertex.y = vertices[ offset ++ ] * scale;
  5615. vertex.z = vertices[ offset ++ ] * scale;
  5616. geometry.vertices.push( vertex );
  5617. }
  5618. offset = 0;
  5619. zLength = faces.length;
  5620. while ( offset < zLength ) {
  5621. type = faces[ offset ++ ];
  5622. isQuad = isBitSet( type, 0 );
  5623. hasMaterial = isBitSet( type, 1 );
  5624. hasFaceUv = isBitSet( type, 2 );
  5625. hasFaceVertexUv = isBitSet( type, 3 );
  5626. hasFaceNormal = isBitSet( type, 4 );
  5627. hasFaceVertexNormal = isBitSet( type, 5 );
  5628. hasFaceColor = isBitSet( type, 6 );
  5629. hasFaceVertexColor = isBitSet( type, 7 );
  5630. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  5631. if ( isQuad ) {
  5632. face = new THREE.Face4();
  5633. face.a = faces[ offset ++ ];
  5634. face.b = faces[ offset ++ ];
  5635. face.c = faces[ offset ++ ];
  5636. face.d = faces[ offset ++ ];
  5637. nVertices = 4;
  5638. } else {
  5639. face = new THREE.Face3();
  5640. face.a = faces[ offset ++ ];
  5641. face.b = faces[ offset ++ ];
  5642. face.c = faces[ offset ++ ];
  5643. nVertices = 3;
  5644. }
  5645. if ( hasMaterial ) {
  5646. materialIndex = faces[ offset ++ ];
  5647. face.materialIndex = materialIndex;
  5648. }
  5649. // to get face <=> uv index correspondence
  5650. fi = geometry.faces.length;
  5651. if ( hasFaceUv ) {
  5652. for ( i = 0; i < nUvLayers; i++ ) {
  5653. uvLayer = json.uvs[ i ];
  5654. uvIndex = faces[ offset ++ ];
  5655. u = uvLayer[ uvIndex * 2 ];
  5656. v = uvLayer[ uvIndex * 2 + 1 ];
  5657. geometry.faceUvs[ i ][ fi ] = new THREE.Vector2( u, v );
  5658. }
  5659. }
  5660. if ( hasFaceVertexUv ) {
  5661. for ( i = 0; i < nUvLayers; i++ ) {
  5662. uvLayer = json.uvs[ i ];
  5663. uvs = [];
  5664. for ( j = 0; j < nVertices; j ++ ) {
  5665. uvIndex = faces[ offset ++ ];
  5666. u = uvLayer[ uvIndex * 2 ];
  5667. v = uvLayer[ uvIndex * 2 + 1 ];
  5668. uvs[ j ] = new THREE.Vector2( u, v );
  5669. }
  5670. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  5671. }
  5672. }
  5673. if ( hasFaceNormal ) {
  5674. normalIndex = faces[ offset ++ ] * 3;
  5675. normal = new THREE.Vector3();
  5676. normal.x = normals[ normalIndex ++ ];
  5677. normal.y = normals[ normalIndex ++ ];
  5678. normal.z = normals[ normalIndex ];
  5679. face.normal = normal;
  5680. }
  5681. if ( hasFaceVertexNormal ) {
  5682. for ( i = 0; i < nVertices; i++ ) {
  5683. normalIndex = faces[ offset ++ ] * 3;
  5684. normal = new THREE.Vector3();
  5685. normal.x = normals[ normalIndex ++ ];
  5686. normal.y = normals[ normalIndex ++ ];
  5687. normal.z = normals[ normalIndex ];
  5688. face.vertexNormals.push( normal );
  5689. }
  5690. }
  5691. if ( hasFaceColor ) {
  5692. colorIndex = faces[ offset ++ ];
  5693. color = new THREE.Color( colors[ colorIndex ] );
  5694. face.color = color;
  5695. }
  5696. if ( hasFaceVertexColor ) {
  5697. for ( i = 0; i < nVertices; i++ ) {
  5698. colorIndex = faces[ offset ++ ];
  5699. color = new THREE.Color( colors[ colorIndex ] );
  5700. face.vertexColors.push( color );
  5701. }
  5702. }
  5703. geometry.faces.push( face );
  5704. }
  5705. };
  5706. function parseSkin() {
  5707. var i, l, x, y, z, w, a, b, c, d;
  5708. if ( json.skinWeights ) {
  5709. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  5710. x = json.skinWeights[ i ];
  5711. y = json.skinWeights[ i + 1 ];
  5712. z = 0;
  5713. w = 0;
  5714. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  5715. }
  5716. }
  5717. if ( json.skinIndices ) {
  5718. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  5719. a = json.skinIndices[ i ];
  5720. b = json.skinIndices[ i + 1 ];
  5721. c = 0;
  5722. d = 0;
  5723. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  5724. }
  5725. }
  5726. geometry.bones = json.bones;
  5727. geometry.animation = json.animation;
  5728. };
  5729. function parseMorphing( scale ) {
  5730. if ( json.morphTargets !== undefined ) {
  5731. var i, l, v, vl, dstVertices, srcVertices;
  5732. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  5733. geometry.morphTargets[ i ] = {};
  5734. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  5735. geometry.morphTargets[ i ].vertices = [];
  5736. dstVertices = geometry.morphTargets[ i ].vertices;
  5737. srcVertices = json.morphTargets [ i ].vertices;
  5738. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  5739. var vertex = new THREE.Vector3();
  5740. vertex.x = srcVertices[ v ] * scale;
  5741. vertex.y = srcVertices[ v + 1 ] * scale;
  5742. vertex.z = srcVertices[ v + 2 ] * scale;
  5743. dstVertices.push( vertex );
  5744. }
  5745. }
  5746. }
  5747. if ( json.morphColors !== undefined ) {
  5748. var i, l, c, cl, dstColors, srcColors, color;
  5749. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  5750. geometry.morphColors[ i ] = {};
  5751. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  5752. geometry.morphColors[ i ].colors = [];
  5753. dstColors = geometry.morphColors[ i ].colors;
  5754. srcColors = json.morphColors [ i ].colors;
  5755. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  5756. color = new THREE.Color( 0xffaa00 );
  5757. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  5758. dstColors.push( color );
  5759. }
  5760. }
  5761. }
  5762. };
  5763. var materials = this.initMaterials( json.materials, texturePath );
  5764. if ( this.needsTangents( materials ) ) geometry.computeTangents();
  5765. callback( geometry, materials );
  5766. };
  5767. /**
  5768. * @author mrdoob / http://mrdoob.com/
  5769. */
  5770. THREE.LoadingMonitor = function () {
  5771. THREE.EventDispatcher.call( this );
  5772. var scope = this;
  5773. var loaded = 0;
  5774. var total = 0;
  5775. var onLoad = function ( event ) {
  5776. loaded ++;
  5777. scope.dispatchEvent( { type: 'progress', loaded: loaded, total: total } );
  5778. if ( loaded === total ) {
  5779. scope.dispatchEvent( { type: 'load' } );
  5780. }
  5781. };
  5782. this.add = function ( loader ) {
  5783. total ++;
  5784. loader.addEventListener( 'load', onLoad, false );
  5785. };
  5786. };
  5787. /**
  5788. * @author alteredq / http://alteredqualia.com/
  5789. */
  5790. THREE.SceneLoader = function () {
  5791. this.onLoadStart = function () {};
  5792. this.onLoadProgress = function() {};
  5793. this.onLoadComplete = function () {};
  5794. this.callbackSync = function () {};
  5795. this.callbackProgress = function () {};
  5796. this.geometryHandlerMap = {};
  5797. this.hierarchyHandlerMap = {};
  5798. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  5799. };
  5800. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  5801. THREE.SceneLoader.prototype.load = function ( url, callbackFinished ) {
  5802. var scope = this;
  5803. var xhr = new XMLHttpRequest();
  5804. xhr.onreadystatechange = function () {
  5805. if ( xhr.readyState === 4 ) {
  5806. if ( xhr.status === 200 || xhr.status === 0 ) {
  5807. var json = JSON.parse( xhr.responseText );
  5808. scope.parse( json, callbackFinished, url );
  5809. } else {
  5810. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5811. }
  5812. }
  5813. };
  5814. xhr.open( "GET", url, true );
  5815. xhr.send( null );
  5816. };
  5817. THREE.SceneLoader.prototype.addGeometryHandler = function ( typeID, loaderClass ) {
  5818. this.geometryHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5819. };
  5820. THREE.SceneLoader.prototype.addHierarchyHandler = function ( typeID, loaderClass ) {
  5821. this.hierarchyHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5822. };
  5823. THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
  5824. var scope = this;
  5825. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  5826. var geometry, material, camera, fog,
  5827. texture, images, color,
  5828. light, hex, intensity,
  5829. counter_models, counter_textures,
  5830. total_models, total_textures,
  5831. result;
  5832. var target_array = [];
  5833. var data = json;
  5834. // async geometry loaders
  5835. for ( var typeID in this.geometryHandlerMap ) {
  5836. var loaderClass = this.geometryHandlerMap[ typeID ][ "loaderClass" ];
  5837. this.geometryHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5838. }
  5839. // async hierachy loaders
  5840. for ( var typeID in this.hierarchyHandlerMap ) {
  5841. var loaderClass = this.hierarchyHandlerMap[ typeID ][ "loaderClass" ];
  5842. this.hierarchyHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5843. }
  5844. counter_models = 0;
  5845. counter_textures = 0;
  5846. result = {
  5847. scene: new THREE.Scene(),
  5848. geometries: {},
  5849. face_materials: {},
  5850. materials: {},
  5851. textures: {},
  5852. objects: {},
  5853. cameras: {},
  5854. lights: {},
  5855. fogs: {},
  5856. empties: {}
  5857. };
  5858. if ( data.transform ) {
  5859. var position = data.transform.position,
  5860. rotation = data.transform.rotation,
  5861. scale = data.transform.scale;
  5862. if ( position )
  5863. result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
  5864. if ( rotation )
  5865. result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
  5866. if ( scale )
  5867. result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
  5868. if ( position || rotation || scale ) {
  5869. result.scene.updateMatrix();
  5870. result.scene.updateMatrixWorld();
  5871. }
  5872. }
  5873. function get_url( source_url, url_type ) {
  5874. if ( url_type == "relativeToHTML" ) {
  5875. return source_url;
  5876. } else {
  5877. return urlBase + "/" + source_url;
  5878. }
  5879. };
  5880. // toplevel loader function, delegates to handle_children
  5881. function handle_objects() {
  5882. handle_children( result.scene, data.objects );
  5883. }
  5884. // handle all the children from the loaded json and attach them to given parent
  5885. function handle_children( parent, children ) {
  5886. var mat, dst, pos, rot, scl, quat;
  5887. for ( var objID in children ) {
  5888. // check by id if child has already been handled,
  5889. // if not, create new object
  5890. if ( result.objects[ objID ] === undefined ) {
  5891. var objJSON = children[ objID ];
  5892. var object = null;
  5893. // meshes
  5894. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlerMap ) ) {
  5895. if ( objJSON.loading === undefined ) {
  5896. var reservedTypes = { "type": 1, "url": 1, "material": 1,
  5897. "position": 1, "rotation": 1, "scale" : 1,
  5898. "visible": 1, "children": 1, "properties": 1,
  5899. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1 };
  5900. var loaderParameters = {};
  5901. for ( var parType in objJSON ) {
  5902. if ( ! ( parType in reservedTypes ) ) {
  5903. loaderParameters[ parType ] = objJSON[ parType ];
  5904. }
  5905. }
  5906. material = result.materials[ objJSON.material ];
  5907. objJSON.loading = true;
  5908. var loader = scope.hierarchyHandlerMap[ objJSON.type ][ "loaderObject" ];
  5909. // ColladaLoader
  5910. if ( loader.options ) {
  5911. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  5912. // UTF8Loader
  5913. // OBJLoader
  5914. } else {
  5915. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  5916. }
  5917. }
  5918. } else if ( objJSON.geometry !== undefined ) {
  5919. geometry = result.geometries[ objJSON.geometry ];
  5920. // geometry already loaded
  5921. if ( geometry ) {
  5922. var needsTangents = false;
  5923. material = result.materials[ objJSON.material ];
  5924. needsTangents = material instanceof THREE.ShaderMaterial;
  5925. pos = objJSON.position;
  5926. rot = objJSON.rotation;
  5927. scl = objJSON.scale;
  5928. mat = objJSON.matrix;
  5929. quat = objJSON.quaternion;
  5930. // use materials from the model file
  5931. // if there is no material specified in the object
  5932. if ( ! objJSON.material ) {
  5933. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  5934. }
  5935. // use materials from the model file
  5936. // if there is just empty face material
  5937. // (must create new material as each model has its own face material)
  5938. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  5939. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  5940. }
  5941. if ( material instanceof THREE.MeshFaceMaterial ) {
  5942. for ( var i = 0; i < material.materials.length; i ++ ) {
  5943. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  5944. }
  5945. }
  5946. if ( needsTangents ) {
  5947. geometry.computeTangents();
  5948. }
  5949. if ( objJSON.skin ) {
  5950. object = new THREE.SkinnedMesh( geometry, material );
  5951. } else if ( objJSON.morph ) {
  5952. object = new THREE.MorphAnimMesh( geometry, material );
  5953. if ( objJSON.duration !== undefined ) {
  5954. object.duration = objJSON.duration;
  5955. }
  5956. if ( objJSON.time !== undefined ) {
  5957. object.time = objJSON.time;
  5958. }
  5959. if ( objJSON.mirroredLoop !== undefined ) {
  5960. object.mirroredLoop = objJSON.mirroredLoop;
  5961. }
  5962. if ( material.morphNormals ) {
  5963. geometry.computeMorphNormals();
  5964. }
  5965. } else {
  5966. object = new THREE.Mesh( geometry, material );
  5967. }
  5968. object.name = objID;
  5969. if ( mat ) {
  5970. object.matrixAutoUpdate = false;
  5971. object.matrix.set(
  5972. mat[0], mat[1], mat[2], mat[3],
  5973. mat[4], mat[5], mat[6], mat[7],
  5974. mat[8], mat[9], mat[10], mat[11],
  5975. mat[12], mat[13], mat[14], mat[15]
  5976. );
  5977. } else {
  5978. object.position.set( pos[0], pos[1], pos[2] );
  5979. if ( quat ) {
  5980. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  5981. object.useQuaternion = true;
  5982. } else {
  5983. object.rotation.set( rot[0], rot[1], rot[2] );
  5984. }
  5985. object.scale.set( scl[0], scl[1], scl[2] );
  5986. }
  5987. object.visible = objJSON.visible;
  5988. object.castShadow = objJSON.castShadow;
  5989. object.receiveShadow = objJSON.receiveShadow;
  5990. parent.add( object );
  5991. result.objects[ objID ] = object;
  5992. }
  5993. // lights
  5994. } else if ( objJSON.type === "DirectionalLight" || objJSON.type === "PointLight" || objJSON.type === "AmbientLight" ) {
  5995. hex = ( objJSON.color !== undefined ) ? objJSON.color : 0xffffff;
  5996. intensity = ( objJSON.intensity !== undefined ) ? objJSON.intensity : 1;
  5997. if ( objJSON.type === "DirectionalLight" ) {
  5998. pos = objJSON.direction;
  5999. light = new THREE.DirectionalLight( hex, intensity );
  6000. light.position.set( pos[0], pos[1], pos[2] );
  6001. if ( objJSON.target ) {
  6002. target_array.push( { "object": light, "targetName" : objJSON.target } );
  6003. // kill existing default target
  6004. // otherwise it gets added to scene when parent gets added
  6005. light.target = null;
  6006. }
  6007. } else if ( objJSON.type === "PointLight" ) {
  6008. pos = objJSON.position;
  6009. dst = objJSON.distance;
  6010. light = new THREE.PointLight( hex, intensity, dst );
  6011. light.position.set( pos[0], pos[1], pos[2] );
  6012. } else if ( objJSON.type === "AmbientLight" ) {
  6013. light = new THREE.AmbientLight( hex );
  6014. }
  6015. parent.add( light );
  6016. light.name = objID;
  6017. result.lights[ objID ] = light;
  6018. result.objects[ objID ] = light;
  6019. // cameras
  6020. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  6021. if ( objJSON.type === "PerspectiveCamera" ) {
  6022. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  6023. } else if ( objJSON.type === "OrthographicCamera" ) {
  6024. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  6025. }
  6026. pos = objJSON.position;
  6027. camera.position.set( pos[0], pos[1], pos[2] );
  6028. parent.add( camera );
  6029. camera.name = objID;
  6030. result.cameras[ objID ] = camera;
  6031. result.objects[ objID ] = camera;
  6032. // pure Object3D
  6033. } else {
  6034. pos = objJSON.position;
  6035. rot = objJSON.rotation;
  6036. scl = objJSON.scale;
  6037. quat = objJSON.quaternion;
  6038. object = new THREE.Object3D();
  6039. object.name = objID;
  6040. object.position.set( pos[0], pos[1], pos[2] );
  6041. if ( quat ) {
  6042. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  6043. object.useQuaternion = true;
  6044. } else {
  6045. object.rotation.set( rot[0], rot[1], rot[2] );
  6046. }
  6047. object.scale.set( scl[0], scl[1], scl[2] );
  6048. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  6049. parent.add( object );
  6050. result.objects[ objID ] = object;
  6051. result.empties[ objID ] = object;
  6052. }
  6053. if ( object ) {
  6054. if ( objJSON.properties !== undefined ) {
  6055. for ( var key in objJSON.properties ) {
  6056. var value = objJSON.properties[ key ];
  6057. object.properties[ key ] = value;
  6058. }
  6059. }
  6060. if ( objJSON.children !== undefined ) {
  6061. handle_children( object, objJSON.children );
  6062. }
  6063. }
  6064. }
  6065. }
  6066. };
  6067. function handle_mesh( geo, mat, id ) {
  6068. result.geometries[ id ] = geo;
  6069. result.face_materials[ id ] = mat;
  6070. handle_objects();
  6071. };
  6072. function handle_hierarchy( node, id, parent, material, obj ) {
  6073. var p = obj.position;
  6074. var r = obj.rotation;
  6075. var q = obj.quaternion;
  6076. var s = obj.scale;
  6077. node.position.set( p[0], p[1], p[2] );
  6078. if ( q ) {
  6079. node.quaternion.set( q[0], q[1], q[2], q[3] );
  6080. node.useQuaternion = true;
  6081. } else {
  6082. node.rotation.set( r[0], r[1], r[2] );
  6083. }
  6084. node.scale.set( s[0], s[1], s[2] );
  6085. // override children materials
  6086. // if object material was specified in JSON explicitly
  6087. if ( material ) {
  6088. node.traverse( function ( child ) {
  6089. child.material = material;
  6090. } );
  6091. }
  6092. // override children visibility
  6093. // with root node visibility as specified in JSON
  6094. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  6095. node.traverse( function ( child ) {
  6096. child.visible = visible;
  6097. } );
  6098. parent.add( node );
  6099. node.name = id;
  6100. result.objects[ id ] = node;
  6101. handle_objects();
  6102. };
  6103. function create_callback_geometry( id ) {
  6104. return function( geo, mat ) {
  6105. handle_mesh( geo, mat, id );
  6106. counter_models -= 1;
  6107. scope.onLoadComplete();
  6108. async_callback_gate();
  6109. }
  6110. };
  6111. function create_callback_hierachy( id, parent, material, obj ) {
  6112. return function( event ) {
  6113. var result;
  6114. // loaders which use EventDispatcher
  6115. if ( event.content ) {
  6116. result = event.content;
  6117. // ColladaLoader
  6118. } else if ( event.dae ) {
  6119. result = event.scene;
  6120. // UTF8Loader
  6121. } else {
  6122. result = event;
  6123. }
  6124. handle_hierarchy( result, id, parent, material, obj );
  6125. counter_models -= 1;
  6126. scope.onLoadComplete();
  6127. async_callback_gate();
  6128. }
  6129. };
  6130. function create_callback_embed( id ) {
  6131. return function( geo, mat ) {
  6132. result.geometries[ id ] = geo;
  6133. result.face_materials[ id ] = mat;
  6134. }
  6135. };
  6136. function async_callback_gate() {
  6137. var progress = {
  6138. totalModels : total_models,
  6139. totalTextures : total_textures,
  6140. loadedModels : total_models - counter_models,
  6141. loadedTextures : total_textures - counter_textures
  6142. };
  6143. scope.callbackProgress( progress, result );
  6144. scope.onLoadProgress();
  6145. if ( counter_models === 0 && counter_textures === 0 ) {
  6146. finalize();
  6147. callbackFinished( result );
  6148. }
  6149. };
  6150. function finalize() {
  6151. // take care of targets which could be asynchronously loaded objects
  6152. for ( var i = 0; i < target_array.length; i ++ ) {
  6153. var ta = target_array[ i ];
  6154. var target = result.objects[ ta.targetName ];
  6155. if ( target ) {
  6156. ta.object.target = target;
  6157. } else {
  6158. // if there was error and target of specified name doesn't exist in the scene file
  6159. // create instead dummy target
  6160. // (target must be added to scene explicitly as parent is already added)
  6161. ta.object.target = new THREE.Object3D();
  6162. result.scene.add( ta.object.target );
  6163. }
  6164. ta.object.target.properties.targetInverse = ta.object;
  6165. }
  6166. };
  6167. var callbackTexture = function ( count ) {
  6168. counter_textures -= count;
  6169. async_callback_gate();
  6170. scope.onLoadComplete();
  6171. };
  6172. // must use this instead of just directly calling callbackTexture
  6173. // because of closure in the calling context loop
  6174. var generateTextureCallback = function ( count ) {
  6175. return function() {
  6176. callbackTexture( count );
  6177. };
  6178. };
  6179. // first go synchronous elements
  6180. // fogs
  6181. var fogID, fogJSON;
  6182. for ( fogID in data.fogs ) {
  6183. fogJSON = data.fogs[ fogID ];
  6184. if ( fogJSON.type === "linear" ) {
  6185. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  6186. } else if ( fogJSON.type === "exp2" ) {
  6187. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  6188. }
  6189. color = fogJSON.color;
  6190. fog.color.setRGB( color[0], color[1], color[2] );
  6191. result.fogs[ fogID ] = fog;
  6192. }
  6193. // now come potentially asynchronous elements
  6194. // geometries
  6195. // count how many geometries will be loaded asynchronously
  6196. var geoID, geoJSON;
  6197. for ( geoID in data.geometries ) {
  6198. geoJSON = data.geometries[ geoID ];
  6199. if ( geoJSON.type in this.geometryHandlerMap ) {
  6200. counter_models += 1;
  6201. scope.onLoadStart();
  6202. }
  6203. }
  6204. // count how many hierarchies will be loaded asynchronously
  6205. var objID, objJSON;
  6206. for ( objID in data.objects ) {
  6207. objJSON = data.objects[ objID ];
  6208. if ( objJSON.type && ( objJSON.type in this.hierarchyHandlerMap ) ) {
  6209. counter_models += 1;
  6210. scope.onLoadStart();
  6211. }
  6212. }
  6213. total_models = counter_models;
  6214. for ( geoID in data.geometries ) {
  6215. geoJSON = data.geometries[ geoID ];
  6216. if ( geoJSON.type === "cube" ) {
  6217. geometry = new THREE.CubeGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  6218. result.geometries[ geoID ] = geometry;
  6219. } else if ( geoJSON.type === "plane" ) {
  6220. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  6221. result.geometries[ geoID ] = geometry;
  6222. } else if ( geoJSON.type === "sphere" ) {
  6223. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  6224. result.geometries[ geoID ] = geometry;
  6225. } else if ( geoJSON.type === "cylinder" ) {
  6226. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  6227. result.geometries[ geoID ] = geometry;
  6228. } else if ( geoJSON.type === "torus" ) {
  6229. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  6230. result.geometries[ geoID ] = geometry;
  6231. } else if ( geoJSON.type === "icosahedron" ) {
  6232. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  6233. result.geometries[ geoID ] = geometry;
  6234. } else if ( geoJSON.type in this.geometryHandlerMap ) {
  6235. var loaderParameters = {};
  6236. for ( var parType in geoJSON ) {
  6237. if ( parType !== "type" && parType !== "url" ) {
  6238. loaderParameters[ parType ] = geoJSON[ parType ];
  6239. }
  6240. }
  6241. var loader = this.geometryHandlerMap[ geoJSON.type ][ "loaderObject" ];
  6242. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  6243. } else if ( geoJSON.type === "embedded" ) {
  6244. var modelJson = data.embeds[ geoJSON.id ],
  6245. texture_path = "";
  6246. // pass metadata along to jsonLoader so it knows the format version
  6247. modelJson.metadata = data.metadata;
  6248. if ( modelJson ) {
  6249. var jsonLoader = this.geometryHandlerMap[ "ascii" ][ "loaderObject" ];
  6250. jsonLoader.createModel( modelJson, create_callback_embed( geoID ), texture_path );
  6251. }
  6252. }
  6253. }
  6254. // textures
  6255. // count how many textures will be loaded asynchronously
  6256. var textureID, textureJSON;
  6257. for ( textureID in data.textures ) {
  6258. textureJSON = data.textures[ textureID ];
  6259. if ( textureJSON.url instanceof Array ) {
  6260. counter_textures += textureJSON.url.length;
  6261. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  6262. scope.onLoadStart();
  6263. }
  6264. } else {
  6265. counter_textures += 1;
  6266. scope.onLoadStart();
  6267. }
  6268. }
  6269. total_textures = counter_textures;
  6270. for ( textureID in data.textures ) {
  6271. textureJSON = data.textures[ textureID ];
  6272. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  6273. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  6274. }
  6275. if ( textureJSON.url instanceof Array ) {
  6276. var count = textureJSON.url.length;
  6277. var url_array = [];
  6278. for( var i = 0; i < count; i ++ ) {
  6279. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  6280. }
  6281. var isCompressed = url_array[ 0 ].endsWith( ".dds" );
  6282. if ( isCompressed ) {
  6283. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6284. } else {
  6285. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6286. }
  6287. } else {
  6288. var isCompressed = textureJSON.url.toLowerCase().endsWith( ".dds" );
  6289. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  6290. var textureCallback = generateTextureCallback( 1 );
  6291. if ( isCompressed ) {
  6292. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  6293. } else {
  6294. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  6295. }
  6296. if ( THREE[ textureJSON.minFilter ] !== undefined )
  6297. texture.minFilter = THREE[ textureJSON.minFilter ];
  6298. if ( THREE[ textureJSON.magFilter ] !== undefined )
  6299. texture.magFilter = THREE[ textureJSON.magFilter ];
  6300. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  6301. if ( textureJSON.repeat ) {
  6302. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  6303. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  6304. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  6305. }
  6306. if ( textureJSON.offset ) {
  6307. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  6308. }
  6309. // handle wrap after repeat so that default repeat can be overriden
  6310. if ( textureJSON.wrap ) {
  6311. var wrapMap = {
  6312. "repeat" : THREE.RepeatWrapping,
  6313. "mirror" : THREE.MirroredRepeatWrapping
  6314. }
  6315. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  6316. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  6317. }
  6318. }
  6319. result.textures[ textureID ] = texture;
  6320. }
  6321. // materials
  6322. var matID, matJSON;
  6323. var parID;
  6324. for ( matID in data.materials ) {
  6325. matJSON = data.materials[ matID ];
  6326. for ( parID in matJSON.parameters ) {
  6327. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  6328. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  6329. } else if ( parID === "shading" ) {
  6330. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  6331. } else if ( parID === "side" ) {
  6332. if ( matJSON.parameters[ parID ] == "double" ) {
  6333. matJSON.parameters[ parID ] = THREE.DoubleSide;
  6334. } else if ( matJSON.parameters[ parID ] == "back" ) {
  6335. matJSON.parameters[ parID ] = THREE.BackSide;
  6336. } else {
  6337. matJSON.parameters[ parID ] = THREE.FrontSide;
  6338. }
  6339. } else if ( parID === "blending" ) {
  6340. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  6341. } else if ( parID === "combine" ) {
  6342. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  6343. } else if ( parID === "vertexColors" ) {
  6344. if ( matJSON.parameters[ parID ] == "face" ) {
  6345. matJSON.parameters[ parID ] = THREE.FaceColors;
  6346. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  6347. } else if ( matJSON.parameters[ parID ] ) {
  6348. matJSON.parameters[ parID ] = THREE.VertexColors;
  6349. }
  6350. } else if ( parID === "wrapRGB" ) {
  6351. var v3 = matJSON.parameters[ parID ];
  6352. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  6353. }
  6354. }
  6355. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  6356. matJSON.parameters.transparent = true;
  6357. }
  6358. if ( matJSON.parameters.normalMap ) {
  6359. var shader = THREE.ShaderUtils.lib[ "normal" ];
  6360. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6361. var diffuse = matJSON.parameters.color;
  6362. var specular = matJSON.parameters.specular;
  6363. var ambient = matJSON.parameters.ambient;
  6364. var shininess = matJSON.parameters.shininess;
  6365. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  6366. if ( matJSON.parameters.normalScale ) {
  6367. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  6368. }
  6369. if ( matJSON.parameters.map ) {
  6370. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  6371. uniforms[ "enableDiffuse" ].value = true;
  6372. }
  6373. if ( matJSON.parameters.envMap ) {
  6374. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  6375. uniforms[ "enableReflection" ].value = true;
  6376. uniforms[ "uReflectivity" ].value = matJSON.parameters.reflectivity;
  6377. }
  6378. if ( matJSON.parameters.lightMap ) {
  6379. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  6380. uniforms[ "enableAO" ].value = true;
  6381. }
  6382. if ( matJSON.parameters.specularMap ) {
  6383. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  6384. uniforms[ "enableSpecular" ].value = true;
  6385. }
  6386. if ( matJSON.parameters.displacementMap ) {
  6387. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  6388. uniforms[ "enableDisplacement" ].value = true;
  6389. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  6390. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  6391. }
  6392. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  6393. uniforms[ "uSpecularColor" ].value.setHex( specular );
  6394. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  6395. uniforms[ "uShininess" ].value = shininess;
  6396. if ( matJSON.parameters.opacity ) {
  6397. uniforms[ "uOpacity" ].value = matJSON.parameters.opacity;
  6398. }
  6399. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6400. material = new THREE.ShaderMaterial( parameters );
  6401. } else {
  6402. material = new THREE[ matJSON.type ]( matJSON.parameters );
  6403. }
  6404. result.materials[ matID ] = material;
  6405. }
  6406. // second pass through all materials to initialize MeshFaceMaterials
  6407. // that could be referring to other materials out of order
  6408. for ( matID in data.materials ) {
  6409. matJSON = data.materials[ matID ];
  6410. if ( matJSON.parameters.materials ) {
  6411. var materialArray = [];
  6412. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  6413. var label = matJSON.parameters.materials[ i ];
  6414. materialArray.push( result.materials[ label ] );
  6415. }
  6416. result.materials[ matID ].materials = materialArray;
  6417. }
  6418. }
  6419. // objects ( synchronous init of procedural primitives )
  6420. handle_objects();
  6421. // defaults
  6422. if ( result.cameras && data.defaults.camera ) {
  6423. result.currentCamera = result.cameras[ data.defaults.camera ];
  6424. }
  6425. if ( result.fogs && data.defaults.fog ) {
  6426. result.scene.fog = result.fogs[ data.defaults.fog ];
  6427. }
  6428. color = data.defaults.bgcolor;
  6429. result.bgColor = new THREE.Color();
  6430. result.bgColor.setRGB( color[0], color[1], color[2] );
  6431. result.bgColorAlpha = data.defaults.bgalpha;
  6432. // synchronous callback
  6433. scope.callbackSync( result );
  6434. // just in case there are no async elements
  6435. async_callback_gate();
  6436. };
  6437. /**
  6438. * @author mrdoob / http://mrdoob.com/
  6439. */
  6440. THREE.TextureLoader = function () {
  6441. THREE.EventDispatcher.call( this );
  6442. this.crossOrigin = null;
  6443. };
  6444. THREE.TextureLoader.prototype = {
  6445. constructor: THREE.TextureLoader,
  6446. load: function ( url ) {
  6447. var scope = this;
  6448. var image = new Image();
  6449. image.addEventListener( 'load', function () {
  6450. var texture = new THREE.Texture( image );
  6451. texture.needsUpdate = true;
  6452. scope.dispatchEvent( { type: 'load', content: texture } );
  6453. }, false );
  6454. image.addEventListener( 'error', function () {
  6455. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  6456. }, false );
  6457. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  6458. image.src = url;
  6459. }
  6460. }
  6461. /**
  6462. * @author mrdoob / http://mrdoob.com/
  6463. * @author alteredq / http://alteredqualia.com/
  6464. */
  6465. THREE.Material = function () {
  6466. THREE.EventDispatcher.call( this );
  6467. this.id = THREE.MaterialIdCount ++;
  6468. this.name = '';
  6469. this.side = THREE.FrontSide;
  6470. this.opacity = 1;
  6471. this.transparent = false;
  6472. this.blending = THREE.NormalBlending;
  6473. this.blendSrc = THREE.SrcAlphaFactor;
  6474. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  6475. this.blendEquation = THREE.AddEquation;
  6476. this.depthTest = true;
  6477. this.depthWrite = true;
  6478. this.polygonOffset = false;
  6479. this.polygonOffsetFactor = 0;
  6480. this.polygonOffsetUnits = 0;
  6481. this.alphaTest = 0;
  6482. this.overdraw = false; // Boolean for fixing antialiasing gaps in CanvasRenderer
  6483. this.visible = true;
  6484. this.needsUpdate = true;
  6485. };
  6486. THREE.Material.prototype.setValues = function ( values ) {
  6487. if ( values === undefined ) return;
  6488. for ( var key in values ) {
  6489. var newValue = values[ key ];
  6490. if ( newValue === undefined ) {
  6491. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  6492. continue;
  6493. }
  6494. if ( key in this ) {
  6495. var currentValue = this[ key ];
  6496. if ( currentValue instanceof THREE.Color && newValue instanceof THREE.Color ) {
  6497. currentValue.copy( newValue );
  6498. } else if ( currentValue instanceof THREE.Color ) {
  6499. currentValue.set( newValue );
  6500. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  6501. currentValue.copy( newValue );
  6502. } else {
  6503. this[ key ] = newValue;
  6504. }
  6505. }
  6506. }
  6507. };
  6508. THREE.Material.prototype.clone = function ( material ) {
  6509. if ( material === undefined ) material = new THREE.Material();
  6510. material.name = this.name;
  6511. material.side = this.side;
  6512. material.opacity = this.opacity;
  6513. material.transparent = this.transparent;
  6514. material.blending = this.blending;
  6515. material.blendSrc = this.blendSrc;
  6516. material.blendDst = this.blendDst;
  6517. material.blendEquation = this.blendEquation;
  6518. material.depthTest = this.depthTest;
  6519. material.depthWrite = this.depthWrite;
  6520. material.polygonOffset = this.polygonOffset;
  6521. material.polygonOffsetFactor = this.polygonOffsetFactor;
  6522. material.polygonOffsetUnits = this.polygonOffsetUnits;
  6523. material.alphaTest = this.alphaTest;
  6524. material.overdraw = this.overdraw;
  6525. material.visible = this.visible;
  6526. return material;
  6527. };
  6528. THREE.Material.prototype.dispose = function () {
  6529. this.dispatchEvent( { type: 'dispose' } );
  6530. };
  6531. THREE.MaterialIdCount = 0;
  6532. /**
  6533. * @author mrdoob / http://mrdoob.com/
  6534. * @author alteredq / http://alteredqualia.com/
  6535. *
  6536. * parameters = {
  6537. * color: <hex>,
  6538. * opacity: <float>,
  6539. *
  6540. * blending: THREE.NormalBlending,
  6541. * depthTest: <bool>,
  6542. * depthWrite: <bool>,
  6543. *
  6544. * linewidth: <float>,
  6545. * linecap: "round",
  6546. * linejoin: "round",
  6547. *
  6548. * vertexColors: <bool>
  6549. *
  6550. * fog: <bool>
  6551. * }
  6552. */
  6553. THREE.LineBasicMaterial = function ( parameters ) {
  6554. THREE.Material.call( this );
  6555. this.color = new THREE.Color( 0xffffff );
  6556. this.linewidth = 1;
  6557. this.linecap = 'round';
  6558. this.linejoin = 'round';
  6559. this.vertexColors = false;
  6560. this.fog = true;
  6561. this.setValues( parameters );
  6562. };
  6563. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6564. THREE.LineBasicMaterial.prototype.clone = function () {
  6565. var material = new THREE.LineBasicMaterial();
  6566. THREE.Material.prototype.clone.call( this, material );
  6567. material.color.copy( this.color );
  6568. material.linewidth = this.linewidth;
  6569. material.linecap = this.linecap;
  6570. material.linejoin = this.linejoin;
  6571. material.vertexColors = this.vertexColors;
  6572. material.fog = this.fog;
  6573. return material;
  6574. };
  6575. /**
  6576. * @author alteredq / http://alteredqualia.com/
  6577. *
  6578. * parameters = {
  6579. * color: <hex>,
  6580. * opacity: <float>,
  6581. *
  6582. * blending: THREE.NormalBlending,
  6583. * depthTest: <bool>,
  6584. * depthWrite: <bool>,
  6585. *
  6586. * linewidth: <float>,
  6587. *
  6588. * scale: <float>,
  6589. * dashSize: <float>,
  6590. * gapSize: <float>,
  6591. *
  6592. * vertexColors: <bool>
  6593. *
  6594. * fog: <bool>
  6595. * }
  6596. */
  6597. THREE.LineDashedMaterial = function ( parameters ) {
  6598. THREE.Material.call( this );
  6599. this.color = new THREE.Color( 0xffffff );
  6600. this.linewidth = 1;
  6601. this.scale = 1;
  6602. this.dashSize = 3;
  6603. this.gapSize = 1;
  6604. this.vertexColors = false;
  6605. this.fog = true;
  6606. this.setValues( parameters );
  6607. };
  6608. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  6609. THREE.LineDashedMaterial.prototype.clone = function () {
  6610. var material = new THREE.LineDashedMaterial();
  6611. THREE.Material.prototype.clone.call( this, material );
  6612. material.color.copy( this.color );
  6613. material.linewidth = this.linewidth;
  6614. material.scale = this.scale;
  6615. material.dashSize = this.dashSize;
  6616. material.gapSize = this.gapSize;
  6617. material.vertexColors = this.vertexColors;
  6618. material.fog = this.fog;
  6619. return material;
  6620. };
  6621. /**
  6622. * @author mrdoob / http://mrdoob.com/
  6623. * @author alteredq / http://alteredqualia.com/
  6624. *
  6625. * parameters = {
  6626. * color: <hex>,
  6627. * opacity: <float>,
  6628. * map: new THREE.Texture( <Image> ),
  6629. *
  6630. * lightMap: new THREE.Texture( <Image> ),
  6631. *
  6632. * specularMap: new THREE.Texture( <Image> ),
  6633. *
  6634. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6635. * combine: THREE.Multiply,
  6636. * reflectivity: <float>,
  6637. * refractionRatio: <float>,
  6638. *
  6639. * shading: THREE.SmoothShading,
  6640. * blending: THREE.NormalBlending,
  6641. * depthTest: <bool>,
  6642. * depthWrite: <bool>,
  6643. *
  6644. * wireframe: <boolean>,
  6645. * wireframeLinewidth: <float>,
  6646. *
  6647. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6648. *
  6649. * skinning: <bool>,
  6650. * morphTargets: <bool>,
  6651. *
  6652. * fog: <bool>
  6653. * }
  6654. */
  6655. THREE.MeshBasicMaterial = function ( parameters ) {
  6656. THREE.Material.call( this );
  6657. this.color = new THREE.Color( 0xffffff ); // emissive
  6658. this.map = null;
  6659. this.lightMap = null;
  6660. this.specularMap = null;
  6661. this.envMap = null;
  6662. this.combine = THREE.MultiplyOperation;
  6663. this.reflectivity = 1;
  6664. this.refractionRatio = 0.98;
  6665. this.fog = true;
  6666. this.shading = THREE.SmoothShading;
  6667. this.wireframe = false;
  6668. this.wireframeLinewidth = 1;
  6669. this.wireframeLinecap = 'round';
  6670. this.wireframeLinejoin = 'round';
  6671. this.vertexColors = THREE.NoColors;
  6672. this.skinning = false;
  6673. this.morphTargets = false;
  6674. this.setValues( parameters );
  6675. };
  6676. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6677. THREE.MeshBasicMaterial.prototype.clone = function () {
  6678. var material = new THREE.MeshBasicMaterial();
  6679. THREE.Material.prototype.clone.call( this, material );
  6680. material.color.copy( this.color );
  6681. material.map = this.map;
  6682. material.lightMap = this.lightMap;
  6683. material.specularMap = this.specularMap;
  6684. material.envMap = this.envMap;
  6685. material.combine = this.combine;
  6686. material.reflectivity = this.reflectivity;
  6687. material.refractionRatio = this.refractionRatio;
  6688. material.fog = this.fog;
  6689. material.shading = this.shading;
  6690. material.wireframe = this.wireframe;
  6691. material.wireframeLinewidth = this.wireframeLinewidth;
  6692. material.wireframeLinecap = this.wireframeLinecap;
  6693. material.wireframeLinejoin = this.wireframeLinejoin;
  6694. material.vertexColors = this.vertexColors;
  6695. material.skinning = this.skinning;
  6696. material.morphTargets = this.morphTargets;
  6697. return material;
  6698. };
  6699. /**
  6700. * @author mrdoob / http://mrdoob.com/
  6701. * @author alteredq / http://alteredqualia.com/
  6702. *
  6703. * parameters = {
  6704. * color: <hex>,
  6705. * ambient: <hex>,
  6706. * emissive: <hex>,
  6707. * opacity: <float>,
  6708. *
  6709. * map: new THREE.Texture( <Image> ),
  6710. *
  6711. * lightMap: new THREE.Texture( <Image> ),
  6712. *
  6713. * specularMap: new THREE.Texture( <Image> ),
  6714. *
  6715. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6716. * combine: THREE.Multiply,
  6717. * reflectivity: <float>,
  6718. * refractionRatio: <float>,
  6719. *
  6720. * shading: THREE.SmoothShading,
  6721. * blending: THREE.NormalBlending,
  6722. * depthTest: <bool>,
  6723. * depthWrite: <bool>,
  6724. *
  6725. * wireframe: <boolean>,
  6726. * wireframeLinewidth: <float>,
  6727. *
  6728. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6729. *
  6730. * skinning: <bool>,
  6731. * morphTargets: <bool>,
  6732. * morphNormals: <bool>,
  6733. *
  6734. * fog: <bool>
  6735. * }
  6736. */
  6737. THREE.MeshLambertMaterial = function ( parameters ) {
  6738. THREE.Material.call( this );
  6739. this.color = new THREE.Color( 0xffffff ); // diffuse
  6740. this.ambient = new THREE.Color( 0xffffff );
  6741. this.emissive = new THREE.Color( 0x000000 );
  6742. this.wrapAround = false;
  6743. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6744. this.map = null;
  6745. this.lightMap = null;
  6746. this.specularMap = null;
  6747. this.envMap = null;
  6748. this.combine = THREE.MultiplyOperation;
  6749. this.reflectivity = 1;
  6750. this.refractionRatio = 0.98;
  6751. this.fog = true;
  6752. this.shading = THREE.SmoothShading;
  6753. this.wireframe = false;
  6754. this.wireframeLinewidth = 1;
  6755. this.wireframeLinecap = 'round';
  6756. this.wireframeLinejoin = 'round';
  6757. this.vertexColors = THREE.NoColors;
  6758. this.skinning = false;
  6759. this.morphTargets = false;
  6760. this.morphNormals = false;
  6761. this.setValues( parameters );
  6762. };
  6763. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  6764. THREE.MeshLambertMaterial.prototype.clone = function () {
  6765. var material = new THREE.MeshLambertMaterial();
  6766. THREE.Material.prototype.clone.call( this, material );
  6767. material.color.copy( this.color );
  6768. material.ambient.copy( this.ambient );
  6769. material.emissive.copy( this.emissive );
  6770. material.wrapAround = this.wrapAround;
  6771. material.wrapRGB.copy( this.wrapRGB );
  6772. material.map = this.map;
  6773. material.lightMap = this.lightMap;
  6774. material.specularMap = this.specularMap;
  6775. material.envMap = this.envMap;
  6776. material.combine = this.combine;
  6777. material.reflectivity = this.reflectivity;
  6778. material.refractionRatio = this.refractionRatio;
  6779. material.fog = this.fog;
  6780. material.shading = this.shading;
  6781. material.wireframe = this.wireframe;
  6782. material.wireframeLinewidth = this.wireframeLinewidth;
  6783. material.wireframeLinecap = this.wireframeLinecap;
  6784. material.wireframeLinejoin = this.wireframeLinejoin;
  6785. material.vertexColors = this.vertexColors;
  6786. material.skinning = this.skinning;
  6787. material.morphTargets = this.morphTargets;
  6788. material.morphNormals = this.morphNormals;
  6789. return material;
  6790. };
  6791. /**
  6792. * @author mrdoob / http://mrdoob.com/
  6793. * @author alteredq / http://alteredqualia.com/
  6794. *
  6795. * parameters = {
  6796. * color: <hex>,
  6797. * ambient: <hex>,
  6798. * emissive: <hex>,
  6799. * specular: <hex>,
  6800. * shininess: <float>,
  6801. * opacity: <float>,
  6802. *
  6803. * map: new THREE.Texture( <Image> ),
  6804. *
  6805. * lightMap: new THREE.Texture( <Image> ),
  6806. *
  6807. * bumpMap: new THREE.Texture( <Image> ),
  6808. * bumpScale: <float>,
  6809. *
  6810. * normalMap: new THREE.Texture( <Image> ),
  6811. * normalScale: <Vector2>,
  6812. *
  6813. * specularMap: new THREE.Texture( <Image> ),
  6814. *
  6815. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6816. * combine: THREE.Multiply,
  6817. * reflectivity: <float>,
  6818. * refractionRatio: <float>,
  6819. *
  6820. * shading: THREE.SmoothShading,
  6821. * blending: THREE.NormalBlending,
  6822. * depthTest: <bool>,
  6823. * depthWrite: <bool>,
  6824. *
  6825. * wireframe: <boolean>,
  6826. * wireframeLinewidth: <float>,
  6827. *
  6828. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6829. *
  6830. * skinning: <bool>,
  6831. * morphTargets: <bool>,
  6832. * morphNormals: <bool>,
  6833. *
  6834. * fog: <bool>
  6835. * }
  6836. */
  6837. THREE.MeshPhongMaterial = function ( parameters ) {
  6838. THREE.Material.call( this );
  6839. this.color = new THREE.Color( 0xffffff ); // diffuse
  6840. this.ambient = new THREE.Color( 0xffffff );
  6841. this.emissive = new THREE.Color( 0x000000 );
  6842. this.specular = new THREE.Color( 0x111111 );
  6843. this.shininess = 30;
  6844. this.metal = false;
  6845. this.perPixel = true;
  6846. this.wrapAround = false;
  6847. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6848. this.map = null;
  6849. this.lightMap = null;
  6850. this.bumpMap = null;
  6851. this.bumpScale = 1;
  6852. this.normalMap = null;
  6853. this.normalScale = new THREE.Vector2( 1, 1 );
  6854. this.specularMap = null;
  6855. this.envMap = null;
  6856. this.combine = THREE.MultiplyOperation;
  6857. this.reflectivity = 1;
  6858. this.refractionRatio = 0.98;
  6859. this.fog = true;
  6860. this.shading = THREE.SmoothShading;
  6861. this.wireframe = false;
  6862. this.wireframeLinewidth = 1;
  6863. this.wireframeLinecap = 'round';
  6864. this.wireframeLinejoin = 'round';
  6865. this.vertexColors = THREE.NoColors;
  6866. this.skinning = false;
  6867. this.morphTargets = false;
  6868. this.morphNormals = false;
  6869. this.setValues( parameters );
  6870. };
  6871. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  6872. THREE.MeshPhongMaterial.prototype.clone = function () {
  6873. var material = new THREE.MeshPhongMaterial();
  6874. THREE.Material.prototype.clone.call( this, material );
  6875. material.color.copy( this.color );
  6876. material.ambient.copy( this.ambient );
  6877. material.emissive.copy( this.emissive );
  6878. material.specular.copy( this.specular );
  6879. material.shininess = this.shininess;
  6880. material.metal = this.metal;
  6881. material.perPixel = this.perPixel;
  6882. material.wrapAround = this.wrapAround;
  6883. material.wrapRGB.copy( this.wrapRGB );
  6884. material.map = this.map;
  6885. material.lightMap = this.lightMap;
  6886. material.bumpMap = this.bumpMap;
  6887. material.bumpScale = this.bumpScale;
  6888. material.normalMap = this.normalMap;
  6889. material.normalScale.copy( this.normalScale );
  6890. material.specularMap = this.specularMap;
  6891. material.envMap = this.envMap;
  6892. material.combine = this.combine;
  6893. material.reflectivity = this.reflectivity;
  6894. material.refractionRatio = this.refractionRatio;
  6895. material.fog = this.fog;
  6896. material.shading = this.shading;
  6897. material.wireframe = this.wireframe;
  6898. material.wireframeLinewidth = this.wireframeLinewidth;
  6899. material.wireframeLinecap = this.wireframeLinecap;
  6900. material.wireframeLinejoin = this.wireframeLinejoin;
  6901. material.vertexColors = this.vertexColors;
  6902. material.skinning = this.skinning;
  6903. material.morphTargets = this.morphTargets;
  6904. material.morphNormals = this.morphNormals;
  6905. return material;
  6906. };
  6907. /**
  6908. * @author mrdoob / http://mrdoob.com/
  6909. * @author alteredq / http://alteredqualia.com/
  6910. *
  6911. * parameters = {
  6912. * opacity: <float>,
  6913. *
  6914. * blending: THREE.NormalBlending,
  6915. * depthTest: <bool>,
  6916. * depthWrite: <bool>,
  6917. *
  6918. * wireframe: <boolean>,
  6919. * wireframeLinewidth: <float>
  6920. * }
  6921. */
  6922. THREE.MeshDepthMaterial = function ( parameters ) {
  6923. THREE.Material.call( this );
  6924. this.wireframe = false;
  6925. this.wireframeLinewidth = 1;
  6926. this.setValues( parameters );
  6927. };
  6928. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  6929. THREE.MeshDepthMaterial.prototype.clone = function () {
  6930. var material = new THREE.LineBasicMaterial();
  6931. THREE.Material.prototype.clone.call( this, material );
  6932. material.wireframe = this.wireframe;
  6933. material.wireframeLinewidth = this.wireframeLinewidth;
  6934. return material;
  6935. };
  6936. /**
  6937. * @author mrdoob / http://mrdoob.com/
  6938. *
  6939. * parameters = {
  6940. * opacity: <float>,
  6941. *
  6942. * shading: THREE.FlatShading,
  6943. * blending: THREE.NormalBlending,
  6944. * depthTest: <bool>,
  6945. * depthWrite: <bool>,
  6946. *
  6947. * wireframe: <boolean>,
  6948. * wireframeLinewidth: <float>
  6949. * }
  6950. */
  6951. THREE.MeshNormalMaterial = function ( parameters ) {
  6952. THREE.Material.call( this, parameters );
  6953. this.shading = THREE.FlatShading;
  6954. this.wireframe = false;
  6955. this.wireframeLinewidth = 1;
  6956. this.setValues( parameters );
  6957. };
  6958. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  6959. THREE.MeshNormalMaterial.prototype.clone = function () {
  6960. var material = new THREE.MeshNormalMaterial();
  6961. THREE.Material.prototype.clone.call( this, material );
  6962. material.shading = this.shading;
  6963. material.wireframe = this.wireframe;
  6964. material.wireframeLinewidth = this.wireframeLinewidth;
  6965. return material;
  6966. };
  6967. /**
  6968. * @author mrdoob / http://mrdoob.com/
  6969. */
  6970. THREE.MeshFaceMaterial = function ( materials ) {
  6971. this.materials = materials instanceof Array ? materials : [];
  6972. };
  6973. THREE.MeshFaceMaterial.prototype.clone = function () {
  6974. return new THREE.MeshFaceMaterial( this.materials.slice( 0 ) );
  6975. };
  6976. /**
  6977. * @author mrdoob / http://mrdoob.com/
  6978. * @author alteredq / http://alteredqualia.com/
  6979. *
  6980. * parameters = {
  6981. * color: <hex>,
  6982. * opacity: <float>,
  6983. * map: new THREE.Texture( <Image> ),
  6984. *
  6985. * size: <float>,
  6986. *
  6987. * blending: THREE.NormalBlending,
  6988. * depthTest: <bool>,
  6989. * depthWrite: <bool>,
  6990. *
  6991. * vertexColors: <bool>,
  6992. *
  6993. * fog: <bool>
  6994. * }
  6995. */
  6996. THREE.ParticleBasicMaterial = function ( parameters ) {
  6997. THREE.Material.call( this );
  6998. this.color = new THREE.Color( 0xffffff );
  6999. this.map = null;
  7000. this.size = 1;
  7001. this.sizeAttenuation = true;
  7002. this.vertexColors = false;
  7003. this.fog = true;
  7004. this.setValues( parameters );
  7005. };
  7006. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7007. THREE.ParticleBasicMaterial.prototype.clone = function () {
  7008. var material = new THREE.ParticleBasicMaterial();
  7009. THREE.Material.prototype.clone.call( this, material );
  7010. material.color.copy( this.color );
  7011. material.map = this.map;
  7012. material.size = this.size;
  7013. material.sizeAttenuation = this.sizeAttenuation;
  7014. material.vertexColors = this.vertexColors;
  7015. material.fog = this.fog;
  7016. return material;
  7017. };
  7018. /**
  7019. * @author mrdoob / http://mrdoob.com/
  7020. *
  7021. * parameters = {
  7022. * color: <hex>,
  7023. * program: <function>,
  7024. * opacity: <float>,
  7025. * blending: THREE.NormalBlending
  7026. * }
  7027. */
  7028. THREE.ParticleCanvasMaterial = function ( parameters ) {
  7029. THREE.Material.call( this );
  7030. this.color = new THREE.Color( 0xffffff );
  7031. this.program = function ( context, color ) {};
  7032. this.setValues( parameters );
  7033. };
  7034. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  7035. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  7036. var material = new THREE.ParticleCanvasMaterial();
  7037. THREE.Material.prototype.clone.call( this, material );
  7038. material.color.copy( this.color );
  7039. material.program = this.program;
  7040. return material;
  7041. };
  7042. /**
  7043. * @author alteredq / http://alteredqualia.com/
  7044. *
  7045. * parameters = {
  7046. * fragmentShader: <string>,
  7047. * vertexShader: <string>,
  7048. *
  7049. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  7050. *
  7051. * defines: { "label" : "value" },
  7052. *
  7053. * shading: THREE.SmoothShading,
  7054. * blending: THREE.NormalBlending,
  7055. * depthTest: <bool>,
  7056. * depthWrite: <bool>,
  7057. *
  7058. * wireframe: <boolean>,
  7059. * wireframeLinewidth: <float>,
  7060. *
  7061. * lights: <bool>,
  7062. *
  7063. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7064. *
  7065. * skinning: <bool>,
  7066. * morphTargets: <bool>,
  7067. * morphNormals: <bool>,
  7068. *
  7069. * fog: <bool>
  7070. * }
  7071. */
  7072. THREE.ShaderMaterial = function ( parameters ) {
  7073. THREE.Material.call( this );
  7074. this.fragmentShader = "void main() {}";
  7075. this.vertexShader = "void main() {}";
  7076. this.uniforms = {};
  7077. this.defines = {};
  7078. this.attributes = null;
  7079. this.shading = THREE.SmoothShading;
  7080. this.wireframe = false;
  7081. this.wireframeLinewidth = 1;
  7082. this.fog = false; // set to use scene fog
  7083. this.lights = false; // set to use scene lights
  7084. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  7085. this.skinning = false; // set to use skinning attribute streams
  7086. this.morphTargets = false; // set to use morph targets
  7087. this.morphNormals = false; // set to use morph normals
  7088. this.setValues( parameters );
  7089. };
  7090. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  7091. THREE.ShaderMaterial.prototype.clone = function () {
  7092. var material = new THREE.ShaderMaterial();
  7093. THREE.Material.prototype.clone.call( this, material );
  7094. material.fragmentShader = this.fragmentShader;
  7095. material.vertexShader = this.vertexShader;
  7096. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  7097. material.attributes = this.attributes;
  7098. material.defines = this.defines;
  7099. material.shading = this.shading;
  7100. material.wireframe = this.wireframe;
  7101. material.wireframeLinewidth = this.wireframeLinewidth;
  7102. material.fog = this.fog;
  7103. material.lights = this.lights;
  7104. material.vertexColors = this.vertexColors;
  7105. material.skinning = this.skinning;
  7106. material.morphTargets = this.morphTargets;
  7107. material.morphNormals = this.morphNormals;
  7108. return material;
  7109. };
  7110. /**
  7111. * @author alteredq / http://alteredqualia.com/
  7112. *
  7113. * parameters = {
  7114. * color: <hex>,
  7115. * opacity: <float>,
  7116. * map: new THREE.Texture( <Image> ),
  7117. *
  7118. * blending: THREE.NormalBlending,
  7119. * depthTest: <bool>,
  7120. * depthWrite: <bool>,
  7121. *
  7122. * useScreenCoordinates: <bool>,
  7123. * sizeAttenuation: <bool>,
  7124. * scaleByViewport: <bool>,
  7125. * alignment: THREE.SpriteAlignment.center,
  7126. *
  7127. * uvOffset: new THREE.Vector2(),
  7128. * uvScale: new THREE.Vector2(),
  7129. *
  7130. * fog: <bool>
  7131. * }
  7132. */
  7133. THREE.SpriteMaterial = function ( parameters ) {
  7134. THREE.Material.call( this );
  7135. // defaults
  7136. this.color = new THREE.Color( 0xffffff );
  7137. this.map = new THREE.Texture();
  7138. this.useScreenCoordinates = true;
  7139. this.depthTest = !this.useScreenCoordinates;
  7140. this.sizeAttenuation = !this.useScreenCoordinates;
  7141. this.scaleByViewport = !this.sizeAttenuation;
  7142. this.alignment = THREE.SpriteAlignment.center.clone();
  7143. this.fog = false;
  7144. this.uvOffset = new THREE.Vector2( 0, 0 );
  7145. this.uvScale = new THREE.Vector2( 1, 1 );
  7146. // set parameters
  7147. this.setValues( parameters );
  7148. // override coupled defaults if not specified explicitly by parameters
  7149. parameters = parameters || {};
  7150. if ( parameters.depthTest === undefined ) this.depthTest = !this.useScreenCoordinates;
  7151. if ( parameters.sizeAttenuation === undefined ) this.sizeAttenuation = !this.useScreenCoordinates;
  7152. if ( parameters.scaleByViewport === undefined ) this.scaleByViewport = !this.sizeAttenuation;
  7153. };
  7154. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  7155. THREE.SpriteMaterial.prototype.clone = function () {
  7156. var material = new THREE.SpriteMaterial();
  7157. THREE.Material.prototype.clone.call( this, material );
  7158. material.color.copy( this.color );
  7159. material.map = this.map;
  7160. material.useScreenCoordinates = this.useScreenCoordinates;
  7161. material.sizeAttenuation = this.sizeAttenuation;
  7162. material.scaleByViewport = this.scaleByViewport;
  7163. material.alignment.copy( this.alignment );
  7164. material.uvOffset.copy( this.uvOffset );
  7165. material.uvScale.copy( this.uvScale );
  7166. material.fog = this.fog;
  7167. return material;
  7168. };
  7169. // Alignment enums
  7170. THREE.SpriteAlignment = {};
  7171. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  7172. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  7173. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  7174. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  7175. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  7176. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  7177. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  7178. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  7179. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  7180. /**
  7181. * @author mrdoob / http://mrdoob.com/
  7182. * @author alteredq / http://alteredqualia.com/
  7183. * @author szimek / https://github.com/szimek/
  7184. */
  7185. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  7186. THREE.EventDispatcher.call( this );
  7187. this.id = THREE.TextureIdCount ++;
  7188. this.name = '';
  7189. this.image = image;
  7190. this.mipmaps = [];
  7191. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  7192. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  7193. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  7194. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  7195. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  7196. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  7197. this.format = format !== undefined ? format : THREE.RGBAFormat;
  7198. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  7199. this.offset = new THREE.Vector2( 0, 0 );
  7200. this.repeat = new THREE.Vector2( 1, 1 );
  7201. this.generateMipmaps = true;
  7202. this.premultiplyAlpha = false;
  7203. this.flipY = true;
  7204. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  7205. this.needsUpdate = false;
  7206. this.onUpdate = null;
  7207. };
  7208. THREE.Texture.prototype = {
  7209. constructor: THREE.Texture,
  7210. clone: function ( texture ) {
  7211. if ( texture === undefined ) texture = new THREE.Texture();
  7212. texture.image = this.image;
  7213. texture.mipmaps = this.mipmaps.slice(0);
  7214. texture.mapping = this.mapping;
  7215. texture.wrapS = this.wrapS;
  7216. texture.wrapT = this.wrapT;
  7217. texture.magFilter = this.magFilter;
  7218. texture.minFilter = this.minFilter;
  7219. texture.anisotropy = this.anisotropy;
  7220. texture.format = this.format;
  7221. texture.type = this.type;
  7222. texture.offset.copy( this.offset );
  7223. texture.repeat.copy( this.repeat );
  7224. texture.generateMipmaps = this.generateMipmaps;
  7225. texture.premultiplyAlpha = this.premultiplyAlpha;
  7226. texture.flipY = this.flipY;
  7227. texture.unpackAlignment = this.unpackAlignment;
  7228. return texture;
  7229. },
  7230. dispose: function () {
  7231. this.dispatchEvent( { type: 'dispose' } );
  7232. }
  7233. };
  7234. THREE.TextureIdCount = 0;
  7235. /**
  7236. * @author alteredq / http://alteredqualia.com/
  7237. */
  7238. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7239. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7240. this.image = { width: width, height: height };
  7241. this.mipmaps = mipmaps;
  7242. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  7243. };
  7244. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  7245. THREE.CompressedTexture.prototype.clone = function () {
  7246. var texture = new THREE.CompressedTexture();
  7247. THREE.Texture.prototype.clone.call( this, texture );
  7248. return texture;
  7249. };
  7250. /**
  7251. * @author alteredq / http://alteredqualia.com/
  7252. */
  7253. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7254. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7255. this.image = { data: data, width: width, height: height };
  7256. };
  7257. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  7258. THREE.DataTexture.prototype.clone = function () {
  7259. var texture = new THREE.DataTexture();
  7260. THREE.Texture.prototype.clone.call( this, texture );
  7261. return texture;
  7262. };
  7263. /**
  7264. * @author mrdoob / http://mrdoob.com/
  7265. */
  7266. THREE.Particle = function ( material ) {
  7267. THREE.Object3D.call( this );
  7268. this.material = material;
  7269. };
  7270. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  7271. THREE.Particle.prototype.clone = function ( object ) {
  7272. if ( object === undefined ) object = new THREE.Particle( this.material );
  7273. THREE.Object3D.prototype.clone.call( this, object );
  7274. return object;
  7275. };
  7276. /**
  7277. * @author alteredq / http://alteredqualia.com/
  7278. */
  7279. THREE.ParticleSystem = function ( geometry, material ) {
  7280. THREE.Object3D.call( this );
  7281. this.geometry = geometry;
  7282. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  7283. this.sortParticles = false;
  7284. if ( this.geometry ) {
  7285. // calc bound radius
  7286. if( this.geometry.boundingSphere === null ) {
  7287. this.geometry.computeBoundingSphere();
  7288. }
  7289. }
  7290. this.frustumCulled = false;
  7291. };
  7292. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  7293. THREE.ParticleSystem.prototype.clone = function ( object ) {
  7294. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  7295. object.sortParticles = this.sortParticles;
  7296. THREE.Object3D.prototype.clone.call( this, object );
  7297. return object;
  7298. };
  7299. /**
  7300. * @author mrdoob / http://mrdoob.com/
  7301. */
  7302. THREE.Line = function ( geometry, material, type ) {
  7303. THREE.Object3D.call( this );
  7304. this.geometry = geometry;
  7305. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  7306. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  7307. if ( this.geometry ) {
  7308. if ( ! this.geometry.boundingSphere ) {
  7309. this.geometry.computeBoundingSphere();
  7310. }
  7311. }
  7312. };
  7313. THREE.LineStrip = 0;
  7314. THREE.LinePieces = 1;
  7315. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  7316. THREE.Line.prototype.clone = function ( object ) {
  7317. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  7318. THREE.Object3D.prototype.clone.call( this, object );
  7319. return object;
  7320. };
  7321. /**
  7322. * @author mrdoob / http://mrdoob.com/
  7323. * @author alteredq / http://alteredqualia.com/
  7324. * @author mikael emtinger / http://gomo.se/
  7325. * @author jonobr1 / http://jonobr1.com/
  7326. */
  7327. THREE.Mesh = function ( geometry, material ) {
  7328. THREE.Object3D.call( this );
  7329. this.geometry = geometry;
  7330. this.material = ( material !== undefined ) ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  7331. if ( this.geometry !== undefined ) {
  7332. if ( this.geometry.boundingSphere === null ) {
  7333. this.geometry.computeBoundingSphere();
  7334. }
  7335. this.updateMorphTargets();
  7336. }
  7337. };
  7338. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  7339. THREE.Mesh.prototype.updateMorphTargets = function () {
  7340. if ( this.geometry.morphTargets.length > 0 ) {
  7341. this.morphTargetBase = -1;
  7342. this.morphTargetForcedOrder = [];
  7343. this.morphTargetInfluences = [];
  7344. this.morphTargetDictionary = {};
  7345. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  7346. this.morphTargetInfluences.push( 0 );
  7347. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  7348. }
  7349. }
  7350. };
  7351. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  7352. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  7353. return this.morphTargetDictionary[ name ];
  7354. }
  7355. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  7356. return 0;
  7357. };
  7358. THREE.Mesh.prototype.clone = function ( object ) {
  7359. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  7360. THREE.Object3D.prototype.clone.call( this, object );
  7361. return object;
  7362. };
  7363. /**
  7364. * @author mikael emtinger / http://gomo.se/
  7365. * @author alteredq / http://alteredqualia.com/
  7366. */
  7367. THREE.Bone = function( belongsToSkin ) {
  7368. THREE.Object3D.call( this );
  7369. this.skin = belongsToSkin;
  7370. this.skinMatrix = new THREE.Matrix4();
  7371. };
  7372. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  7373. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  7374. // update local
  7375. if ( this.matrixAutoUpdate ) {
  7376. forceUpdate |= this.updateMatrix();
  7377. }
  7378. // update skin matrix
  7379. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  7380. if( parentSkinMatrix ) {
  7381. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  7382. } else {
  7383. this.skinMatrix.copy( this.matrix );
  7384. }
  7385. this.matrixWorldNeedsUpdate = false;
  7386. forceUpdate = true;
  7387. }
  7388. // update children
  7389. var child, i, l = this.children.length;
  7390. for ( i = 0; i < l; i ++ ) {
  7391. this.children[ i ].update( this.skinMatrix, forceUpdate );
  7392. }
  7393. };
  7394. /**
  7395. * @author mikael emtinger / http://gomo.se/
  7396. * @author alteredq / http://alteredqualia.com/
  7397. */
  7398. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  7399. THREE.Mesh.call( this, geometry, material );
  7400. //
  7401. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  7402. // init bones
  7403. this.identityMatrix = new THREE.Matrix4();
  7404. this.bones = [];
  7405. this.boneMatrices = [];
  7406. var b, bone, gbone, p, q, s;
  7407. if ( this.geometry && this.geometry.bones !== undefined ) {
  7408. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  7409. gbone = this.geometry.bones[ b ];
  7410. p = gbone.pos;
  7411. q = gbone.rotq;
  7412. s = gbone.scl;
  7413. bone = this.addBone();
  7414. bone.name = gbone.name;
  7415. bone.position.set( p[0], p[1], p[2] );
  7416. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  7417. bone.useQuaternion = true;
  7418. if ( s !== undefined ) {
  7419. bone.scale.set( s[0], s[1], s[2] );
  7420. } else {
  7421. bone.scale.set( 1, 1, 1 );
  7422. }
  7423. }
  7424. for ( b = 0; b < this.bones.length; b ++ ) {
  7425. gbone = this.geometry.bones[ b ];
  7426. bone = this.bones[ b ];
  7427. if ( gbone.parent === -1 ) {
  7428. this.add( bone );
  7429. } else {
  7430. this.bones[ gbone.parent ].add( bone );
  7431. }
  7432. }
  7433. //
  7434. var nBones = this.bones.length;
  7435. if ( this.useVertexTexture ) {
  7436. // layout (1 matrix = 4 pixels)
  7437. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  7438. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  7439. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  7440. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  7441. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  7442. var size;
  7443. if ( nBones > 256 )
  7444. size = 64;
  7445. else if ( nBones > 64 )
  7446. size = 32;
  7447. else if ( nBones > 16 )
  7448. size = 16;
  7449. else
  7450. size = 8;
  7451. this.boneTextureWidth = size;
  7452. this.boneTextureHeight = size;
  7453. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  7454. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  7455. this.boneTexture.minFilter = THREE.NearestFilter;
  7456. this.boneTexture.magFilter = THREE.NearestFilter;
  7457. this.boneTexture.generateMipmaps = false;
  7458. this.boneTexture.flipY = false;
  7459. } else {
  7460. this.boneMatrices = new Float32Array( 16 * nBones );
  7461. }
  7462. this.pose();
  7463. }
  7464. };
  7465. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  7466. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  7467. if ( bone === undefined ) {
  7468. bone = new THREE.Bone( this );
  7469. }
  7470. this.bones.push( bone );
  7471. return bone;
  7472. };
  7473. THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
  7474. this.matrixAutoUpdate && this.updateMatrix();
  7475. // update matrixWorld
  7476. if ( this.matrixWorldNeedsUpdate || force ) {
  7477. if ( this.parent ) {
  7478. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  7479. } else {
  7480. this.matrixWorld.copy( this.matrix );
  7481. }
  7482. this.matrixWorldNeedsUpdate = false;
  7483. force = true;
  7484. }
  7485. // update children
  7486. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  7487. var child = this.children[ i ];
  7488. if ( child instanceof THREE.Bone ) {
  7489. child.update( this.identityMatrix, false );
  7490. } else {
  7491. child.updateMatrixWorld( true );
  7492. }
  7493. }
  7494. // make a snapshot of the bones' rest position
  7495. if ( this.boneInverses == undefined ) {
  7496. this.boneInverses = [];
  7497. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7498. var inverse = new THREE.Matrix4();
  7499. inverse.getInverse( this.bones[ b ].skinMatrix );
  7500. this.boneInverses.push( inverse );
  7501. }
  7502. }
  7503. // flatten bone matrices to array
  7504. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7505. // compute the offset between the current and the original transform;
  7506. //TODO: we could get rid of this multiplication step if the skinMatrix
  7507. // was already representing the offset; however, this requires some
  7508. // major changes to the animation system
  7509. THREE.SkinnedMesh.offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  7510. THREE.SkinnedMesh.offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  7511. }
  7512. if ( this.useVertexTexture ) {
  7513. this.boneTexture.needsUpdate = true;
  7514. }
  7515. };
  7516. THREE.SkinnedMesh.prototype.pose = function () {
  7517. this.updateMatrixWorld( true );
  7518. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  7519. // normalize weights
  7520. var sw = this.geometry.skinWeights[ i ];
  7521. var scale = 1.0 / sw.lengthManhattan();
  7522. if ( scale !== Infinity ) {
  7523. sw.multiplyScalar( scale );
  7524. } else {
  7525. sw.set( 1 ); // this will be normalized by the shader anyway
  7526. }
  7527. }
  7528. };
  7529. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  7530. if ( object === undefined ) object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  7531. THREE.Mesh.prototype.clone.call( this, object );
  7532. return object;
  7533. };
  7534. THREE.SkinnedMesh.offsetMatrix = new THREE.Matrix4();
  7535. /**
  7536. * @author alteredq / http://alteredqualia.com/
  7537. */
  7538. THREE.MorphAnimMesh = function ( geometry, material ) {
  7539. THREE.Mesh.call( this, geometry, material );
  7540. // API
  7541. this.duration = 1000; // milliseconds
  7542. this.mirroredLoop = false;
  7543. this.time = 0;
  7544. // internals
  7545. this.lastKeyframe = 0;
  7546. this.currentKeyframe = 0;
  7547. this.direction = 1;
  7548. this.directionBackwards = false;
  7549. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  7550. };
  7551. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  7552. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  7553. this.startKeyframe = start;
  7554. this.endKeyframe = end;
  7555. this.length = this.endKeyframe - this.startKeyframe + 1;
  7556. };
  7557. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  7558. this.direction = 1;
  7559. this.directionBackwards = false;
  7560. };
  7561. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  7562. this.direction = -1;
  7563. this.directionBackwards = true;
  7564. };
  7565. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  7566. var geometry = this.geometry;
  7567. if ( ! geometry.animations ) geometry.animations = {};
  7568. var firstAnimation, animations = geometry.animations;
  7569. var pattern = /([a-z]+)(\d+)/;
  7570. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  7571. var morph = geometry.morphTargets[ i ];
  7572. var parts = morph.name.match( pattern );
  7573. if ( parts && parts.length > 1 ) {
  7574. var label = parts[ 1 ];
  7575. var num = parts[ 2 ];
  7576. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  7577. var animation = animations[ label ];
  7578. if ( i < animation.start ) animation.start = i;
  7579. if ( i > animation.end ) animation.end = i;
  7580. if ( ! firstAnimation ) firstAnimation = label;
  7581. }
  7582. }
  7583. geometry.firstAnimation = firstAnimation;
  7584. };
  7585. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  7586. if ( ! this.geometry.animations ) this.geometry.animations = {};
  7587. this.geometry.animations[ label ] = { start: start, end: end };
  7588. };
  7589. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  7590. var animation = this.geometry.animations[ label ];
  7591. if ( animation ) {
  7592. this.setFrameRange( animation.start, animation.end );
  7593. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  7594. this.time = 0;
  7595. } else {
  7596. console.warn( "animation[" + label + "] undefined" );
  7597. }
  7598. };
  7599. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  7600. var frameTime = this.duration / this.length;
  7601. this.time += this.direction * delta;
  7602. if ( this.mirroredLoop ) {
  7603. if ( this.time > this.duration || this.time < 0 ) {
  7604. this.direction *= -1;
  7605. if ( this.time > this.duration ) {
  7606. this.time = this.duration;
  7607. this.directionBackwards = true;
  7608. }
  7609. if ( this.time < 0 ) {
  7610. this.time = 0;
  7611. this.directionBackwards = false;
  7612. }
  7613. }
  7614. } else {
  7615. this.time = this.time % this.duration;
  7616. if ( this.time < 0 ) this.time += this.duration;
  7617. }
  7618. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  7619. if ( keyframe !== this.currentKeyframe ) {
  7620. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  7621. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  7622. this.morphTargetInfluences[ keyframe ] = 0;
  7623. this.lastKeyframe = this.currentKeyframe;
  7624. this.currentKeyframe = keyframe;
  7625. }
  7626. var mix = ( this.time % frameTime ) / frameTime;
  7627. if ( this.directionBackwards ) {
  7628. mix = 1 - mix;
  7629. }
  7630. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  7631. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  7632. };
  7633. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  7634. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  7635. object.duration = this.duration;
  7636. object.mirroredLoop = this.mirroredLoop;
  7637. object.time = this.time;
  7638. object.lastKeyframe = this.lastKeyframe;
  7639. object.currentKeyframe = this.currentKeyframe;
  7640. object.direction = this.direction;
  7641. object.directionBackwards = this.directionBackwards;
  7642. THREE.Mesh.prototype.clone.call( this, object );
  7643. return object;
  7644. };
  7645. /**
  7646. * @author alteredq / http://alteredqualia.com/
  7647. */
  7648. THREE.Ribbon = function ( geometry, material ) {
  7649. THREE.Object3D.call( this );
  7650. this.geometry = geometry;
  7651. this.material = material;
  7652. };
  7653. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  7654. THREE.Ribbon.prototype.clone = function ( object ) {
  7655. if ( object === undefined ) object = new THREE.Ribbon( this.geometry, this.material );
  7656. THREE.Object3D.prototype.clone.call( this, object );
  7657. return object;
  7658. };
  7659. /**
  7660. * @author mikael emtinger / http://gomo.se/
  7661. * @author alteredq / http://alteredqualia.com/
  7662. * @author mrdoob / http://mrdoob.com/
  7663. */
  7664. THREE.LOD = function () {
  7665. THREE.Object3D.call( this );
  7666. this.LODs = [];
  7667. };
  7668. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  7669. THREE.LOD.prototype.addLevel = function ( object3D, visibleAtDistance ) {
  7670. if ( visibleAtDistance === undefined ) {
  7671. visibleAtDistance = 0;
  7672. }
  7673. visibleAtDistance = Math.abs( visibleAtDistance );
  7674. for ( var l = 0; l < this.LODs.length; l ++ ) {
  7675. if ( visibleAtDistance < this.LODs[ l ].visibleAtDistance ) {
  7676. break;
  7677. }
  7678. }
  7679. this.LODs.splice( l, 0, { visibleAtDistance: visibleAtDistance, object3D: object3D } );
  7680. this.add( object3D );
  7681. };
  7682. THREE.LOD.prototype.update = function ( camera ) {
  7683. if ( this.LODs.length > 1 ) {
  7684. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  7685. var inverse = camera.matrixWorldInverse;
  7686. 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] );
  7687. this.LODs[ 0 ].object3D.visible = true;
  7688. for ( var l = 1; l < this.LODs.length; l ++ ) {
  7689. if( distance >= this.LODs[ l ].visibleAtDistance ) {
  7690. this.LODs[ l - 1 ].object3D.visible = false;
  7691. this.LODs[ l ].object3D.visible = true;
  7692. } else {
  7693. break;
  7694. }
  7695. }
  7696. for( ; l < this.LODs.length; l ++ ) {
  7697. this.LODs[ l ].object3D.visible = false;
  7698. }
  7699. }
  7700. };
  7701. THREE.LOD.prototype.clone = function () {
  7702. // TODO
  7703. };
  7704. /**
  7705. * @author mikael emtinger / http://gomo.se/
  7706. * @author alteredq / http://alteredqualia.com/
  7707. */
  7708. THREE.Sprite = function ( material ) {
  7709. THREE.Object3D.call( this );
  7710. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  7711. this.rotation3d = this.rotation;
  7712. this.rotation = 0;
  7713. };
  7714. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  7715. /*
  7716. * Custom update matrix
  7717. */
  7718. THREE.Sprite.prototype.updateMatrix = function () {
  7719. this.matrix.setPosition( this.position );
  7720. this.rotation3d.set( 0, 0, this.rotation );
  7721. this.matrix.setRotationFromEuler( this.rotation3d );
  7722. if ( this.scale.x !== 1 || this.scale.y !== 1 ) {
  7723. this.matrix.scale( this.scale );
  7724. }
  7725. this.matrixWorldNeedsUpdate = true;
  7726. };
  7727. THREE.Sprite.prototype.clone = function ( object ) {
  7728. if ( object === undefined ) object = new THREE.Sprite( this.material );
  7729. THREE.Object3D.prototype.clone.call( this, object );
  7730. return object;
  7731. };
  7732. /**
  7733. * @author mrdoob / http://mrdoob.com/
  7734. */
  7735. THREE.Scene = function () {
  7736. THREE.Object3D.call( this );
  7737. this.fog = null;
  7738. this.overrideMaterial = null;
  7739. this.matrixAutoUpdate = false;
  7740. this.__objects = [];
  7741. this.__lights = [];
  7742. this.__objectsAdded = [];
  7743. this.__objectsRemoved = [];
  7744. };
  7745. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  7746. THREE.Scene.prototype.__addObject = function ( object ) {
  7747. if ( object instanceof THREE.Light ) {
  7748. if ( this.__lights.indexOf( object ) === - 1 ) {
  7749. this.__lights.push( object );
  7750. }
  7751. if ( object.target && object.target.parent === undefined ) {
  7752. this.add( object.target );
  7753. }
  7754. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  7755. if ( this.__objects.indexOf( object ) === - 1 ) {
  7756. this.__objects.push( object );
  7757. this.__objectsAdded.push( object );
  7758. // check if previously removed
  7759. var i = this.__objectsRemoved.indexOf( object );
  7760. if ( i !== -1 ) {
  7761. this.__objectsRemoved.splice( i, 1 );
  7762. }
  7763. }
  7764. }
  7765. for ( var c = 0; c < object.children.length; c ++ ) {
  7766. this.__addObject( object.children[ c ] );
  7767. }
  7768. };
  7769. THREE.Scene.prototype.__removeObject = function ( object ) {
  7770. if ( object instanceof THREE.Light ) {
  7771. var i = this.__lights.indexOf( object );
  7772. if ( i !== -1 ) {
  7773. this.__lights.splice( i, 1 );
  7774. }
  7775. } else if ( !( object instanceof THREE.Camera ) ) {
  7776. var i = this.__objects.indexOf( object );
  7777. if( i !== -1 ) {
  7778. this.__objects.splice( i, 1 );
  7779. this.__objectsRemoved.push( object );
  7780. // check if previously added
  7781. var ai = this.__objectsAdded.indexOf( object );
  7782. if ( ai !== -1 ) {
  7783. this.__objectsAdded.splice( ai, 1 );
  7784. }
  7785. }
  7786. }
  7787. for ( var c = 0; c < object.children.length; c ++ ) {
  7788. this.__removeObject( object.children[ c ] );
  7789. }
  7790. };
  7791. /**
  7792. * @author mrdoob / http://mrdoob.com/
  7793. * @author alteredq / http://alteredqualia.com/
  7794. */
  7795. THREE.Fog = function ( hex, near, far ) {
  7796. this.name = '';
  7797. this.color = new THREE.Color( hex );
  7798. this.near = ( near !== undefined ) ? near : 1;
  7799. this.far = ( far !== undefined ) ? far : 1000;
  7800. };
  7801. THREE.Fog.prototype.clone = function () {
  7802. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  7803. };
  7804. /**
  7805. * @author mrdoob / http://mrdoob.com/
  7806. * @author alteredq / http://alteredqualia.com/
  7807. */
  7808. THREE.FogExp2 = function ( hex, density ) {
  7809. this.name = '';
  7810. this.color = new THREE.Color( hex );
  7811. this.density = ( density !== undefined ) ? density : 0.00025;
  7812. };
  7813. THREE.FogExp2.prototype.clone = function () {
  7814. return new THREE.FogExp2( this.color.getHex(), this.density );
  7815. };
  7816. /**
  7817. * @author mrdoob / http://mrdoob.com/
  7818. */
  7819. THREE.CanvasRenderer = function ( parameters ) {
  7820. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  7821. parameters = parameters || {};
  7822. var _this = this,
  7823. _renderData, _elements, _lights,
  7824. _projector = new THREE.Projector(),
  7825. _canvas = parameters.canvas !== undefined
  7826. ? parameters.canvas
  7827. : document.createElement( 'canvas' ),
  7828. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  7829. _context = _canvas.getContext( '2d' ),
  7830. _clearColor = new THREE.Color( 0x000000 ),
  7831. _clearOpacity = 0,
  7832. _contextGlobalAlpha = 1,
  7833. _contextGlobalCompositeOperation = 0,
  7834. _contextStrokeStyle = null,
  7835. _contextFillStyle = null,
  7836. _contextLineWidth = null,
  7837. _contextLineCap = null,
  7838. _contextLineJoin = null,
  7839. _v1, _v2, _v3, _v4,
  7840. _v5 = new THREE.RenderableVertex(),
  7841. _v6 = new THREE.RenderableVertex(),
  7842. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  7843. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  7844. _color = new THREE.Color(),
  7845. _color1 = new THREE.Color(),
  7846. _color2 = new THREE.Color(),
  7847. _color3 = new THREE.Color(),
  7848. _color4 = new THREE.Color(),
  7849. _diffuseColor = new THREE.Color(),
  7850. _emissiveColor = new THREE.Color(),
  7851. _lightColor = new THREE.Color(),
  7852. _patterns = {}, _imagedatas = {},
  7853. _near, _far,
  7854. _image, _uvs,
  7855. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  7856. _clipBox = new THREE.Box2(),
  7857. _clearBox = new THREE.Box2(),
  7858. _elemBox = new THREE.Box2(),
  7859. _enableLighting = false,
  7860. _ambientLight = new THREE.Color(),
  7861. _directionalLights = new THREE.Color(),
  7862. _pointLights = new THREE.Color(),
  7863. _pi2 = Math.PI * 2,
  7864. _vector3 = new THREE.Vector3(), // Needed for PointLight
  7865. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  7866. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  7867. _pixelMap = document.createElement( 'canvas' );
  7868. _pixelMap.width = _pixelMap.height = 2;
  7869. _pixelMapContext = _pixelMap.getContext( '2d' );
  7870. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  7871. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  7872. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  7873. _pixelMapData = _pixelMapImage.data;
  7874. _gradientMap = document.createElement( 'canvas' );
  7875. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  7876. _gradientMapContext = _gradientMap.getContext( '2d' );
  7877. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  7878. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  7879. _gradientMapQuality --; // Fix UVs
  7880. this.domElement = _canvas;
  7881. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  7882. ? parameters.devicePixelRatio
  7883. : window.devicePixelRatio !== undefined
  7884. ? window.devicePixelRatio
  7885. : 1;
  7886. this.autoClear = true;
  7887. this.sortObjects = true;
  7888. this.sortElements = true;
  7889. this.info = {
  7890. render: {
  7891. vertices: 0,
  7892. faces: 0
  7893. }
  7894. }
  7895. this.setSize = function ( width, height ) {
  7896. _canvasWidth = width * this.devicePixelRatio;
  7897. _canvasHeight = height * this.devicePixelRatio;
  7898. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  7899. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  7900. _canvas.width = _canvasWidth;
  7901. _canvas.height = _canvasHeight;
  7902. _canvas.style.width = width + 'px';
  7903. _canvas.style.height = height + 'px';
  7904. _clipBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  7905. _clipBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  7906. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  7907. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  7908. _contextGlobalAlpha = 1;
  7909. _contextGlobalCompositeOperation = 0;
  7910. _contextStrokeStyle = null;
  7911. _contextFillStyle = null;
  7912. _contextLineWidth = null;
  7913. _contextLineCap = null;
  7914. _contextLineJoin = null;
  7915. };
  7916. this.setClearColor = function ( color, opacity ) {
  7917. _clearColor.copy( color );
  7918. _clearOpacity = opacity !== undefined ? opacity : 1;
  7919. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  7920. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  7921. };
  7922. this.setClearColorHex = function ( hex, opacity ) {
  7923. _clearColor.setHex( hex );
  7924. _clearOpacity = opacity !== undefined ? opacity : 1;
  7925. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  7926. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  7927. };
  7928. this.getMaxAnisotropy = function () {
  7929. return 0;
  7930. };
  7931. this.clear = function () {
  7932. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  7933. if ( _clearBox.empty() === false ) {
  7934. _clearBox.intersect( _clipBox );
  7935. _clearBox.expandByScalar( 2 );
  7936. if ( _clearOpacity < 1 ) {
  7937. _context.clearRect( _clearBox.min.x | 0, _clearBox.min.y | 0, ( _clearBox.max.x - _clearBox.min.x ) | 0, ( _clearBox.max.y - _clearBox.min.y ) | 0 );
  7938. }
  7939. if ( _clearOpacity > 0 ) {
  7940. setBlending( THREE.NormalBlending );
  7941. setOpacity( 1 );
  7942. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearOpacity + ')' );
  7943. _context.fillRect( _clearBox.min.x | 0, _clearBox.min.y | 0, ( _clearBox.max.x - _clearBox.min.x ) | 0, ( _clearBox.max.y - _clearBox.min.y ) | 0 );
  7944. }
  7945. _clearBox.makeEmpty();
  7946. }
  7947. };
  7948. this.render = function ( scene, camera ) {
  7949. if ( camera instanceof THREE.Camera === false ) {
  7950. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  7951. return;
  7952. }
  7953. if ( this.autoClear === true ) {
  7954. this.clear();
  7955. }
  7956. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  7957. _this.info.render.vertices = 0;
  7958. _this.info.render.faces = 0;
  7959. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  7960. _elements = _renderData.elements;
  7961. _lights = _renderData.lights;
  7962. /* DEBUG
  7963. _context.fillStyle = 'rgba( 0, 255, 255, 0.5 )';
  7964. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  7965. */
  7966. _enableLighting = _lights.length > 0;
  7967. if ( _enableLighting === true ) {
  7968. calculateLights();
  7969. }
  7970. for ( var e = 0, el = _elements.length; e < el; e++ ) {
  7971. var element = _elements[ e ];
  7972. var material = element.material;
  7973. if ( material === undefined || material.visible === false ) continue;
  7974. _elemBox.makeEmpty();
  7975. if ( element instanceof THREE.RenderableParticle ) {
  7976. _v1 = element;
  7977. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  7978. renderParticle( _v1, element, material, scene );
  7979. } else if ( element instanceof THREE.RenderableLine ) {
  7980. _v1 = element.v1; _v2 = element.v2;
  7981. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7982. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7983. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen ] );
  7984. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  7985. renderLine( _v1, _v2, element, material, scene );
  7986. }
  7987. } else if ( element instanceof THREE.RenderableFace3 ) {
  7988. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  7989. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7990. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7991. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  7992. if ( material.overdraw === true ) {
  7993. expand( _v1.positionScreen, _v2.positionScreen );
  7994. expand( _v2.positionScreen, _v3.positionScreen );
  7995. expand( _v3.positionScreen, _v1.positionScreen );
  7996. }
  7997. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen, _v3.positionScreen ] );
  7998. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  7999. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material, scene );
  8000. }
  8001. } else if ( element instanceof THREE.RenderableFace4 ) {
  8002. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  8003. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8004. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8005. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8006. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  8007. _v5.positionScreen.copy( _v2.positionScreen );
  8008. _v6.positionScreen.copy( _v4.positionScreen );
  8009. if ( material.overdraw === true ) {
  8010. expand( _v1.positionScreen, _v2.positionScreen );
  8011. expand( _v2.positionScreen, _v4.positionScreen );
  8012. expand( _v4.positionScreen, _v1.positionScreen );
  8013. expand( _v3.positionScreen, _v5.positionScreen );
  8014. expand( _v3.positionScreen, _v6.positionScreen );
  8015. }
  8016. _elemBox.setFromPoints( [ _v1.positionScreen, _v2.positionScreen, _v3.positionScreen, _v4.positionScreen ] );
  8017. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8018. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material, scene );
  8019. }
  8020. }
  8021. /* DEBUG
  8022. _context.lineWidth = 1;
  8023. _context.strokeStyle = 'rgba( 0, 255, 0, 0.5 )';
  8024. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  8025. */
  8026. _clearBox.union( _elemBox );
  8027. }
  8028. /* DEBUG
  8029. _context.lineWidth = 1;
  8030. _context.strokeStyle = 'rgba( 255, 0, 0, 0.5 )';
  8031. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  8032. */
  8033. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  8034. //
  8035. function calculateLights() {
  8036. _ambientLight.setRGB( 0, 0, 0 );
  8037. _directionalLights.setRGB( 0, 0, 0 );
  8038. _pointLights.setRGB( 0, 0, 0 );
  8039. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8040. var light = _lights[ l ];
  8041. var lightColor = light.color;
  8042. if ( light instanceof THREE.AmbientLight ) {
  8043. _ambientLight.add( lightColor );
  8044. } else if ( light instanceof THREE.DirectionalLight ) {
  8045. // for particles
  8046. _directionalLights.add( lightColor );
  8047. } else if ( light instanceof THREE.PointLight ) {
  8048. // for particles
  8049. _pointLights.add( lightColor );
  8050. }
  8051. }
  8052. }
  8053. function calculateLight( position, normal, color ) {
  8054. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8055. var light = _lights[ l ];
  8056. _lightColor.copy( light.color );
  8057. if ( light instanceof THREE.DirectionalLight ) {
  8058. var lightPosition = light.matrixWorld.getPosition().normalize();
  8059. var amount = normal.dot( lightPosition );
  8060. if ( amount <= 0 ) continue;
  8061. amount *= light.intensity;
  8062. color.add( _lightColor.multiplyScalar( amount ) );
  8063. } else if ( light instanceof THREE.PointLight ) {
  8064. var lightPosition = light.matrixWorld.getPosition();
  8065. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  8066. if ( amount <= 0 ) continue;
  8067. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  8068. if ( amount == 0 ) continue;
  8069. amount *= light.intensity;
  8070. color.add( _lightColor.multiplyScalar( amount ) );
  8071. }
  8072. }
  8073. }
  8074. function renderParticle( v1, element, material, scene ) {
  8075. setOpacity( material.opacity );
  8076. setBlending( material.blending );
  8077. var width, height, scaleX, scaleY,
  8078. bitmap, bitmapWidth, bitmapHeight;
  8079. if ( material instanceof THREE.ParticleBasicMaterial ) {
  8080. if ( material.map === null ) {
  8081. scaleX = element.object.scale.x;
  8082. scaleY = element.object.scale.y;
  8083. // TODO: Be able to disable this
  8084. scaleX *= element.scale.x * _canvasWidthHalf;
  8085. scaleY *= element.scale.y * _canvasHeightHalf;
  8086. _elemBox.min.set( v1.x - scaleX, v1.y - scaleY );
  8087. _elemBox.max.set( v1.x + scaleX, v1.y + scaleY );
  8088. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8089. return;
  8090. }
  8091. setFillStyle( material.color.getStyle() );
  8092. _context.save();
  8093. _context.translate( v1.x, v1.y );
  8094. _context.rotate( - element.rotation );
  8095. _context.scale( scaleX, scaleY );
  8096. _context.fillRect( -1, -1, 2, 2 );
  8097. _context.restore();
  8098. } else {
  8099. bitmap = material.map.image;
  8100. bitmapWidth = bitmap.width >> 1;
  8101. bitmapHeight = bitmap.height >> 1;
  8102. scaleX = element.scale.x * _canvasWidthHalf;
  8103. scaleY = element.scale.y * _canvasHeightHalf;
  8104. width = scaleX * bitmapWidth;
  8105. height = scaleY * bitmapHeight;
  8106. // TODO: Rotations break this...
  8107. _elemBox.min.set( v1.x - width, v1.y - height );
  8108. _elemBox.max.set( v1.x + width, v1.y + height );
  8109. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8110. return;
  8111. }
  8112. _context.save();
  8113. _context.translate( v1.x, v1.y );
  8114. _context.rotate( - element.rotation );
  8115. _context.scale( scaleX, - scaleY );
  8116. _context.translate( - bitmapWidth, - bitmapHeight );
  8117. _context.drawImage( bitmap, 0, 0 );
  8118. _context.restore();
  8119. }
  8120. /* DEBUG
  8121. setStrokeStyle( 'rgb(255,255,0)' );
  8122. _context.beginPath();
  8123. _context.moveTo( v1.x - 10, v1.y );
  8124. _context.lineTo( v1.x + 10, v1.y );
  8125. _context.moveTo( v1.x, v1.y - 10 );
  8126. _context.lineTo( v1.x, v1.y + 10 );
  8127. _context.stroke();
  8128. */
  8129. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  8130. width = element.scale.x * _canvasWidthHalf;
  8131. height = element.scale.y * _canvasHeightHalf;
  8132. _elemBox.min.set( v1.x - width, v1.y - height );
  8133. _elemBox.max.set( v1.x + width, v1.y + height );
  8134. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  8135. return;
  8136. }
  8137. setStrokeStyle( material.color.getStyle() );
  8138. setFillStyle( material.color.getStyle() );
  8139. _context.save();
  8140. _context.translate( v1.x, v1.y );
  8141. _context.rotate( - element.rotation );
  8142. _context.scale( width, height );
  8143. material.program( _context );
  8144. _context.restore();
  8145. }
  8146. }
  8147. function renderLine( v1, v2, element, material, scene ) {
  8148. setOpacity( material.opacity );
  8149. setBlending( material.blending );
  8150. _context.beginPath();
  8151. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  8152. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  8153. if ( material instanceof THREE.LineBasicMaterial ) {
  8154. setLineWidth( material.linewidth );
  8155. setLineCap( material.linecap );
  8156. setLineJoin( material.linejoin );
  8157. setStrokeStyle( material.color.getStyle() );
  8158. _context.stroke();
  8159. _elemBox.expandByScalar( material.linewidth * 2 );
  8160. }
  8161. }
  8162. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material, scene ) {
  8163. _this.info.render.vertices += 3;
  8164. _this.info.render.faces ++;
  8165. setOpacity( material.opacity );
  8166. setBlending( material.blending );
  8167. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8168. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8169. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8170. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  8171. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null && material.map === null ) {
  8172. _diffuseColor.copy( material.color );
  8173. _emissiveColor.copy( material.emissive );
  8174. if ( material.vertexColors === THREE.FaceColors ) {
  8175. _diffuseColor.multiply( element.color );
  8176. }
  8177. if ( _enableLighting === true ) {
  8178. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  8179. _color1.copy( _ambientLight );
  8180. _color2.copy( _ambientLight );
  8181. _color3.copy( _ambientLight );
  8182. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  8183. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  8184. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color3 );
  8185. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  8186. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  8187. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  8188. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8189. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8190. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8191. } else {
  8192. _color.copy( _ambientLight );
  8193. calculateLight( element.centroidModel, element.normalModel, _color );
  8194. _color.multiply( _diffuseColor ).add( _emissiveColor );
  8195. material.wireframe === true
  8196. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8197. : fillPath( _color );
  8198. }
  8199. } else {
  8200. material.wireframe === true
  8201. ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8202. : fillPath( material.color );
  8203. }
  8204. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8205. if ( material.map !== null ) {
  8206. if ( material.map.mapping instanceof THREE.UVMapping ) {
  8207. _uvs = element.uvs[ 0 ];
  8208. 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 );
  8209. }
  8210. } else if ( material.envMap !== null ) {
  8211. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  8212. _vector3.copy( element.vertexNormalsModelView[ uv1 ] );
  8213. _uv1x = 0.5 * _vector3.x + 0.5;
  8214. _uv1y = 0.5 * _vector3.y + 0.5;
  8215. _vector3.copy( element.vertexNormalsModelView[ uv2 ] );
  8216. _uv2x = 0.5 * _vector3.x + 0.5;
  8217. _uv2y = 0.5 * _vector3.y + 0.5;
  8218. _vector3.copy( element.vertexNormalsModelView[ uv3 ] );
  8219. _uv3x = 0.5 * _vector3.x + 0.5;
  8220. _uv3y = 0.5 * _vector3.y + 0.5;
  8221. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  8222. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  8223. }*/
  8224. } else {
  8225. _color.copy( material.color );
  8226. if ( material.vertexColors === THREE.FaceColors ) {
  8227. _color.multiply( element.color );
  8228. }
  8229. material.wireframe === true
  8230. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8231. : fillPath( _color );
  8232. }
  8233. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8234. _near = camera.near;
  8235. _far = camera.far;
  8236. var depth;
  8237. depth = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  8238. _color1.setRGB( depth, depth, depth );
  8239. depth = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far )
  8240. _color2.setRGB( depth, depth, depth );
  8241. depth = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  8242. _color3.setRGB( depth, depth, depth );
  8243. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8244. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8245. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8246. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8247. var normal;
  8248. if ( material.shading == THREE.FlatShading ) {
  8249. normal = element.normalModelView;
  8250. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8251. material.wireframe === true
  8252. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8253. : fillPath( _color );
  8254. } else if ( material.shading == THREE.SmoothShading ) {
  8255. normal = element.vertexNormalsModelView[ uv1 ];
  8256. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8257. normal = element.vertexNormalsModelView[ uv2 ];
  8258. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8259. normal = element.vertexNormalsModelView[ uv3 ];
  8260. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8261. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  8262. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8263. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8264. }
  8265. }
  8266. }
  8267. function renderFace4( v1, v2, v3, v4, v5, v6, element, material, scene ) {
  8268. _this.info.render.vertices += 4;
  8269. _this.info.render.faces ++;
  8270. setOpacity( material.opacity );
  8271. setBlending( material.blending );
  8272. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  8273. // Let renderFace3() handle this
  8274. renderFace3( v1, v2, v4, 0, 1, 3, element, material, scene );
  8275. renderFace3( v5, v3, v6, 1, 2, 3, element, material, scene );
  8276. return;
  8277. }
  8278. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8279. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8280. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8281. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  8282. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  8283. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  8284. if ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8285. _diffuseColor.copy( material.color );
  8286. _emissiveColor.copy( material.emissive );
  8287. if ( material.vertexColors === THREE.FaceColors ) {
  8288. _diffuseColor.multiply( element.color );
  8289. }
  8290. if ( _enableLighting === true ) {
  8291. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  8292. _color1.copy( _ambientLight );
  8293. _color2.copy( _ambientLight );
  8294. _color3.copy( _ambientLight );
  8295. _color4.copy( _ambientLight );
  8296. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  8297. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  8298. calculateLight( element.v4.positionWorld, element.vertexNormalsModel[ 3 ], _color3 );
  8299. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color4 );
  8300. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  8301. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  8302. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  8303. _color4.multiply( _diffuseColor ).add( _emissiveColor );
  8304. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8305. // TODO: UVs are incorrect, v4->v3?
  8306. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8307. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8308. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8309. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8310. } else {
  8311. _color.copy( _ambientLight );
  8312. calculateLight( element.centroidModel, element.normalModel, _color );
  8313. _color.multiply( _diffuseColor ).add( _emissiveColor );
  8314. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8315. material.wireframe === true
  8316. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8317. : fillPath( _color );
  8318. }
  8319. } else {
  8320. _color.addColors( _diffuseColor, _emissiveColor );
  8321. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8322. material.wireframe === true
  8323. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8324. : fillPath( _color );
  8325. }
  8326. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  8327. _color.copy( material.color );
  8328. if ( material.vertexColors === THREE.FaceColors ) {
  8329. _color.multiply( element.color );
  8330. }
  8331. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8332. material.wireframe === true
  8333. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8334. : fillPath( _color );
  8335. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8336. var normal;
  8337. if ( material.shading == THREE.FlatShading ) {
  8338. normal = element.normalModelView;
  8339. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8340. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8341. material.wireframe === true
  8342. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8343. : fillPath( _color );
  8344. } else if ( material.shading == THREE.SmoothShading ) {
  8345. normal = element.vertexNormalsModelView[ 0 ];
  8346. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8347. normal = element.vertexNormalsModelView[ 1 ];
  8348. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8349. normal = element.vertexNormalsModelView[ 3 ];
  8350. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8351. normal = element.vertexNormalsModelView[ 2 ];
  8352. _color4.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  8353. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8354. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8355. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8356. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8357. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8358. }
  8359. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8360. _near = camera.near;
  8361. _far = camera.far;
  8362. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  8363. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  8364. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z * v4.positionScreen.w, _near, _far );
  8365. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  8366. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8367. // TODO: UVs are incorrect, v4->v3?
  8368. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8369. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8370. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8371. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8372. }
  8373. }
  8374. //
  8375. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  8376. _context.beginPath();
  8377. _context.moveTo( x0, y0 );
  8378. _context.lineTo( x1, y1 );
  8379. _context.lineTo( x2, y2 );
  8380. _context.closePath();
  8381. }
  8382. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  8383. _context.beginPath();
  8384. _context.moveTo( x0, y0 );
  8385. _context.lineTo( x1, y1 );
  8386. _context.lineTo( x2, y2 );
  8387. _context.lineTo( x3, y3 );
  8388. _context.closePath();
  8389. }
  8390. function strokePath( color, linewidth, linecap, linejoin ) {
  8391. setLineWidth( linewidth );
  8392. setLineCap( linecap );
  8393. setLineJoin( linejoin );
  8394. setStrokeStyle( color.getStyle() );
  8395. _context.stroke();
  8396. _elemBox.expandByScalar( linewidth * 2 );
  8397. }
  8398. function fillPath( color ) {
  8399. setFillStyle( color.getStyle() );
  8400. _context.fill();
  8401. }
  8402. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  8403. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  8404. if ( texture.needsUpdate === true ) {
  8405. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  8406. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  8407. _patterns[ texture.id ] = _context.createPattern(
  8408. texture.image, repeatX === true && repeatY === true
  8409. ? 'repeat'
  8410. : repeatX === true && repeatY === false
  8411. ? 'repeat-x'
  8412. : repeatX === false && repeatY === true
  8413. ? 'repeat-y'
  8414. : 'no-repeat'
  8415. );
  8416. texture.needsUpdate = false;
  8417. }
  8418. _patterns[ texture.id ] === undefined
  8419. ? setFillStyle( 'rgba(0,0,0,1)' )
  8420. : setFillStyle( _patterns[ texture.id ] );
  8421. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8422. var a, b, c, d, e, f, det, idet,
  8423. offsetX = texture.offset.x / texture.repeat.x,
  8424. offsetY = texture.offset.y / texture.repeat.y,
  8425. width = texture.image.width * texture.repeat.x,
  8426. height = texture.image.height * texture.repeat.y;
  8427. u0 = ( u0 + offsetX ) * width;
  8428. v0 = ( 1.0 - v0 + offsetY ) * height;
  8429. u1 = ( u1 + offsetX ) * width;
  8430. v1 = ( 1.0 - v1 + offsetY ) * height;
  8431. u2 = ( u2 + offsetX ) * width;
  8432. v2 = ( 1.0 - v2 + offsetY ) * height;
  8433. x1 -= x0; y1 -= y0;
  8434. x2 -= x0; y2 -= y0;
  8435. u1 -= u0; v1 -= v0;
  8436. u2 -= u0; v2 -= v0;
  8437. det = u1 * v2 - u2 * v1;
  8438. if ( det === 0 ) {
  8439. if ( _imagedatas[ texture.id ] === undefined ) {
  8440. var canvas = document.createElement( 'canvas' )
  8441. canvas.width = texture.image.width;
  8442. canvas.height = texture.image.height;
  8443. var context = canvas.getContext( '2d' );
  8444. context.drawImage( texture.image, 0, 0 );
  8445. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  8446. }
  8447. var data = _imagedatas[ texture.id ];
  8448. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  8449. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  8450. fillPath( _color );
  8451. return;
  8452. }
  8453. idet = 1 / det;
  8454. a = ( v2 * x1 - v1 * x2 ) * idet;
  8455. b = ( v2 * y1 - v1 * y2 ) * idet;
  8456. c = ( u1 * x2 - u2 * x1 ) * idet;
  8457. d = ( u1 * y2 - u2 * y1 ) * idet;
  8458. e = x0 - a * u0 - c * v0;
  8459. f = y0 - b * u0 - d * v0;
  8460. _context.save();
  8461. _context.transform( a, b, c, d, e, f );
  8462. _context.fill();
  8463. _context.restore();
  8464. }
  8465. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  8466. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8467. var a, b, c, d, e, f, det, idet,
  8468. width = image.width - 1,
  8469. height = image.height - 1;
  8470. u0 *= width; v0 *= height;
  8471. u1 *= width; v1 *= height;
  8472. u2 *= width; v2 *= height;
  8473. x1 -= x0; y1 -= y0;
  8474. x2 -= x0; y2 -= y0;
  8475. u1 -= u0; v1 -= v0;
  8476. u2 -= u0; v2 -= v0;
  8477. det = u1 * v2 - u2 * v1;
  8478. idet = 1 / det;
  8479. a = ( v2 * x1 - v1 * x2 ) * idet;
  8480. b = ( v2 * y1 - v1 * y2 ) * idet;
  8481. c = ( u1 * x2 - u2 * x1 ) * idet;
  8482. d = ( u1 * y2 - u2 * y1 ) * idet;
  8483. e = x0 - a * u0 - c * v0;
  8484. f = y0 - b * u0 - d * v0;
  8485. _context.save();
  8486. _context.transform( a, b, c, d, e, f );
  8487. _context.clip();
  8488. _context.drawImage( image, 0, 0 );
  8489. _context.restore();
  8490. }
  8491. function getGradientTexture( color1, color2, color3, color4 ) {
  8492. // http://mrdoob.com/blog/post/710
  8493. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  8494. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  8495. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  8496. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  8497. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  8498. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  8499. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  8500. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  8501. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  8502. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  8503. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  8504. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  8505. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  8506. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  8507. return _gradientMap;
  8508. }
  8509. function smoothstep( value, min, max ) {
  8510. var x = ( value - min ) / ( max - min );
  8511. return x * x * ( 3 - 2 * x );
  8512. }
  8513. // Hide anti-alias gaps
  8514. function expand( v1, v2 ) {
  8515. var x = v2.x - v1.x, y = v2.y - v1.y,
  8516. det = x * x + y * y, idet;
  8517. if ( det === 0 ) return;
  8518. idet = 1 / Math.sqrt( det );
  8519. x *= idet; y *= idet;
  8520. v2.x += x; v2.y += y;
  8521. v1.x -= x; v1.y -= y;
  8522. }
  8523. };
  8524. // Context cached methods.
  8525. function setOpacity( value ) {
  8526. if ( _contextGlobalAlpha !== value ) {
  8527. _context.globalAlpha = value;
  8528. _contextGlobalAlpha = value;
  8529. }
  8530. }
  8531. function setBlending( value ) {
  8532. if ( _contextGlobalCompositeOperation !== value ) {
  8533. if ( value === THREE.NormalBlending ) {
  8534. _context.globalCompositeOperation = 'source-over';
  8535. } else if ( value === THREE.AdditiveBlending ) {
  8536. _context.globalCompositeOperation = 'lighter';
  8537. } else if ( value === THREE.SubtractiveBlending ) {
  8538. _context.globalCompositeOperation = 'darker';
  8539. }
  8540. _contextGlobalCompositeOperation = value;
  8541. }
  8542. }
  8543. function setLineWidth( value ) {
  8544. if ( _contextLineWidth !== value ) {
  8545. _context.lineWidth = value;
  8546. _contextLineWidth = value;
  8547. }
  8548. }
  8549. function setLineCap( value ) {
  8550. // "butt", "round", "square"
  8551. if ( _contextLineCap !== value ) {
  8552. _context.lineCap = value;
  8553. _contextLineCap = value;
  8554. }
  8555. }
  8556. function setLineJoin( value ) {
  8557. // "round", "bevel", "miter"
  8558. if ( _contextLineJoin !== value ) {
  8559. _context.lineJoin = value;
  8560. _contextLineJoin = value;
  8561. }
  8562. }
  8563. function setStrokeStyle( value ) {
  8564. if ( _contextStrokeStyle !== value ) {
  8565. _context.strokeStyle = value;
  8566. _contextStrokeStyle = value;
  8567. }
  8568. }
  8569. function setFillStyle( value ) {
  8570. if ( _contextFillStyle !== value ) {
  8571. _context.fillStyle = value;
  8572. _contextFillStyle = value;
  8573. }
  8574. }
  8575. };
  8576. /**
  8577. * @author alteredq / http://alteredqualia.com/
  8578. * @author mrdoob / http://mrdoob.com/
  8579. * @author mikael emtinger / http://gomo.se/
  8580. */
  8581. THREE.ShaderChunk = {
  8582. // FOG
  8583. fog_pars_fragment: [
  8584. "#ifdef USE_FOG",
  8585. "uniform vec3 fogColor;",
  8586. "#ifdef FOG_EXP2",
  8587. "uniform float fogDensity;",
  8588. "#else",
  8589. "uniform float fogNear;",
  8590. "uniform float fogFar;",
  8591. "#endif",
  8592. "#endif"
  8593. ].join("\n"),
  8594. fog_fragment: [
  8595. "#ifdef USE_FOG",
  8596. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  8597. "#ifdef FOG_EXP2",
  8598. "const float LOG2 = 1.442695;",
  8599. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  8600. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  8601. "#else",
  8602. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  8603. "#endif",
  8604. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  8605. "#endif"
  8606. ].join("\n"),
  8607. // ENVIRONMENT MAP
  8608. envmap_pars_fragment: [
  8609. "#ifdef USE_ENVMAP",
  8610. "uniform float reflectivity;",
  8611. "uniform samplerCube envMap;",
  8612. "uniform float flipEnvMap;",
  8613. "uniform int combine;",
  8614. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8615. "uniform bool useRefract;",
  8616. "uniform float refractionRatio;",
  8617. "#else",
  8618. "varying vec3 vReflect;",
  8619. "#endif",
  8620. "#endif"
  8621. ].join("\n"),
  8622. envmap_fragment: [
  8623. "#ifdef USE_ENVMAP",
  8624. "vec3 reflectVec;",
  8625. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8626. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  8627. "if ( useRefract ) {",
  8628. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  8629. "} else { ",
  8630. "reflectVec = reflect( cameraToVertex, normal );",
  8631. "}",
  8632. "#else",
  8633. "reflectVec = vReflect;",
  8634. "#endif",
  8635. "#ifdef DOUBLE_SIDED",
  8636. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  8637. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8638. "#else",
  8639. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8640. "#endif",
  8641. "#ifdef GAMMA_INPUT",
  8642. "cubeColor.xyz *= cubeColor.xyz;",
  8643. "#endif",
  8644. "if ( combine == 1 ) {",
  8645. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  8646. "} else if ( combine == 2 ) {",
  8647. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  8648. "} else {",
  8649. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  8650. "}",
  8651. "#endif"
  8652. ].join("\n"),
  8653. envmap_pars_vertex: [
  8654. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8655. "varying vec3 vReflect;",
  8656. "uniform float refractionRatio;",
  8657. "uniform bool useRefract;",
  8658. "#endif"
  8659. ].join("\n"),
  8660. worldpos_vertex : [
  8661. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  8662. "#ifdef USE_SKINNING",
  8663. "vec4 worldPosition = modelMatrix * skinned;",
  8664. "#endif",
  8665. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8666. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  8667. "#endif",
  8668. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8669. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  8670. "#endif",
  8671. "#endif"
  8672. ].join("\n"),
  8673. envmap_vertex : [
  8674. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8675. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  8676. "worldNormal = normalize( worldNormal );",
  8677. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  8678. "if ( useRefract ) {",
  8679. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  8680. "} else {",
  8681. "vReflect = reflect( cameraToVertex, worldNormal );",
  8682. "}",
  8683. "#endif"
  8684. ].join("\n"),
  8685. // COLOR MAP (particles)
  8686. map_particle_pars_fragment: [
  8687. "#ifdef USE_MAP",
  8688. "uniform sampler2D map;",
  8689. "#endif"
  8690. ].join("\n"),
  8691. map_particle_fragment: [
  8692. "#ifdef USE_MAP",
  8693. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  8694. "#endif"
  8695. ].join("\n"),
  8696. // COLOR MAP (triangles)
  8697. map_pars_vertex: [
  8698. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8699. "varying vec2 vUv;",
  8700. "uniform vec4 offsetRepeat;",
  8701. "#endif"
  8702. ].join("\n"),
  8703. map_pars_fragment: [
  8704. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8705. "varying vec2 vUv;",
  8706. "#endif",
  8707. "#ifdef USE_MAP",
  8708. "uniform sampler2D map;",
  8709. "#endif"
  8710. ].join("\n"),
  8711. map_vertex: [
  8712. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8713. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  8714. "#endif"
  8715. ].join("\n"),
  8716. map_fragment: [
  8717. "#ifdef USE_MAP",
  8718. "vec4 texelColor = texture2D( map, vUv );",
  8719. "#ifdef GAMMA_INPUT",
  8720. "texelColor.xyz *= texelColor.xyz;",
  8721. "#endif",
  8722. "gl_FragColor = gl_FragColor * texelColor;",
  8723. "#endif"
  8724. ].join("\n"),
  8725. // LIGHT MAP
  8726. lightmap_pars_fragment: [
  8727. "#ifdef USE_LIGHTMAP",
  8728. "varying vec2 vUv2;",
  8729. "uniform sampler2D lightMap;",
  8730. "#endif"
  8731. ].join("\n"),
  8732. lightmap_pars_vertex: [
  8733. "#ifdef USE_LIGHTMAP",
  8734. "varying vec2 vUv2;",
  8735. "#endif"
  8736. ].join("\n"),
  8737. lightmap_fragment: [
  8738. "#ifdef USE_LIGHTMAP",
  8739. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  8740. "#endif"
  8741. ].join("\n"),
  8742. lightmap_vertex: [
  8743. "#ifdef USE_LIGHTMAP",
  8744. "vUv2 = uv2;",
  8745. "#endif"
  8746. ].join("\n"),
  8747. // BUMP MAP
  8748. bumpmap_pars_fragment: [
  8749. "#ifdef USE_BUMPMAP",
  8750. "uniform sampler2D bumpMap;",
  8751. "uniform float bumpScale;",
  8752. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  8753. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  8754. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8755. "vec2 dHdxy_fwd() {",
  8756. "vec2 dSTdx = dFdx( vUv );",
  8757. "vec2 dSTdy = dFdy( vUv );",
  8758. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  8759. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  8760. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  8761. "return vec2( dBx, dBy );",
  8762. "}",
  8763. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  8764. "vec3 vSigmaX = dFdx( surf_pos );",
  8765. "vec3 vSigmaY = dFdy( surf_pos );",
  8766. "vec3 vN = surf_norm;", // normalized
  8767. "vec3 R1 = cross( vSigmaY, vN );",
  8768. "vec3 R2 = cross( vN, vSigmaX );",
  8769. "float fDet = dot( vSigmaX, R1 );",
  8770. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  8771. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  8772. "}",
  8773. "#endif"
  8774. ].join("\n"),
  8775. // NORMAL MAP
  8776. normalmap_pars_fragment: [
  8777. "#ifdef USE_NORMALMAP",
  8778. "uniform sampler2D normalMap;",
  8779. "uniform vec2 normalScale;",
  8780. // Per-Pixel Tangent Space Normal Mapping
  8781. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  8782. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  8783. "vec3 q0 = dFdx( eye_pos.xyz );",
  8784. "vec3 q1 = dFdy( eye_pos.xyz );",
  8785. "vec2 st0 = dFdx( vUv.st );",
  8786. "vec2 st1 = dFdy( vUv.st );",
  8787. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  8788. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  8789. "vec3 N = normalize( surf_norm );",
  8790. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  8791. "mapN.xy = normalScale * mapN.xy;",
  8792. "mat3 tsn = mat3( S, T, N );",
  8793. "return normalize( tsn * mapN );",
  8794. "}",
  8795. "#endif"
  8796. ].join("\n"),
  8797. // SPECULAR MAP
  8798. specularmap_pars_fragment: [
  8799. "#ifdef USE_SPECULARMAP",
  8800. "uniform sampler2D specularMap;",
  8801. "#endif"
  8802. ].join("\n"),
  8803. specularmap_fragment: [
  8804. "float specularStrength;",
  8805. "#ifdef USE_SPECULARMAP",
  8806. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  8807. "specularStrength = texelSpecular.r;",
  8808. "#else",
  8809. "specularStrength = 1.0;",
  8810. "#endif"
  8811. ].join("\n"),
  8812. // LIGHTS LAMBERT
  8813. lights_lambert_pars_vertex: [
  8814. "uniform vec3 ambient;",
  8815. "uniform vec3 diffuse;",
  8816. "uniform vec3 emissive;",
  8817. "uniform vec3 ambientLightColor;",
  8818. "#if MAX_DIR_LIGHTS > 0",
  8819. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  8820. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  8821. "#endif",
  8822. "#if MAX_HEMI_LIGHTS > 0",
  8823. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  8824. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  8825. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  8826. "#endif",
  8827. "#if MAX_POINT_LIGHTS > 0",
  8828. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  8829. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8830. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8831. "#endif",
  8832. "#if MAX_SPOT_LIGHTS > 0",
  8833. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  8834. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8835. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  8836. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8837. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  8838. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  8839. "#endif",
  8840. "#ifdef WRAP_AROUND",
  8841. "uniform vec3 wrapRGB;",
  8842. "#endif"
  8843. ].join("\n"),
  8844. lights_lambert_vertex: [
  8845. "vLightFront = vec3( 0.0 );",
  8846. "#ifdef DOUBLE_SIDED",
  8847. "vLightBack = vec3( 0.0 );",
  8848. "#endif",
  8849. "transformedNormal = normalize( transformedNormal );",
  8850. "#if MAX_DIR_LIGHTS > 0",
  8851. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  8852. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  8853. "vec3 dirVector = normalize( lDirection.xyz );",
  8854. "float dotProduct = dot( transformedNormal, dirVector );",
  8855. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8856. "#ifdef DOUBLE_SIDED",
  8857. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8858. "#ifdef WRAP_AROUND",
  8859. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8860. "#endif",
  8861. "#endif",
  8862. "#ifdef WRAP_AROUND",
  8863. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8864. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  8865. "#ifdef DOUBLE_SIDED",
  8866. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  8867. "#endif",
  8868. "#endif",
  8869. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  8870. "#ifdef DOUBLE_SIDED",
  8871. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  8872. "#endif",
  8873. "}",
  8874. "#endif",
  8875. "#if MAX_POINT_LIGHTS > 0",
  8876. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8877. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8878. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8879. "float lDistance = 1.0;",
  8880. "if ( pointLightDistance[ i ] > 0.0 )",
  8881. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8882. "lVector = normalize( lVector );",
  8883. "float dotProduct = dot( transformedNormal, lVector );",
  8884. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8885. "#ifdef DOUBLE_SIDED",
  8886. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8887. "#ifdef WRAP_AROUND",
  8888. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8889. "#endif",
  8890. "#endif",
  8891. "#ifdef WRAP_AROUND",
  8892. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8893. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  8894. "#ifdef DOUBLE_SIDED",
  8895. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  8896. "#endif",
  8897. "#endif",
  8898. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  8899. "#ifdef DOUBLE_SIDED",
  8900. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  8901. "#endif",
  8902. "}",
  8903. "#endif",
  8904. "#if MAX_SPOT_LIGHTS > 0",
  8905. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8906. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8907. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8908. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  8909. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  8910. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  8911. "float lDistance = 1.0;",
  8912. "if ( spotLightDistance[ i ] > 0.0 )",
  8913. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8914. "lVector = normalize( lVector );",
  8915. "float dotProduct = dot( transformedNormal, lVector );",
  8916. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8917. "#ifdef DOUBLE_SIDED",
  8918. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8919. "#ifdef WRAP_AROUND",
  8920. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8921. "#endif",
  8922. "#endif",
  8923. "#ifdef WRAP_AROUND",
  8924. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8925. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  8926. "#ifdef DOUBLE_SIDED",
  8927. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  8928. "#endif",
  8929. "#endif",
  8930. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  8931. "#ifdef DOUBLE_SIDED",
  8932. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  8933. "#endif",
  8934. "}",
  8935. "}",
  8936. "#endif",
  8937. "#if MAX_HEMI_LIGHTS > 0",
  8938. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  8939. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  8940. "vec3 lVector = normalize( lDirection.xyz );",
  8941. "float dotProduct = dot( transformedNormal, lVector );",
  8942. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  8943. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  8944. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  8945. "#ifdef DOUBLE_SIDED",
  8946. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  8947. "#endif",
  8948. "}",
  8949. "#endif",
  8950. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  8951. "#ifdef DOUBLE_SIDED",
  8952. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  8953. "#endif"
  8954. ].join("\n"),
  8955. // LIGHTS PHONG
  8956. lights_phong_pars_vertex: [
  8957. "#ifndef PHONG_PER_PIXEL",
  8958. "#if MAX_POINT_LIGHTS > 0",
  8959. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8960. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8961. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  8962. "#endif",
  8963. "#if MAX_SPOT_LIGHTS > 0",
  8964. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8965. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8966. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  8967. "#endif",
  8968. "#endif",
  8969. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8970. "varying vec3 vWorldPosition;",
  8971. "#endif"
  8972. ].join("\n"),
  8973. lights_phong_vertex: [
  8974. "#ifndef PHONG_PER_PIXEL",
  8975. "#if MAX_POINT_LIGHTS > 0",
  8976. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8977. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8978. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8979. "float lDistance = 1.0;",
  8980. "if ( pointLightDistance[ i ] > 0.0 )",
  8981. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8982. "vPointLight[ i ] = vec4( lVector, lDistance );",
  8983. "}",
  8984. "#endif",
  8985. "#if MAX_SPOT_LIGHTS > 0",
  8986. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8987. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8988. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8989. "float lDistance = 1.0;",
  8990. "if ( spotLightDistance[ i ] > 0.0 )",
  8991. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8992. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  8993. "}",
  8994. "#endif",
  8995. "#endif",
  8996. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8997. "vWorldPosition = worldPosition.xyz;",
  8998. "#endif"
  8999. ].join("\n"),
  9000. lights_phong_pars_fragment: [
  9001. "uniform vec3 ambientLightColor;",
  9002. "#if MAX_DIR_LIGHTS > 0",
  9003. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9004. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9005. "#endif",
  9006. "#if MAX_HEMI_LIGHTS > 0",
  9007. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9008. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9009. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9010. "#endif",
  9011. "#if MAX_POINT_LIGHTS > 0",
  9012. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9013. "#ifdef PHONG_PER_PIXEL",
  9014. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9015. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9016. "#else",
  9017. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9018. "#endif",
  9019. "#endif",
  9020. "#if MAX_SPOT_LIGHTS > 0",
  9021. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9022. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9023. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9024. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9025. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9026. "#ifdef PHONG_PER_PIXEL",
  9027. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9028. "#else",
  9029. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9030. "#endif",
  9031. "#endif",
  9032. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9033. "varying vec3 vWorldPosition;",
  9034. "#endif",
  9035. "#ifdef WRAP_AROUND",
  9036. "uniform vec3 wrapRGB;",
  9037. "#endif",
  9038. "varying vec3 vViewPosition;",
  9039. "varying vec3 vNormal;"
  9040. ].join("\n"),
  9041. lights_phong_fragment: [
  9042. "vec3 normal = normalize( vNormal );",
  9043. "vec3 viewPosition = normalize( vViewPosition );",
  9044. "#ifdef DOUBLE_SIDED",
  9045. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9046. "#endif",
  9047. "#ifdef USE_NORMALMAP",
  9048. "normal = perturbNormal2Arb( -viewPosition, normal );",
  9049. "#elif defined( USE_BUMPMAP )",
  9050. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  9051. "#endif",
  9052. "#if MAX_POINT_LIGHTS > 0",
  9053. "vec3 pointDiffuse = vec3( 0.0 );",
  9054. "vec3 pointSpecular = vec3( 0.0 );",
  9055. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9056. "#ifdef PHONG_PER_PIXEL",
  9057. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9058. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9059. "float lDistance = 1.0;",
  9060. "if ( pointLightDistance[ i ] > 0.0 )",
  9061. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9062. "lVector = normalize( lVector );",
  9063. "#else",
  9064. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  9065. "float lDistance = vPointLight[ i ].w;",
  9066. "#endif",
  9067. // diffuse
  9068. "float dotProduct = dot( normal, lVector );",
  9069. "#ifdef WRAP_AROUND",
  9070. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  9071. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9072. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  9073. "#else",
  9074. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  9075. "#endif",
  9076. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  9077. // specular
  9078. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  9079. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  9080. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  9081. "#ifdef PHYSICALLY_BASED_SHADING",
  9082. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9083. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9084. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  9085. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  9086. "#else",
  9087. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  9088. "#endif",
  9089. "}",
  9090. "#endif",
  9091. "#if MAX_SPOT_LIGHTS > 0",
  9092. "vec3 spotDiffuse = vec3( 0.0 );",
  9093. "vec3 spotSpecular = vec3( 0.0 );",
  9094. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9095. "#ifdef PHONG_PER_PIXEL",
  9096. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9097. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9098. "float lDistance = 1.0;",
  9099. "if ( spotLightDistance[ i ] > 0.0 )",
  9100. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9101. "lVector = normalize( lVector );",
  9102. "#else",
  9103. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  9104. "float lDistance = vSpotLight[ i ].w;",
  9105. "#endif",
  9106. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  9107. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9108. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9109. // diffuse
  9110. "float dotProduct = dot( normal, lVector );",
  9111. "#ifdef WRAP_AROUND",
  9112. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  9113. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9114. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  9115. "#else",
  9116. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  9117. "#endif",
  9118. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  9119. // specular
  9120. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  9121. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  9122. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  9123. "#ifdef PHYSICALLY_BASED_SHADING",
  9124. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9125. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9126. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  9127. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  9128. "#else",
  9129. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  9130. "#endif",
  9131. "}",
  9132. "}",
  9133. "#endif",
  9134. "#if MAX_DIR_LIGHTS > 0",
  9135. "vec3 dirDiffuse = vec3( 0.0 );",
  9136. "vec3 dirSpecular = vec3( 0.0 );" ,
  9137. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9138. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9139. "vec3 dirVector = normalize( lDirection.xyz );",
  9140. // diffuse
  9141. "float dotProduct = dot( normal, dirVector );",
  9142. "#ifdef WRAP_AROUND",
  9143. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  9144. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9145. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  9146. "#else",
  9147. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  9148. "#endif",
  9149. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  9150. // specular
  9151. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  9152. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  9153. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  9154. "#ifdef PHYSICALLY_BASED_SHADING",
  9155. /*
  9156. // fresnel term from skin shader
  9157. "const float F0 = 0.128;",
  9158. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  9159. "float exponential = pow( base, 5.0 );",
  9160. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  9161. */
  9162. /*
  9163. // fresnel term from fresnel shader
  9164. "const float mFresnelBias = 0.08;",
  9165. "const float mFresnelScale = 0.3;",
  9166. "const float mFresnelPower = 5.0;",
  9167. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  9168. */
  9169. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9170. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9171. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  9172. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  9173. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  9174. "#else",
  9175. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  9176. "#endif",
  9177. "}",
  9178. "#endif",
  9179. "#if MAX_HEMI_LIGHTS > 0",
  9180. "vec3 hemiDiffuse = vec3( 0.0 );",
  9181. "vec3 hemiSpecular = vec3( 0.0 );" ,
  9182. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9183. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9184. "vec3 lVector = normalize( lDirection.xyz );",
  9185. // diffuse
  9186. "float dotProduct = dot( normal, lVector );",
  9187. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9188. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9189. "hemiDiffuse += diffuse * hemiColor;",
  9190. // specular (sky light)
  9191. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  9192. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  9193. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  9194. // specular (ground light)
  9195. "vec3 lVectorGround = -lVector;",
  9196. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  9197. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  9198. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  9199. "#ifdef PHYSICALLY_BASED_SHADING",
  9200. "float dotProductGround = dot( normal, lVectorGround );",
  9201. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9202. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9203. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  9204. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  9205. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  9206. "#else",
  9207. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  9208. "#endif",
  9209. "}",
  9210. "#endif",
  9211. "vec3 totalDiffuse = vec3( 0.0 );",
  9212. "vec3 totalSpecular = vec3( 0.0 );",
  9213. "#if MAX_DIR_LIGHTS > 0",
  9214. "totalDiffuse += dirDiffuse;",
  9215. "totalSpecular += dirSpecular;",
  9216. "#endif",
  9217. "#if MAX_HEMI_LIGHTS > 0",
  9218. "totalDiffuse += hemiDiffuse;",
  9219. "totalSpecular += hemiSpecular;",
  9220. "#endif",
  9221. "#if MAX_POINT_LIGHTS > 0",
  9222. "totalDiffuse += pointDiffuse;",
  9223. "totalSpecular += pointSpecular;",
  9224. "#endif",
  9225. "#if MAX_SPOT_LIGHTS > 0",
  9226. "totalDiffuse += spotDiffuse;",
  9227. "totalSpecular += spotSpecular;",
  9228. "#endif",
  9229. "#ifdef METAL",
  9230. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  9231. "#else",
  9232. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  9233. "#endif"
  9234. ].join("\n"),
  9235. // VERTEX COLORS
  9236. color_pars_fragment: [
  9237. "#ifdef USE_COLOR",
  9238. "varying vec3 vColor;",
  9239. "#endif"
  9240. ].join("\n"),
  9241. color_fragment: [
  9242. "#ifdef USE_COLOR",
  9243. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  9244. "#endif"
  9245. ].join("\n"),
  9246. color_pars_vertex: [
  9247. "#ifdef USE_COLOR",
  9248. "varying vec3 vColor;",
  9249. "#endif"
  9250. ].join("\n"),
  9251. color_vertex: [
  9252. "#ifdef USE_COLOR",
  9253. "#ifdef GAMMA_INPUT",
  9254. "vColor = color * color;",
  9255. "#else",
  9256. "vColor = color;",
  9257. "#endif",
  9258. "#endif"
  9259. ].join("\n"),
  9260. // SKINNING
  9261. skinning_pars_vertex: [
  9262. "#ifdef USE_SKINNING",
  9263. "#ifdef BONE_TEXTURE",
  9264. "uniform sampler2D boneTexture;",
  9265. "mat4 getBoneMatrix( const in float i ) {",
  9266. "float j = i * 4.0;",
  9267. "float x = mod( j, N_BONE_PIXEL_X );",
  9268. "float y = floor( j / N_BONE_PIXEL_X );",
  9269. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  9270. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  9271. "y = dy * ( y + 0.5 );",
  9272. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  9273. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  9274. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  9275. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  9276. "mat4 bone = mat4( v1, v2, v3, v4 );",
  9277. "return bone;",
  9278. "}",
  9279. "#else",
  9280. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  9281. "mat4 getBoneMatrix( const in float i ) {",
  9282. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  9283. "return bone;",
  9284. "}",
  9285. "#endif",
  9286. "#endif"
  9287. ].join("\n"),
  9288. skinbase_vertex: [
  9289. "#ifdef USE_SKINNING",
  9290. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  9291. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  9292. "#endif"
  9293. ].join("\n"),
  9294. skinning_vertex: [
  9295. "#ifdef USE_SKINNING",
  9296. "#ifdef USE_MORPHTARGETS",
  9297. "vec4 skinVertex = vec4( morphed, 1.0 );",
  9298. "#else",
  9299. "vec4 skinVertex = vec4( position, 1.0 );",
  9300. "#endif",
  9301. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  9302. "skinned += boneMatY * skinVertex * skinWeight.y;",
  9303. "#endif"
  9304. ].join("\n"),
  9305. // MORPHING
  9306. morphtarget_pars_vertex: [
  9307. "#ifdef USE_MORPHTARGETS",
  9308. "#ifndef USE_MORPHNORMALS",
  9309. "uniform float morphTargetInfluences[ 8 ];",
  9310. "#else",
  9311. "uniform float morphTargetInfluences[ 4 ];",
  9312. "#endif",
  9313. "#endif"
  9314. ].join("\n"),
  9315. morphtarget_vertex: [
  9316. "#ifdef USE_MORPHTARGETS",
  9317. "vec3 morphed = vec3( 0.0 );",
  9318. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  9319. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  9320. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  9321. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  9322. "#ifndef USE_MORPHNORMALS",
  9323. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  9324. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  9325. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  9326. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  9327. "#endif",
  9328. "morphed += position;",
  9329. "#endif"
  9330. ].join("\n"),
  9331. default_vertex : [
  9332. "vec4 mvPosition;",
  9333. "#ifdef USE_SKINNING",
  9334. "mvPosition = modelViewMatrix * skinned;",
  9335. "#endif",
  9336. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  9337. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  9338. "#endif",
  9339. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  9340. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9341. "#endif",
  9342. "gl_Position = projectionMatrix * mvPosition;"
  9343. ].join("\n"),
  9344. morphnormal_vertex: [
  9345. "#ifdef USE_MORPHNORMALS",
  9346. "vec3 morphedNormal = vec3( 0.0 );",
  9347. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  9348. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  9349. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  9350. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  9351. "morphedNormal += normal;",
  9352. "#endif"
  9353. ].join("\n"),
  9354. skinnormal_vertex: [
  9355. "#ifdef USE_SKINNING",
  9356. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  9357. "skinMatrix += skinWeight.y * boneMatY;",
  9358. "#ifdef USE_MORPHNORMALS",
  9359. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  9360. "#else",
  9361. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  9362. "#endif",
  9363. "#endif"
  9364. ].join("\n"),
  9365. defaultnormal_vertex: [
  9366. "vec3 objectNormal;",
  9367. "#ifdef USE_SKINNING",
  9368. "objectNormal = skinnedNormal.xyz;",
  9369. "#endif",
  9370. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  9371. "objectNormal = morphedNormal;",
  9372. "#endif",
  9373. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  9374. "objectNormal = normal;",
  9375. "#endif",
  9376. "#ifdef FLIP_SIDED",
  9377. "objectNormal = -objectNormal;",
  9378. "#endif",
  9379. "vec3 transformedNormal = normalMatrix * objectNormal;"
  9380. ].join("\n"),
  9381. // SHADOW MAP
  9382. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  9383. // http://spidergl.org/example.php?id=6
  9384. // http://fabiensanglard.net/shadowmapping
  9385. shadowmap_pars_fragment: [
  9386. "#ifdef USE_SHADOWMAP",
  9387. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  9388. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  9389. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  9390. "uniform float shadowBias[ MAX_SHADOWS ];",
  9391. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  9392. "float unpackDepth( const in vec4 rgba_depth ) {",
  9393. "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 );",
  9394. "float depth = dot( rgba_depth, bit_shift );",
  9395. "return depth;",
  9396. "}",
  9397. "#endif"
  9398. ].join("\n"),
  9399. shadowmap_fragment: [
  9400. "#ifdef USE_SHADOWMAP",
  9401. "#ifdef SHADOWMAP_DEBUG",
  9402. "vec3 frustumColors[3];",
  9403. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  9404. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  9405. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  9406. "#endif",
  9407. "#ifdef SHADOWMAP_CASCADE",
  9408. "int inFrustumCount = 0;",
  9409. "#endif",
  9410. "float fDepth;",
  9411. "vec3 shadowColor = vec3( 1.0 );",
  9412. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  9413. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  9414. // "if ( something && something )" breaks ATI OpenGL shader compiler
  9415. // "if ( all( something, something ) )" using this instead
  9416. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  9417. "bool inFrustum = all( inFrustumVec );",
  9418. // don't shadow pixels outside of light frustum
  9419. // use just first frustum (for cascades)
  9420. // don't shadow pixels behind far plane of light frustum
  9421. "#ifdef SHADOWMAP_CASCADE",
  9422. "inFrustumCount += int( inFrustum );",
  9423. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  9424. "#else",
  9425. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  9426. "#endif",
  9427. "bool frustumTest = all( frustumTestVec );",
  9428. "if ( frustumTest ) {",
  9429. "shadowCoord.z += shadowBias[ i ];",
  9430. "#if defined( SHADOWMAP_TYPE_PCF )",
  9431. // Percentage-close filtering
  9432. // (9 pixel kernel)
  9433. // http://fabiensanglard.net/shadowmappingPCF/
  9434. "float shadow = 0.0;",
  9435. /*
  9436. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  9437. // must enroll loop manually
  9438. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  9439. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  9440. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  9441. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  9442. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  9443. "float fDepth = unpackDepth( rgbaDepth );",
  9444. "if ( fDepth < shadowCoord.z )",
  9445. "shadow += 1.0;",
  9446. "}",
  9447. "shadow /= 9.0;",
  9448. */
  9449. "const float shadowDelta = 1.0 / 9.0;",
  9450. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  9451. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  9452. "float dx0 = -1.25 * xPixelOffset;",
  9453. "float dy0 = -1.25 * yPixelOffset;",
  9454. "float dx1 = 1.25 * xPixelOffset;",
  9455. "float dy1 = 1.25 * yPixelOffset;",
  9456. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  9457. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9458. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  9459. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9460. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  9461. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9462. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  9463. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9464. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  9465. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9466. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  9467. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9468. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  9469. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9470. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  9471. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9472. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  9473. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9474. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  9475. "#elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  9476. // Percentage-close filtering
  9477. // (9 pixel kernel)
  9478. // http://fabiensanglard.net/shadowmappingPCF/
  9479. "float shadow = 0.0;",
  9480. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  9481. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  9482. "float dx0 = -1.0 * xPixelOffset;",
  9483. "float dy0 = -1.0 * yPixelOffset;",
  9484. "float dx1 = 1.0 * xPixelOffset;",
  9485. "float dy1 = 1.0 * yPixelOffset;",
  9486. "mat3 shadowKernel;",
  9487. "mat3 depthKernel;",
  9488. "depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  9489. "if ( depthKernel[0][0] < shadowCoord.z ) shadowKernel[0][0] = 0.25;",
  9490. "else shadowKernel[0][0] = 0.0;",
  9491. "depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  9492. "if ( depthKernel[0][1] < shadowCoord.z ) shadowKernel[0][1] = 0.25;",
  9493. "else shadowKernel[0][1] = 0.0;",
  9494. "depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  9495. "if ( depthKernel[0][2] < shadowCoord.z ) shadowKernel[0][2] = 0.25;",
  9496. "else shadowKernel[0][2] = 0.0;",
  9497. "depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  9498. "if ( depthKernel[1][0] < shadowCoord.z ) shadowKernel[1][0] = 0.25;",
  9499. "else shadowKernel[1][0] = 0.0;",
  9500. "depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  9501. "if ( depthKernel[1][1] < shadowCoord.z ) shadowKernel[1][1] = 0.25;",
  9502. "else shadowKernel[1][1] = 0.0;",
  9503. "depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  9504. "if ( depthKernel[1][2] < shadowCoord.z ) shadowKernel[1][2] = 0.25;",
  9505. "else shadowKernel[1][2] = 0.0;",
  9506. "depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  9507. "if ( depthKernel[2][0] < shadowCoord.z ) shadowKernel[2][0] = 0.25;",
  9508. "else shadowKernel[2][0] = 0.0;",
  9509. "depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  9510. "if ( depthKernel[2][1] < shadowCoord.z ) shadowKernel[2][1] = 0.25;",
  9511. "else shadowKernel[2][1] = 0.0;",
  9512. "depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  9513. "if ( depthKernel[2][2] < shadowCoord.z ) shadowKernel[2][2] = 0.25;",
  9514. "else shadowKernel[2][2] = 0.0;",
  9515. "vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  9516. "shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  9517. "shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  9518. "vec4 shadowValues;",
  9519. "shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  9520. "shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  9521. "shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  9522. "shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  9523. "shadow = dot( shadowValues, vec4( 1.0 ) );",
  9524. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  9525. "#else",
  9526. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  9527. "float fDepth = unpackDepth( rgbaDepth );",
  9528. "if ( fDepth < shadowCoord.z )",
  9529. // spot with multiple shadows is darker
  9530. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  9531. // spot with multiple shadows has the same color as single shadow spot
  9532. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  9533. "#endif",
  9534. "}",
  9535. "#ifdef SHADOWMAP_DEBUG",
  9536. "#ifdef SHADOWMAP_CASCADE",
  9537. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  9538. "#else",
  9539. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  9540. "#endif",
  9541. "#endif",
  9542. "}",
  9543. "#ifdef GAMMA_OUTPUT",
  9544. "shadowColor *= shadowColor;",
  9545. "#endif",
  9546. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  9547. "#endif"
  9548. ].join("\n"),
  9549. shadowmap_pars_vertex: [
  9550. "#ifdef USE_SHADOWMAP",
  9551. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  9552. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  9553. "#endif"
  9554. ].join("\n"),
  9555. shadowmap_vertex: [
  9556. "#ifdef USE_SHADOWMAP",
  9557. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  9558. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  9559. "}",
  9560. "#endif"
  9561. ].join("\n"),
  9562. // ALPHATEST
  9563. alphatest_fragment: [
  9564. "#ifdef ALPHATEST",
  9565. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  9566. "#endif"
  9567. ].join("\n"),
  9568. // LINEAR SPACE
  9569. linear_to_gamma_fragment: [
  9570. "#ifdef GAMMA_OUTPUT",
  9571. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  9572. "#endif"
  9573. ].join("\n")
  9574. };
  9575. THREE.UniformsUtils = {
  9576. merge: function ( uniforms ) {
  9577. var u, p, tmp, merged = {};
  9578. for ( u = 0; u < uniforms.length; u ++ ) {
  9579. tmp = this.clone( uniforms[ u ] );
  9580. for ( p in tmp ) {
  9581. merged[ p ] = tmp[ p ];
  9582. }
  9583. }
  9584. return merged;
  9585. },
  9586. clone: function ( uniforms_src ) {
  9587. var u, p, parameter, parameter_src, uniforms_dst = {};
  9588. for ( u in uniforms_src ) {
  9589. uniforms_dst[ u ] = {};
  9590. for ( p in uniforms_src[ u ] ) {
  9591. parameter_src = uniforms_src[ u ][ p ];
  9592. if ( parameter_src instanceof THREE.Color ||
  9593. parameter_src instanceof THREE.Vector2 ||
  9594. parameter_src instanceof THREE.Vector3 ||
  9595. parameter_src instanceof THREE.Vector4 ||
  9596. parameter_src instanceof THREE.Matrix4 ||
  9597. parameter_src instanceof THREE.Texture ) {
  9598. uniforms_dst[ u ][ p ] = parameter_src.clone();
  9599. } else if ( parameter_src instanceof Array ) {
  9600. uniforms_dst[ u ][ p ] = parameter_src.slice();
  9601. } else {
  9602. uniforms_dst[ u ][ p ] = parameter_src;
  9603. }
  9604. }
  9605. }
  9606. return uniforms_dst;
  9607. }
  9608. };
  9609. THREE.UniformsLib = {
  9610. common: {
  9611. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9612. "opacity" : { type: "f", value: 1.0 },
  9613. "map" : { type: "t", value: null },
  9614. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  9615. "lightMap" : { type: "t", value: null },
  9616. "specularMap" : { type: "t", value: null },
  9617. "envMap" : { type: "t", value: null },
  9618. "flipEnvMap" : { type: "f", value: -1 },
  9619. "useRefract" : { type: "i", value: 0 },
  9620. "reflectivity" : { type: "f", value: 1.0 },
  9621. "refractionRatio" : { type: "f", value: 0.98 },
  9622. "combine" : { type: "i", value: 0 },
  9623. "morphTargetInfluences" : { type: "f", value: 0 }
  9624. },
  9625. bump: {
  9626. "bumpMap" : { type: "t", value: null },
  9627. "bumpScale" : { type: "f", value: 1 }
  9628. },
  9629. normalmap: {
  9630. "normalMap" : { type: "t", value: null },
  9631. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  9632. },
  9633. fog : {
  9634. "fogDensity" : { type: "f", value: 0.00025 },
  9635. "fogNear" : { type: "f", value: 1 },
  9636. "fogFar" : { type: "f", value: 2000 },
  9637. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9638. },
  9639. lights: {
  9640. "ambientLightColor" : { type: "fv", value: [] },
  9641. "directionalLightDirection" : { type: "fv", value: [] },
  9642. "directionalLightColor" : { type: "fv", value: [] },
  9643. "hemisphereLightDirection" : { type: "fv", value: [] },
  9644. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  9645. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  9646. "pointLightColor" : { type: "fv", value: [] },
  9647. "pointLightPosition" : { type: "fv", value: [] },
  9648. "pointLightDistance" : { type: "fv1", value: [] },
  9649. "spotLightColor" : { type: "fv", value: [] },
  9650. "spotLightPosition" : { type: "fv", value: [] },
  9651. "spotLightDirection" : { type: "fv", value: [] },
  9652. "spotLightDistance" : { type: "fv1", value: [] },
  9653. "spotLightAngleCos" : { type: "fv1", value: [] },
  9654. "spotLightExponent" : { type: "fv1", value: [] }
  9655. },
  9656. particle: {
  9657. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9658. "opacity" : { type: "f", value: 1.0 },
  9659. "size" : { type: "f", value: 1.0 },
  9660. "scale" : { type: "f", value: 1.0 },
  9661. "map" : { type: "t", value: null },
  9662. "fogDensity" : { type: "f", value: 0.00025 },
  9663. "fogNear" : { type: "f", value: 1 },
  9664. "fogFar" : { type: "f", value: 2000 },
  9665. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9666. },
  9667. shadowmap: {
  9668. "shadowMap": { type: "tv", value: [] },
  9669. "shadowMapSize": { type: "v2v", value: [] },
  9670. "shadowBias" : { type: "fv1", value: [] },
  9671. "shadowDarkness": { type: "fv1", value: [] },
  9672. "shadowMatrix" : { type: "m4v", value: [] }
  9673. }
  9674. };
  9675. THREE.ShaderLib = {
  9676. 'depth': {
  9677. uniforms: {
  9678. "mNear": { type: "f", value: 1.0 },
  9679. "mFar" : { type: "f", value: 2000.0 },
  9680. "opacity" : { type: "f", value: 1.0 }
  9681. },
  9682. vertexShader: [
  9683. "void main() {",
  9684. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  9685. "}"
  9686. ].join("\n"),
  9687. fragmentShader: [
  9688. "uniform float mNear;",
  9689. "uniform float mFar;",
  9690. "uniform float opacity;",
  9691. "void main() {",
  9692. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  9693. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  9694. "gl_FragColor = vec4( vec3( color ), opacity );",
  9695. "}"
  9696. ].join("\n")
  9697. },
  9698. 'normal': {
  9699. uniforms: {
  9700. "opacity" : { type: "f", value: 1.0 }
  9701. },
  9702. vertexShader: [
  9703. "varying vec3 vNormal;",
  9704. "void main() {",
  9705. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9706. "vNormal = normalize( normalMatrix * normal );",
  9707. "gl_Position = projectionMatrix * mvPosition;",
  9708. "}"
  9709. ].join("\n"),
  9710. fragmentShader: [
  9711. "uniform float opacity;",
  9712. "varying vec3 vNormal;",
  9713. "void main() {",
  9714. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  9715. "}"
  9716. ].join("\n")
  9717. },
  9718. 'basic': {
  9719. uniforms: THREE.UniformsUtils.merge( [
  9720. THREE.UniformsLib[ "common" ],
  9721. THREE.UniformsLib[ "fog" ],
  9722. THREE.UniformsLib[ "shadowmap" ]
  9723. ] ),
  9724. vertexShader: [
  9725. THREE.ShaderChunk[ "map_pars_vertex" ],
  9726. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9727. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9728. THREE.ShaderChunk[ "color_pars_vertex" ],
  9729. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9730. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9731. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9732. "void main() {",
  9733. THREE.ShaderChunk[ "map_vertex" ],
  9734. THREE.ShaderChunk[ "lightmap_vertex" ],
  9735. THREE.ShaderChunk[ "color_vertex" ],
  9736. THREE.ShaderChunk[ "skinbase_vertex" ],
  9737. "#ifdef USE_ENVMAP",
  9738. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9739. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9740. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9741. "#endif",
  9742. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9743. THREE.ShaderChunk[ "skinning_vertex" ],
  9744. THREE.ShaderChunk[ "default_vertex" ],
  9745. THREE.ShaderChunk[ "worldpos_vertex" ],
  9746. THREE.ShaderChunk[ "envmap_vertex" ],
  9747. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9748. "}"
  9749. ].join("\n"),
  9750. fragmentShader: [
  9751. "uniform vec3 diffuse;",
  9752. "uniform float opacity;",
  9753. THREE.ShaderChunk[ "color_pars_fragment" ],
  9754. THREE.ShaderChunk[ "map_pars_fragment" ],
  9755. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9756. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9757. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9758. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9759. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9760. "void main() {",
  9761. "gl_FragColor = vec4( diffuse, opacity );",
  9762. THREE.ShaderChunk[ "map_fragment" ],
  9763. THREE.ShaderChunk[ "alphatest_fragment" ],
  9764. THREE.ShaderChunk[ "specularmap_fragment" ],
  9765. THREE.ShaderChunk[ "lightmap_fragment" ],
  9766. THREE.ShaderChunk[ "color_fragment" ],
  9767. THREE.ShaderChunk[ "envmap_fragment" ],
  9768. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9769. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9770. THREE.ShaderChunk[ "fog_fragment" ],
  9771. "}"
  9772. ].join("\n")
  9773. },
  9774. 'lambert': {
  9775. uniforms: THREE.UniformsUtils.merge( [
  9776. THREE.UniformsLib[ "common" ],
  9777. THREE.UniformsLib[ "fog" ],
  9778. THREE.UniformsLib[ "lights" ],
  9779. THREE.UniformsLib[ "shadowmap" ],
  9780. {
  9781. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9782. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9783. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9784. }
  9785. ] ),
  9786. vertexShader: [
  9787. "#define LAMBERT",
  9788. "varying vec3 vLightFront;",
  9789. "#ifdef DOUBLE_SIDED",
  9790. "varying vec3 vLightBack;",
  9791. "#endif",
  9792. THREE.ShaderChunk[ "map_pars_vertex" ],
  9793. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9794. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9795. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  9796. THREE.ShaderChunk[ "color_pars_vertex" ],
  9797. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9798. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9799. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9800. "void main() {",
  9801. THREE.ShaderChunk[ "map_vertex" ],
  9802. THREE.ShaderChunk[ "lightmap_vertex" ],
  9803. THREE.ShaderChunk[ "color_vertex" ],
  9804. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9805. THREE.ShaderChunk[ "skinbase_vertex" ],
  9806. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9807. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9808. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9809. THREE.ShaderChunk[ "skinning_vertex" ],
  9810. THREE.ShaderChunk[ "default_vertex" ],
  9811. THREE.ShaderChunk[ "worldpos_vertex" ],
  9812. THREE.ShaderChunk[ "envmap_vertex" ],
  9813. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  9814. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9815. "}"
  9816. ].join("\n"),
  9817. fragmentShader: [
  9818. "uniform float opacity;",
  9819. "varying vec3 vLightFront;",
  9820. "#ifdef DOUBLE_SIDED",
  9821. "varying vec3 vLightBack;",
  9822. "#endif",
  9823. THREE.ShaderChunk[ "color_pars_fragment" ],
  9824. THREE.ShaderChunk[ "map_pars_fragment" ],
  9825. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9826. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9827. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9828. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9829. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9830. "void main() {",
  9831. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  9832. THREE.ShaderChunk[ "map_fragment" ],
  9833. THREE.ShaderChunk[ "alphatest_fragment" ],
  9834. THREE.ShaderChunk[ "specularmap_fragment" ],
  9835. "#ifdef DOUBLE_SIDED",
  9836. //"float isFront = float( gl_FrontFacing );",
  9837. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  9838. "if ( gl_FrontFacing )",
  9839. "gl_FragColor.xyz *= vLightFront;",
  9840. "else",
  9841. "gl_FragColor.xyz *= vLightBack;",
  9842. "#else",
  9843. "gl_FragColor.xyz *= vLightFront;",
  9844. "#endif",
  9845. THREE.ShaderChunk[ "lightmap_fragment" ],
  9846. THREE.ShaderChunk[ "color_fragment" ],
  9847. THREE.ShaderChunk[ "envmap_fragment" ],
  9848. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9849. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9850. THREE.ShaderChunk[ "fog_fragment" ],
  9851. "}"
  9852. ].join("\n")
  9853. },
  9854. 'phong': {
  9855. uniforms: THREE.UniformsUtils.merge( [
  9856. THREE.UniformsLib[ "common" ],
  9857. THREE.UniformsLib[ "bump" ],
  9858. THREE.UniformsLib[ "normalmap" ],
  9859. THREE.UniformsLib[ "fog" ],
  9860. THREE.UniformsLib[ "lights" ],
  9861. THREE.UniformsLib[ "shadowmap" ],
  9862. {
  9863. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9864. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9865. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  9866. "shininess": { type: "f", value: 30 },
  9867. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9868. }
  9869. ] ),
  9870. vertexShader: [
  9871. "#define PHONG",
  9872. "varying vec3 vViewPosition;",
  9873. "varying vec3 vNormal;",
  9874. THREE.ShaderChunk[ "map_pars_vertex" ],
  9875. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9876. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9877. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  9878. THREE.ShaderChunk[ "color_pars_vertex" ],
  9879. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9880. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9881. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9882. "void main() {",
  9883. THREE.ShaderChunk[ "map_vertex" ],
  9884. THREE.ShaderChunk[ "lightmap_vertex" ],
  9885. THREE.ShaderChunk[ "color_vertex" ],
  9886. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9887. THREE.ShaderChunk[ "skinbase_vertex" ],
  9888. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9889. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9890. "vNormal = normalize( transformedNormal );",
  9891. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9892. THREE.ShaderChunk[ "skinning_vertex" ],
  9893. THREE.ShaderChunk[ "default_vertex" ],
  9894. "vViewPosition = -mvPosition.xyz;",
  9895. THREE.ShaderChunk[ "worldpos_vertex" ],
  9896. THREE.ShaderChunk[ "envmap_vertex" ],
  9897. THREE.ShaderChunk[ "lights_phong_vertex" ],
  9898. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9899. "}"
  9900. ].join("\n"),
  9901. fragmentShader: [
  9902. "uniform vec3 diffuse;",
  9903. "uniform float opacity;",
  9904. "uniform vec3 ambient;",
  9905. "uniform vec3 emissive;",
  9906. "uniform vec3 specular;",
  9907. "uniform float shininess;",
  9908. THREE.ShaderChunk[ "color_pars_fragment" ],
  9909. THREE.ShaderChunk[ "map_pars_fragment" ],
  9910. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9911. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9912. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9913. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  9914. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9915. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  9916. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  9917. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9918. "void main() {",
  9919. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  9920. THREE.ShaderChunk[ "map_fragment" ],
  9921. THREE.ShaderChunk[ "alphatest_fragment" ],
  9922. THREE.ShaderChunk[ "specularmap_fragment" ],
  9923. THREE.ShaderChunk[ "lights_phong_fragment" ],
  9924. THREE.ShaderChunk[ "lightmap_fragment" ],
  9925. THREE.ShaderChunk[ "color_fragment" ],
  9926. THREE.ShaderChunk[ "envmap_fragment" ],
  9927. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9928. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9929. THREE.ShaderChunk[ "fog_fragment" ],
  9930. "}"
  9931. ].join("\n")
  9932. },
  9933. 'particle_basic': {
  9934. uniforms: THREE.UniformsUtils.merge( [
  9935. THREE.UniformsLib[ "particle" ],
  9936. THREE.UniformsLib[ "shadowmap" ]
  9937. ] ),
  9938. vertexShader: [
  9939. "uniform float size;",
  9940. "uniform float scale;",
  9941. THREE.ShaderChunk[ "color_pars_vertex" ],
  9942. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9943. "void main() {",
  9944. THREE.ShaderChunk[ "color_vertex" ],
  9945. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9946. "#ifdef USE_SIZEATTENUATION",
  9947. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  9948. "#else",
  9949. "gl_PointSize = size;",
  9950. "#endif",
  9951. "gl_Position = projectionMatrix * mvPosition;",
  9952. THREE.ShaderChunk[ "worldpos_vertex" ],
  9953. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9954. "}"
  9955. ].join("\n"),
  9956. fragmentShader: [
  9957. "uniform vec3 psColor;",
  9958. "uniform float opacity;",
  9959. THREE.ShaderChunk[ "color_pars_fragment" ],
  9960. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  9961. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9962. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9963. "void main() {",
  9964. "gl_FragColor = vec4( psColor, opacity );",
  9965. THREE.ShaderChunk[ "map_particle_fragment" ],
  9966. THREE.ShaderChunk[ "alphatest_fragment" ],
  9967. THREE.ShaderChunk[ "color_fragment" ],
  9968. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9969. THREE.ShaderChunk[ "fog_fragment" ],
  9970. "}"
  9971. ].join("\n")
  9972. },
  9973. 'dashed': {
  9974. uniforms: THREE.UniformsUtils.merge( [
  9975. THREE.UniformsLib[ "common" ],
  9976. THREE.UniformsLib[ "fog" ],
  9977. {
  9978. "scale": { type: "f", value: 1 },
  9979. "dashSize": { type: "f", value: 1 },
  9980. "totalSize": { type: "f", value: 2 }
  9981. }
  9982. ] ),
  9983. vertexShader: [
  9984. "uniform float scale;",
  9985. "attribute float lineDistance;",
  9986. "varying float vLineDistance;",
  9987. THREE.ShaderChunk[ "color_pars_vertex" ],
  9988. "void main() {",
  9989. THREE.ShaderChunk[ "color_vertex" ],
  9990. "vLineDistance = scale * lineDistance;",
  9991. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9992. "gl_Position = projectionMatrix * mvPosition;",
  9993. "}"
  9994. ].join("\n"),
  9995. fragmentShader: [
  9996. "uniform vec3 diffuse;",
  9997. "uniform float opacity;",
  9998. "uniform float dashSize;",
  9999. "uniform float totalSize;",
  10000. "varying float vLineDistance;",
  10001. THREE.ShaderChunk[ "color_pars_fragment" ],
  10002. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10003. "void main() {",
  10004. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  10005. "discard;",
  10006. "}",
  10007. "gl_FragColor = vec4( diffuse, opacity );",
  10008. THREE.ShaderChunk[ "color_fragment" ],
  10009. THREE.ShaderChunk[ "fog_fragment" ],
  10010. "}"
  10011. ].join("\n")
  10012. },
  10013. // Depth encoding into RGBA texture
  10014. // based on SpiderGL shadow map example
  10015. // http://spidergl.org/example.php?id=6
  10016. // originally from
  10017. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  10018. // see also here:
  10019. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  10020. 'depthRGBA': {
  10021. uniforms: {},
  10022. vertexShader: [
  10023. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10024. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10025. "void main() {",
  10026. THREE.ShaderChunk[ "skinbase_vertex" ],
  10027. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10028. THREE.ShaderChunk[ "skinning_vertex" ],
  10029. THREE.ShaderChunk[ "default_vertex" ],
  10030. "}"
  10031. ].join("\n"),
  10032. fragmentShader: [
  10033. "vec4 pack_depth( const in float depth ) {",
  10034. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  10035. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  10036. "vec4 res = fract( depth * bit_shift );",
  10037. "res -= res.xxyz * bit_mask;",
  10038. "return res;",
  10039. "}",
  10040. "void main() {",
  10041. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  10042. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  10043. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  10044. //"gl_FragData[ 0 ] = pack_depth( z );",
  10045. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  10046. "}"
  10047. ].join("\n")
  10048. }
  10049. };
  10050. /**
  10051. * @author supereggbert / http://www.paulbrunt.co.uk/
  10052. * @author mrdoob / http://mrdoob.com/
  10053. * @author alteredq / http://alteredqualia.com/
  10054. * @author szimek / https://github.com/szimek/
  10055. */
  10056. THREE.WebGLRenderer = function ( parameters ) {
  10057. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  10058. parameters = parameters || {};
  10059. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  10060. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  10061. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  10062. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  10063. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  10064. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  10065. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  10066. _clearColor = parameters.clearColor !== undefined ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ),
  10067. _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0;
  10068. // public properties
  10069. this.domElement = _canvas;
  10070. this.context = null;
  10071. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  10072. ? parameters.devicePixelRatio
  10073. : window.devicePixelRatio !== undefined
  10074. ? window.devicePixelRatio
  10075. : 1;
  10076. // clearing
  10077. this.autoClear = true;
  10078. this.autoClearColor = true;
  10079. this.autoClearDepth = true;
  10080. this.autoClearStencil = true;
  10081. // scene graph
  10082. this.sortObjects = true;
  10083. this.autoUpdateObjects = true;
  10084. this.autoUpdateScene = true;
  10085. // physically based shading
  10086. this.gammaInput = false;
  10087. this.gammaOutput = false;
  10088. this.physicallyBasedShading = false;
  10089. // shadow map
  10090. this.shadowMapEnabled = false;
  10091. this.shadowMapAutoUpdate = true;
  10092. this.shadowMapType = THREE.PCFShadowMap;
  10093. this.shadowMapCullFace = THREE.CullFaceFront;
  10094. this.shadowMapDebug = false;
  10095. this.shadowMapCascade = false;
  10096. // morphs
  10097. this.maxMorphTargets = 8;
  10098. this.maxMorphNormals = 4;
  10099. // flags
  10100. this.autoScaleCubemaps = true;
  10101. // custom render plugins
  10102. this.renderPluginsPre = [];
  10103. this.renderPluginsPost = [];
  10104. // info
  10105. this.info = {
  10106. memory: {
  10107. programs: 0,
  10108. geometries: 0,
  10109. textures: 0
  10110. },
  10111. render: {
  10112. calls: 0,
  10113. vertices: 0,
  10114. faces: 0,
  10115. points: 0
  10116. }
  10117. };
  10118. // internal properties
  10119. var _this = this,
  10120. _programs = [],
  10121. _programs_counter = 0,
  10122. // internal state cache
  10123. _currentProgram = null,
  10124. _currentFramebuffer = null,
  10125. _currentMaterialId = -1,
  10126. _currentGeometryGroupHash = null,
  10127. _currentCamera = null,
  10128. _geometryGroupCounter = 0,
  10129. _usedTextureUnits = 0,
  10130. // GL state cache
  10131. _oldDoubleSided = -1,
  10132. _oldFlipSided = -1,
  10133. _oldBlending = -1,
  10134. _oldBlendEquation = -1,
  10135. _oldBlendSrc = -1,
  10136. _oldBlendDst = -1,
  10137. _oldDepthTest = -1,
  10138. _oldDepthWrite = -1,
  10139. _oldPolygonOffset = null,
  10140. _oldPolygonOffsetFactor = null,
  10141. _oldPolygonOffsetUnits = null,
  10142. _oldLineWidth = null,
  10143. _viewportX = 0,
  10144. _viewportY = 0,
  10145. _viewportWidth = 0,
  10146. _viewportHeight = 0,
  10147. _currentWidth = 0,
  10148. _currentHeight = 0,
  10149. _enabledAttributes = {},
  10150. // frustum
  10151. _frustum = new THREE.Frustum(),
  10152. // camera matrices cache
  10153. _projScreenMatrix = new THREE.Matrix4(),
  10154. _projScreenMatrixPS = new THREE.Matrix4(),
  10155. _vector3 = new THREE.Vector3(),
  10156. // light arrays cache
  10157. _direction = new THREE.Vector3(),
  10158. _lightsNeedUpdate = true,
  10159. _lights = {
  10160. ambient: [ 0, 0, 0 ],
  10161. directional: { length: 0, colors: new Array(), positions: new Array() },
  10162. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  10163. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  10164. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  10165. };
  10166. // initialize
  10167. var _gl;
  10168. var _glExtensionTextureFloat;
  10169. var _glExtensionStandardDerivatives;
  10170. var _glExtensionTextureFilterAnisotropic;
  10171. var _glExtensionCompressedTextureS3TC;
  10172. initGL();
  10173. setDefaultGLState();
  10174. this.context = _gl;
  10175. // GPU capabilities
  10176. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  10177. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  10178. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  10179. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  10180. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  10181. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  10182. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  10183. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  10184. //
  10185. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  10186. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  10187. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  10188. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  10189. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  10190. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  10191. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  10192. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  10193. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  10194. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  10195. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  10196. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  10197. // clamp precision to maximum available
  10198. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  10199. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  10200. if ( _precision === "highp" && ! highpAvailable ) {
  10201. if ( mediumpAvailable ) {
  10202. _precision = "mediump";
  10203. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  10204. } else {
  10205. _precision = "lowp";
  10206. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  10207. }
  10208. }
  10209. if ( _precision === "mediump" && ! mediumpAvailable ) {
  10210. _precision = "lowp";
  10211. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  10212. }
  10213. // API
  10214. this.getContext = function () {
  10215. return _gl;
  10216. };
  10217. this.supportsVertexTextures = function () {
  10218. return _supportsVertexTextures;
  10219. };
  10220. this.supportsFloatTextures = function () {
  10221. return _glExtensionTextureFloat;
  10222. };
  10223. this.supportsStandardDerivatives = function () {
  10224. return _glExtensionStandardDerivatives;
  10225. };
  10226. this.supportsCompressedTextureS3TC = function () {
  10227. return _glExtensionCompressedTextureS3TC;
  10228. };
  10229. this.getMaxAnisotropy = function () {
  10230. return _maxAnisotropy;
  10231. };
  10232. this.getPrecision = function () {
  10233. return _precision;
  10234. };
  10235. this.setSize = function ( width, height ) {
  10236. _canvas.width = width * this.devicePixelRatio;
  10237. _canvas.height = height * this.devicePixelRatio;
  10238. _canvas.style.width = width + 'px';
  10239. _canvas.style.height = height + 'px';
  10240. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  10241. };
  10242. this.setViewport = function ( x, y, width, height ) {
  10243. _viewportX = x !== undefined ? x : 0;
  10244. _viewportY = y !== undefined ? y : 0;
  10245. _viewportWidth = width !== undefined ? width : _canvas.width;
  10246. _viewportHeight = height !== undefined ? height : _canvas.height;
  10247. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  10248. };
  10249. this.setScissor = function ( x, y, width, height ) {
  10250. _gl.scissor( x, y, width, height );
  10251. };
  10252. this.enableScissorTest = function ( enable ) {
  10253. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  10254. };
  10255. // Clearing
  10256. this.setClearColorHex = function ( hex, alpha ) {
  10257. _clearColor.setHex( hex );
  10258. _clearAlpha = alpha;
  10259. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  10260. };
  10261. this.setClearColor = function ( color, alpha ) {
  10262. _clearColor.copy( color );
  10263. _clearAlpha = alpha;
  10264. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  10265. };
  10266. this.getClearColor = function () {
  10267. return _clearColor;
  10268. };
  10269. this.getClearAlpha = function () {
  10270. return _clearAlpha;
  10271. };
  10272. this.clear = function ( color, depth, stencil ) {
  10273. var bits = 0;
  10274. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  10275. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  10276. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  10277. _gl.clear( bits );
  10278. };
  10279. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  10280. this.setRenderTarget( renderTarget );
  10281. this.clear( color, depth, stencil );
  10282. };
  10283. // Plugins
  10284. this.addPostPlugin = function ( plugin ) {
  10285. plugin.init( this );
  10286. this.renderPluginsPost.push( plugin );
  10287. };
  10288. this.addPrePlugin = function ( plugin ) {
  10289. plugin.init( this );
  10290. this.renderPluginsPre.push( plugin );
  10291. };
  10292. // Rendering
  10293. this.updateShadowMap = function ( scene, camera ) {
  10294. _currentProgram = null;
  10295. _oldBlending = -1;
  10296. _oldDepthTest = -1;
  10297. _oldDepthWrite = -1;
  10298. _currentGeometryGroupHash = -1;
  10299. _currentMaterialId = -1;
  10300. _lightsNeedUpdate = true;
  10301. _oldDoubleSided = -1;
  10302. _oldFlipSided = -1;
  10303. this.shadowMapPlugin.update( scene, camera );
  10304. };
  10305. // Internal functions
  10306. // Buffer allocation
  10307. function createParticleBuffers ( geometry ) {
  10308. geometry.__webglVertexBuffer = _gl.createBuffer();
  10309. geometry.__webglColorBuffer = _gl.createBuffer();
  10310. _this.info.memory.geometries ++;
  10311. };
  10312. function createLineBuffers ( geometry ) {
  10313. geometry.__webglVertexBuffer = _gl.createBuffer();
  10314. geometry.__webglColorBuffer = _gl.createBuffer();
  10315. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  10316. _this.info.memory.geometries ++;
  10317. };
  10318. function createRibbonBuffers ( geometry ) {
  10319. geometry.__webglVertexBuffer = _gl.createBuffer();
  10320. geometry.__webglColorBuffer = _gl.createBuffer();
  10321. geometry.__webglNormalBuffer = _gl.createBuffer();
  10322. _this.info.memory.geometries ++;
  10323. };
  10324. function createMeshBuffers ( geometryGroup ) {
  10325. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  10326. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  10327. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  10328. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  10329. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  10330. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  10331. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  10332. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  10333. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  10334. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  10335. var m, ml;
  10336. if ( geometryGroup.numMorphTargets ) {
  10337. geometryGroup.__webglMorphTargetsBuffers = [];
  10338. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10339. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  10340. }
  10341. }
  10342. if ( geometryGroup.numMorphNormals ) {
  10343. geometryGroup.__webglMorphNormalsBuffers = [];
  10344. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10345. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  10346. }
  10347. }
  10348. _this.info.memory.geometries ++;
  10349. };
  10350. // Events
  10351. var onGeometryDispose = function ( event ) {
  10352. var geometry = event.target;
  10353. geometry.removeEventListener( 'dispose', onGeometryDispose );
  10354. deallocateGeometry( geometry );
  10355. _this.info.memory.geometries --;
  10356. };
  10357. var onTextureDispose = function ( event ) {
  10358. var texture = event.target;
  10359. texture.removeEventListener( 'dispose', onTextureDispose );
  10360. deallocateTexture( texture );
  10361. _this.info.memory.textures --;
  10362. };
  10363. var onRenderTargetDispose = function ( event ) {
  10364. var renderTarget = event.target;
  10365. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  10366. deallocateRenderTarget( renderTarget );
  10367. _this.info.memory.textures --;
  10368. };
  10369. var onMaterialDispose = function ( event ) {
  10370. var material = event.target;
  10371. material.removeEventListener( 'dispose', onMaterialDispose );
  10372. deallocateMaterial( material );
  10373. };
  10374. // Buffer deallocation
  10375. var deallocateGeometry = function ( geometry ) {
  10376. geometry.__webglInit = undefined;
  10377. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10378. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  10379. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  10380. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  10381. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  10382. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  10383. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  10384. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  10385. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  10386. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  10387. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  10388. // geometry groups
  10389. if ( geometry.geometryGroups !== undefined ) {
  10390. for ( var g in geometry.geometryGroups ) {
  10391. var geometryGroup = geometry.geometryGroups[ g ];
  10392. if ( geometryGroup.numMorphTargets !== undefined ) {
  10393. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10394. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  10395. }
  10396. }
  10397. if ( geometryGroup.numMorphNormals !== undefined ) {
  10398. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10399. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  10400. }
  10401. }
  10402. deleteCustomAttributesBuffers( geometryGroup );
  10403. }
  10404. }
  10405. deleteCustomAttributesBuffers( geometry );
  10406. };
  10407. var deallocateTexture = function ( texture ) {
  10408. if ( texture.image && texture.image.__webglTextureCube ) {
  10409. // cube texture
  10410. _gl.deleteTexture( texture.image.__webglTextureCube );
  10411. } else {
  10412. // 2D texture
  10413. if ( ! texture.__webglInit ) return;
  10414. texture.__webglInit = false;
  10415. _gl.deleteTexture( texture.__webglTexture );
  10416. }
  10417. };
  10418. var deallocateRenderTarget = function ( renderTarget ) {
  10419. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  10420. _gl.deleteTexture( renderTarget.__webglTexture );
  10421. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  10422. for ( var i = 0; i < 6; i ++ ) {
  10423. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  10424. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  10425. }
  10426. } else {
  10427. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  10428. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  10429. }
  10430. };
  10431. var deallocateMaterial = function ( material ) {
  10432. var program = material.program;
  10433. if ( program === undefined ) return;
  10434. material.program = undefined;
  10435. // only deallocate GL program if this was the last use of shared program
  10436. // assumed there is only single copy of any program in the _programs list
  10437. // (that's how it's constructed)
  10438. var i, il, programInfo;
  10439. var deleteProgram = false;
  10440. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  10441. programInfo = _programs[ i ];
  10442. if ( programInfo.program === program ) {
  10443. programInfo.usedTimes --;
  10444. if ( programInfo.usedTimes === 0 ) {
  10445. deleteProgram = true;
  10446. }
  10447. break;
  10448. }
  10449. }
  10450. if ( deleteProgram === true ) {
  10451. // avoid using array.splice, this is costlier than creating new array from scratch
  10452. var newPrograms = [];
  10453. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  10454. programInfo = _programs[ i ];
  10455. if ( programInfo.program !== program ) {
  10456. newPrograms.push( programInfo );
  10457. }
  10458. }
  10459. _programs = newPrograms;
  10460. _gl.deleteProgram( program );
  10461. _this.info.memory.programs --;
  10462. }
  10463. };
  10464. //
  10465. /*
  10466. function deleteParticleBuffers ( geometry ) {
  10467. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10468. _gl.deleteBuffer( geometry.__webglColorBuffer );
  10469. deleteCustomAttributesBuffers( geometry );
  10470. _this.info.memory.geometries --;
  10471. };
  10472. function deleteLineBuffers ( geometry ) {
  10473. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10474. _gl.deleteBuffer( geometry.__webglColorBuffer );
  10475. _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  10476. deleteCustomAttributesBuffers( geometry );
  10477. _this.info.memory.geometries --;
  10478. };
  10479. function deleteRibbonBuffers ( geometry ) {
  10480. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10481. _gl.deleteBuffer( geometry.__webglColorBuffer );
  10482. _gl.deleteBuffer( geometry.__webglNormalBuffer );
  10483. deleteCustomAttributesBuffers( geometry );
  10484. _this.info.memory.geometries --;
  10485. };
  10486. function deleteMeshBuffers ( geometryGroup ) {
  10487. _gl.deleteBuffer( geometryGroup.__webglVertexBuffer );
  10488. _gl.deleteBuffer( geometryGroup.__webglNormalBuffer );
  10489. _gl.deleteBuffer( geometryGroup.__webglTangentBuffer );
  10490. _gl.deleteBuffer( geometryGroup.__webglColorBuffer );
  10491. _gl.deleteBuffer( geometryGroup.__webglUVBuffer );
  10492. _gl.deleteBuffer( geometryGroup.__webglUV2Buffer );
  10493. _gl.deleteBuffer( geometryGroup.__webglSkinIndicesBuffer );
  10494. _gl.deleteBuffer( geometryGroup.__webglSkinWeightsBuffer );
  10495. _gl.deleteBuffer( geometryGroup.__webglFaceBuffer );
  10496. _gl.deleteBuffer( geometryGroup.__webglLineBuffer );
  10497. var m, ml;
  10498. if ( geometryGroup.numMorphTargets ) {
  10499. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10500. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  10501. }
  10502. }
  10503. if ( geometryGroup.numMorphNormals ) {
  10504. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10505. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  10506. }
  10507. }
  10508. deleteCustomAttributesBuffers( geometryGroup );
  10509. _this.info.memory.geometries --;
  10510. };
  10511. */
  10512. function deleteCustomAttributesBuffers( geometry ) {
  10513. if ( geometry.__webglCustomAttributesList ) {
  10514. for ( var id in geometry.__webglCustomAttributesList ) {
  10515. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  10516. }
  10517. }
  10518. };
  10519. // Buffer initialization
  10520. function initCustomAttributes ( geometry, object ) {
  10521. var nvertices = geometry.vertices.length;
  10522. var material = object.material;
  10523. if ( material.attributes ) {
  10524. if ( geometry.__webglCustomAttributesList === undefined ) {
  10525. geometry.__webglCustomAttributesList = [];
  10526. }
  10527. for ( var a in material.attributes ) {
  10528. var attribute = material.attributes[ a ];
  10529. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  10530. attribute.__webglInitialized = true;
  10531. var size = 1; // "f" and "i"
  10532. if ( attribute.type === "v2" ) size = 2;
  10533. else if ( attribute.type === "v3" ) size = 3;
  10534. else if ( attribute.type === "v4" ) size = 4;
  10535. else if ( attribute.type === "c" ) size = 3;
  10536. attribute.size = size;
  10537. attribute.array = new Float32Array( nvertices * size );
  10538. attribute.buffer = _gl.createBuffer();
  10539. attribute.buffer.belongsToAttribute = a;
  10540. attribute.needsUpdate = true;
  10541. }
  10542. geometry.__webglCustomAttributesList.push( attribute );
  10543. }
  10544. }
  10545. };
  10546. function initParticleBuffers ( geometry, object ) {
  10547. var nvertices = geometry.vertices.length;
  10548. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  10549. geometry.__colorArray = new Float32Array( nvertices * 3 );
  10550. geometry.__sortArray = [];
  10551. geometry.__webglParticleCount = nvertices;
  10552. initCustomAttributes ( geometry, object );
  10553. };
  10554. function initLineBuffers ( geometry, object ) {
  10555. var nvertices = geometry.vertices.length;
  10556. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  10557. geometry.__colorArray = new Float32Array( nvertices * 3 );
  10558. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  10559. geometry.__webglLineCount = nvertices;
  10560. initCustomAttributes ( geometry, object );
  10561. };
  10562. function initRibbonBuffers ( geometry, object ) {
  10563. var nvertices = geometry.vertices.length;
  10564. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  10565. geometry.__colorArray = new Float32Array( nvertices * 3 );
  10566. geometry.__normalArray = new Float32Array( nvertices * 3 );
  10567. geometry.__webglVertexCount = nvertices;
  10568. initCustomAttributes ( geometry, object );
  10569. };
  10570. function initMeshBuffers ( geometryGroup, object ) {
  10571. var geometry = object.geometry,
  10572. faces3 = geometryGroup.faces3,
  10573. faces4 = geometryGroup.faces4,
  10574. nvertices = faces3.length * 3 + faces4.length * 4,
  10575. ntris = faces3.length * 1 + faces4.length * 2,
  10576. nlines = faces3.length * 3 + faces4.length * 4,
  10577. material = getBufferMaterial( object, geometryGroup ),
  10578. uvType = bufferGuessUVType( material ),
  10579. normalType = bufferGuessNormalType( material ),
  10580. vertexColorType = bufferGuessVertexColorType( material );
  10581. //console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  10582. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  10583. if ( normalType ) {
  10584. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  10585. }
  10586. if ( geometry.hasTangents ) {
  10587. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  10588. }
  10589. if ( vertexColorType ) {
  10590. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  10591. }
  10592. if ( uvType ) {
  10593. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  10594. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  10595. }
  10596. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  10597. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  10598. }
  10599. }
  10600. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  10601. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  10602. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  10603. }
  10604. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  10605. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  10606. var m, ml;
  10607. if ( geometryGroup.numMorphTargets ) {
  10608. geometryGroup.__morphTargetsArrays = [];
  10609. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10610. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  10611. }
  10612. }
  10613. if ( geometryGroup.numMorphNormals ) {
  10614. geometryGroup.__morphNormalsArrays = [];
  10615. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10616. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  10617. }
  10618. }
  10619. geometryGroup.__webglFaceCount = ntris * 3;
  10620. geometryGroup.__webglLineCount = nlines * 2;
  10621. // custom attributes
  10622. if ( material.attributes ) {
  10623. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  10624. geometryGroup.__webglCustomAttributesList = [];
  10625. }
  10626. for ( var a in material.attributes ) {
  10627. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  10628. // attribute buffers which are correctly indexed in the setMeshBuffers function
  10629. var originalAttribute = material.attributes[ a ];
  10630. var attribute = {};
  10631. for ( var property in originalAttribute ) {
  10632. attribute[ property ] = originalAttribute[ property ];
  10633. }
  10634. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  10635. attribute.__webglInitialized = true;
  10636. var size = 1; // "f" and "i"
  10637. if( attribute.type === "v2" ) size = 2;
  10638. else if( attribute.type === "v3" ) size = 3;
  10639. else if( attribute.type === "v4" ) size = 4;
  10640. else if( attribute.type === "c" ) size = 3;
  10641. attribute.size = size;
  10642. attribute.array = new Float32Array( nvertices * size );
  10643. attribute.buffer = _gl.createBuffer();
  10644. attribute.buffer.belongsToAttribute = a;
  10645. originalAttribute.needsUpdate = true;
  10646. attribute.__original = originalAttribute;
  10647. }
  10648. geometryGroup.__webglCustomAttributesList.push( attribute );
  10649. }
  10650. }
  10651. geometryGroup.__inittedArrays = true;
  10652. };
  10653. function getBufferMaterial( object, geometryGroup ) {
  10654. return object.material instanceof THREE.MeshFaceMaterial
  10655. ? object.material.materials[ geometryGroup.materialIndex ]
  10656. : object.material;
  10657. };
  10658. function materialNeedsSmoothNormals ( material ) {
  10659. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  10660. };
  10661. function bufferGuessNormalType ( material ) {
  10662. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  10663. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  10664. return false;
  10665. }
  10666. if ( materialNeedsSmoothNormals( material ) ) {
  10667. return THREE.SmoothShading;
  10668. } else {
  10669. return THREE.FlatShading;
  10670. }
  10671. };
  10672. function bufferGuessVertexColorType ( material ) {
  10673. if ( material.vertexColors ) {
  10674. return material.vertexColors;
  10675. }
  10676. return false;
  10677. };
  10678. function bufferGuessUVType ( material ) {
  10679. // material must use some texture to require uvs
  10680. if ( material.map || material.lightMap || material.bumpMap || material.normalMap || material.specularMap || material instanceof THREE.ShaderMaterial ) {
  10681. return true;
  10682. }
  10683. return false;
  10684. };
  10685. //
  10686. function initDirectBuffers( geometry ) {
  10687. var a, attribute, type;
  10688. for ( a in geometry.attributes ) {
  10689. if ( a === "index" ) {
  10690. type = _gl.ELEMENT_ARRAY_BUFFER;
  10691. } else {
  10692. type = _gl.ARRAY_BUFFER;
  10693. }
  10694. attribute = geometry.attributes[ a ];
  10695. attribute.buffer = _gl.createBuffer();
  10696. _gl.bindBuffer( type, attribute.buffer );
  10697. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  10698. }
  10699. };
  10700. // Buffer setting
  10701. function setParticleBuffers ( geometry, hint, object ) {
  10702. var v, c, vertex, offset, index, color,
  10703. vertices = geometry.vertices,
  10704. vl = vertices.length,
  10705. colors = geometry.colors,
  10706. cl = colors.length,
  10707. vertexArray = geometry.__vertexArray,
  10708. colorArray = geometry.__colorArray,
  10709. sortArray = geometry.__sortArray,
  10710. dirtyVertices = geometry.verticesNeedUpdate,
  10711. dirtyElements = geometry.elementsNeedUpdate,
  10712. dirtyColors = geometry.colorsNeedUpdate,
  10713. customAttributes = geometry.__webglCustomAttributesList,
  10714. i, il,
  10715. a, ca, cal, value,
  10716. customAttribute;
  10717. if ( object.sortParticles ) {
  10718. _projScreenMatrixPS.copy( _projScreenMatrix );
  10719. _projScreenMatrixPS.multiply( object.matrixWorld );
  10720. for ( v = 0; v < vl; v ++ ) {
  10721. vertex = vertices[ v ];
  10722. _vector3.copy( vertex );
  10723. _vector3.applyMatrix4( _projScreenMatrixPS );
  10724. sortArray[ v ] = [ _vector3.z, v ];
  10725. }
  10726. sortArray.sort( numericalSort );
  10727. for ( v = 0; v < vl; v ++ ) {
  10728. vertex = vertices[ sortArray[v][1] ];
  10729. offset = v * 3;
  10730. vertexArray[ offset ] = vertex.x;
  10731. vertexArray[ offset + 1 ] = vertex.y;
  10732. vertexArray[ offset + 2 ] = vertex.z;
  10733. }
  10734. for ( c = 0; c < cl; c ++ ) {
  10735. offset = c * 3;
  10736. color = colors[ sortArray[c][1] ];
  10737. colorArray[ offset ] = color.r;
  10738. colorArray[ offset + 1 ] = color.g;
  10739. colorArray[ offset + 2 ] = color.b;
  10740. }
  10741. if ( customAttributes ) {
  10742. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10743. customAttribute = customAttributes[ i ];
  10744. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  10745. offset = 0;
  10746. cal = customAttribute.value.length;
  10747. if ( customAttribute.size === 1 ) {
  10748. for ( ca = 0; ca < cal; ca ++ ) {
  10749. index = sortArray[ ca ][ 1 ];
  10750. customAttribute.array[ ca ] = customAttribute.value[ index ];
  10751. }
  10752. } else if ( customAttribute.size === 2 ) {
  10753. for ( ca = 0; ca < cal; ca ++ ) {
  10754. index = sortArray[ ca ][ 1 ];
  10755. value = customAttribute.value[ index ];
  10756. customAttribute.array[ offset ] = value.x;
  10757. customAttribute.array[ offset + 1 ] = value.y;
  10758. offset += 2;
  10759. }
  10760. } else if ( customAttribute.size === 3 ) {
  10761. if ( customAttribute.type === "c" ) {
  10762. for ( ca = 0; ca < cal; ca ++ ) {
  10763. index = sortArray[ ca ][ 1 ];
  10764. value = customAttribute.value[ index ];
  10765. customAttribute.array[ offset ] = value.r;
  10766. customAttribute.array[ offset + 1 ] = value.g;
  10767. customAttribute.array[ offset + 2 ] = value.b;
  10768. offset += 3;
  10769. }
  10770. } else {
  10771. for ( ca = 0; ca < cal; ca ++ ) {
  10772. index = sortArray[ ca ][ 1 ];
  10773. value = customAttribute.value[ index ];
  10774. customAttribute.array[ offset ] = value.x;
  10775. customAttribute.array[ offset + 1 ] = value.y;
  10776. customAttribute.array[ offset + 2 ] = value.z;
  10777. offset += 3;
  10778. }
  10779. }
  10780. } else if ( customAttribute.size === 4 ) {
  10781. for ( ca = 0; ca < cal; ca ++ ) {
  10782. index = sortArray[ ca ][ 1 ];
  10783. value = customAttribute.value[ index ];
  10784. customAttribute.array[ offset ] = value.x;
  10785. customAttribute.array[ offset + 1 ] = value.y;
  10786. customAttribute.array[ offset + 2 ] = value.z;
  10787. customAttribute.array[ offset + 3 ] = value.w;
  10788. offset += 4;
  10789. }
  10790. }
  10791. }
  10792. }
  10793. } else {
  10794. if ( dirtyVertices ) {
  10795. for ( v = 0; v < vl; v ++ ) {
  10796. vertex = vertices[ v ];
  10797. offset = v * 3;
  10798. vertexArray[ offset ] = vertex.x;
  10799. vertexArray[ offset + 1 ] = vertex.y;
  10800. vertexArray[ offset + 2 ] = vertex.z;
  10801. }
  10802. }
  10803. if ( dirtyColors ) {
  10804. for ( c = 0; c < cl; c ++ ) {
  10805. color = colors[ c ];
  10806. offset = c * 3;
  10807. colorArray[ offset ] = color.r;
  10808. colorArray[ offset + 1 ] = color.g;
  10809. colorArray[ offset + 2 ] = color.b;
  10810. }
  10811. }
  10812. if ( customAttributes ) {
  10813. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10814. customAttribute = customAttributes[ i ];
  10815. if ( customAttribute.needsUpdate &&
  10816. ( customAttribute.boundTo === undefined ||
  10817. customAttribute.boundTo === "vertices") ) {
  10818. cal = customAttribute.value.length;
  10819. offset = 0;
  10820. if ( customAttribute.size === 1 ) {
  10821. for ( ca = 0; ca < cal; ca ++ ) {
  10822. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10823. }
  10824. } else if ( customAttribute.size === 2 ) {
  10825. for ( ca = 0; ca < cal; ca ++ ) {
  10826. value = customAttribute.value[ ca ];
  10827. customAttribute.array[ offset ] = value.x;
  10828. customAttribute.array[ offset + 1 ] = value.y;
  10829. offset += 2;
  10830. }
  10831. } else if ( customAttribute.size === 3 ) {
  10832. if ( customAttribute.type === "c" ) {
  10833. for ( ca = 0; ca < cal; ca ++ ) {
  10834. value = customAttribute.value[ ca ];
  10835. customAttribute.array[ offset ] = value.r;
  10836. customAttribute.array[ offset + 1 ] = value.g;
  10837. customAttribute.array[ offset + 2 ] = value.b;
  10838. offset += 3;
  10839. }
  10840. } else {
  10841. for ( ca = 0; ca < cal; ca ++ ) {
  10842. value = customAttribute.value[ ca ];
  10843. customAttribute.array[ offset ] = value.x;
  10844. customAttribute.array[ offset + 1 ] = value.y;
  10845. customAttribute.array[ offset + 2 ] = value.z;
  10846. offset += 3;
  10847. }
  10848. }
  10849. } else if ( customAttribute.size === 4 ) {
  10850. for ( ca = 0; ca < cal; ca ++ ) {
  10851. value = customAttribute.value[ ca ];
  10852. customAttribute.array[ offset ] = value.x;
  10853. customAttribute.array[ offset + 1 ] = value.y;
  10854. customAttribute.array[ offset + 2 ] = value.z;
  10855. customAttribute.array[ offset + 3 ] = value.w;
  10856. offset += 4;
  10857. }
  10858. }
  10859. }
  10860. }
  10861. }
  10862. }
  10863. if ( dirtyVertices || object.sortParticles ) {
  10864. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10865. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10866. }
  10867. if ( dirtyColors || object.sortParticles ) {
  10868. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10869. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10870. }
  10871. if ( customAttributes ) {
  10872. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10873. customAttribute = customAttributes[ i ];
  10874. if ( customAttribute.needsUpdate || object.sortParticles ) {
  10875. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10876. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10877. }
  10878. }
  10879. }
  10880. };
  10881. function setLineBuffers ( geometry, hint ) {
  10882. var v, c, d, vertex, offset, color,
  10883. vertices = geometry.vertices,
  10884. colors = geometry.colors,
  10885. lineDistances = geometry.lineDistances,
  10886. vl = vertices.length,
  10887. cl = colors.length,
  10888. dl = lineDistances.length,
  10889. vertexArray = geometry.__vertexArray,
  10890. colorArray = geometry.__colorArray,
  10891. lineDistanceArray = geometry.__lineDistanceArray,
  10892. dirtyVertices = geometry.verticesNeedUpdate,
  10893. dirtyColors = geometry.colorsNeedUpdate,
  10894. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  10895. customAttributes = geometry.__webglCustomAttributesList,
  10896. i, il,
  10897. a, ca, cal, value,
  10898. customAttribute;
  10899. if ( dirtyVertices ) {
  10900. for ( v = 0; v < vl; v ++ ) {
  10901. vertex = vertices[ v ];
  10902. offset = v * 3;
  10903. vertexArray[ offset ] = vertex.x;
  10904. vertexArray[ offset + 1 ] = vertex.y;
  10905. vertexArray[ offset + 2 ] = vertex.z;
  10906. }
  10907. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10908. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10909. }
  10910. if ( dirtyColors ) {
  10911. for ( c = 0; c < cl; c ++ ) {
  10912. color = colors[ c ];
  10913. offset = c * 3;
  10914. colorArray[ offset ] = color.r;
  10915. colorArray[ offset + 1 ] = color.g;
  10916. colorArray[ offset + 2 ] = color.b;
  10917. }
  10918. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10919. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10920. }
  10921. if ( dirtyLineDistances ) {
  10922. for ( d = 0; d < dl; d ++ ) {
  10923. lineDistanceArray[ d ] = lineDistances[ d ];
  10924. }
  10925. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  10926. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  10927. }
  10928. if ( customAttributes ) {
  10929. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10930. customAttribute = customAttributes[ i ];
  10931. if ( customAttribute.needsUpdate &&
  10932. ( customAttribute.boundTo === undefined ||
  10933. customAttribute.boundTo === "vertices" ) ) {
  10934. offset = 0;
  10935. cal = customAttribute.value.length;
  10936. if ( customAttribute.size === 1 ) {
  10937. for ( ca = 0; ca < cal; ca ++ ) {
  10938. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10939. }
  10940. } else if ( customAttribute.size === 2 ) {
  10941. for ( ca = 0; ca < cal; ca ++ ) {
  10942. value = customAttribute.value[ ca ];
  10943. customAttribute.array[ offset ] = value.x;
  10944. customAttribute.array[ offset + 1 ] = value.y;
  10945. offset += 2;
  10946. }
  10947. } else if ( customAttribute.size === 3 ) {
  10948. if ( customAttribute.type === "c" ) {
  10949. for ( ca = 0; ca < cal; ca ++ ) {
  10950. value = customAttribute.value[ ca ];
  10951. customAttribute.array[ offset ] = value.r;
  10952. customAttribute.array[ offset + 1 ] = value.g;
  10953. customAttribute.array[ offset + 2 ] = value.b;
  10954. offset += 3;
  10955. }
  10956. } else {
  10957. for ( ca = 0; ca < cal; ca ++ ) {
  10958. value = customAttribute.value[ ca ];
  10959. customAttribute.array[ offset ] = value.x;
  10960. customAttribute.array[ offset + 1 ] = value.y;
  10961. customAttribute.array[ offset + 2 ] = value.z;
  10962. offset += 3;
  10963. }
  10964. }
  10965. } else if ( customAttribute.size === 4 ) {
  10966. for ( ca = 0; ca < cal; ca ++ ) {
  10967. value = customAttribute.value[ ca ];
  10968. customAttribute.array[ offset ] = value.x;
  10969. customAttribute.array[ offset + 1 ] = value.y;
  10970. customAttribute.array[ offset + 2 ] = value.z;
  10971. customAttribute.array[ offset + 3 ] = value.w;
  10972. offset += 4;
  10973. }
  10974. }
  10975. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10976. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10977. }
  10978. }
  10979. }
  10980. };
  10981. function setRibbonBuffers ( geometry, hint ) {
  10982. var v, c, n, vertex, offset, color, normal,
  10983. i, il, ca, cal, customAttribute, value,
  10984. vertices = geometry.vertices,
  10985. colors = geometry.colors,
  10986. normals = geometry.normals,
  10987. vl = vertices.length,
  10988. cl = colors.length,
  10989. nl = normals.length,
  10990. vertexArray = geometry.__vertexArray,
  10991. colorArray = geometry.__colorArray,
  10992. normalArray = geometry.__normalArray,
  10993. dirtyVertices = geometry.verticesNeedUpdate,
  10994. dirtyColors = geometry.colorsNeedUpdate,
  10995. dirtyNormals = geometry.normalsNeedUpdate,
  10996. customAttributes = geometry.__webglCustomAttributesList;
  10997. if ( dirtyVertices ) {
  10998. for ( v = 0; v < vl; v ++ ) {
  10999. vertex = vertices[ v ];
  11000. offset = v * 3;
  11001. vertexArray[ offset ] = vertex.x;
  11002. vertexArray[ offset + 1 ] = vertex.y;
  11003. vertexArray[ offset + 2 ] = vertex.z;
  11004. }
  11005. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  11006. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11007. }
  11008. if ( dirtyColors ) {
  11009. for ( c = 0; c < cl; c ++ ) {
  11010. color = colors[ c ];
  11011. offset = c * 3;
  11012. colorArray[ offset ] = color.r;
  11013. colorArray[ offset + 1 ] = color.g;
  11014. colorArray[ offset + 2 ] = color.b;
  11015. }
  11016. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  11017. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11018. }
  11019. if ( dirtyNormals ) {
  11020. for ( n = 0; n < nl; n ++ ) {
  11021. normal = normals[ n ];
  11022. offset = n * 3;
  11023. normalArray[ offset ] = normal.x;
  11024. normalArray[ offset + 1 ] = normal.y;
  11025. normalArray[ offset + 2 ] = normal.z;
  11026. }
  11027. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglNormalBuffer );
  11028. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  11029. }
  11030. if ( customAttributes ) {
  11031. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11032. customAttribute = customAttributes[ i ];
  11033. if ( customAttribute.needsUpdate &&
  11034. ( customAttribute.boundTo === undefined ||
  11035. customAttribute.boundTo === "vertices" ) ) {
  11036. offset = 0;
  11037. cal = customAttribute.value.length;
  11038. if ( customAttribute.size === 1 ) {
  11039. for ( ca = 0; ca < cal; ca ++ ) {
  11040. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  11041. }
  11042. } else if ( customAttribute.size === 2 ) {
  11043. for ( ca = 0; ca < cal; ca ++ ) {
  11044. value = customAttribute.value[ ca ];
  11045. customAttribute.array[ offset ] = value.x;
  11046. customAttribute.array[ offset + 1 ] = value.y;
  11047. offset += 2;
  11048. }
  11049. } else if ( customAttribute.size === 3 ) {
  11050. if ( customAttribute.type === "c" ) {
  11051. for ( ca = 0; ca < cal; ca ++ ) {
  11052. value = customAttribute.value[ ca ];
  11053. customAttribute.array[ offset ] = value.r;
  11054. customAttribute.array[ offset + 1 ] = value.g;
  11055. customAttribute.array[ offset + 2 ] = value.b;
  11056. offset += 3;
  11057. }
  11058. } else {
  11059. for ( ca = 0; ca < cal; ca ++ ) {
  11060. value = customAttribute.value[ ca ];
  11061. customAttribute.array[ offset ] = value.x;
  11062. customAttribute.array[ offset + 1 ] = value.y;
  11063. customAttribute.array[ offset + 2 ] = value.z;
  11064. offset += 3;
  11065. }
  11066. }
  11067. } else if ( customAttribute.size === 4 ) {
  11068. for ( ca = 0; ca < cal; ca ++ ) {
  11069. value = customAttribute.value[ ca ];
  11070. customAttribute.array[ offset ] = value.x;
  11071. customAttribute.array[ offset + 1 ] = value.y;
  11072. customAttribute.array[ offset + 2 ] = value.z;
  11073. customAttribute.array[ offset + 3 ] = value.w;
  11074. offset += 4;
  11075. }
  11076. }
  11077. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11078. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11079. }
  11080. }
  11081. }
  11082. };
  11083. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  11084. if ( ! geometryGroup.__inittedArrays ) {
  11085. return;
  11086. }
  11087. var normalType = bufferGuessNormalType( material ),
  11088. vertexColorType = bufferGuessVertexColorType( material ),
  11089. uvType = bufferGuessUVType( material ),
  11090. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  11091. var f, fl, fi, face,
  11092. vertexNormals, faceNormal, normal,
  11093. vertexColors, faceColor,
  11094. vertexTangents,
  11095. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  11096. c1, c2, c3, c4,
  11097. sw1, sw2, sw3, sw4,
  11098. si1, si2, si3, si4,
  11099. sa1, sa2, sa3, sa4,
  11100. sb1, sb2, sb3, sb4,
  11101. m, ml, i, il,
  11102. vn, uvi, uv2i,
  11103. vk, vkl, vka,
  11104. nka, chf, faceVertexNormals,
  11105. a,
  11106. vertexIndex = 0,
  11107. offset = 0,
  11108. offset_uv = 0,
  11109. offset_uv2 = 0,
  11110. offset_face = 0,
  11111. offset_normal = 0,
  11112. offset_tangent = 0,
  11113. offset_line = 0,
  11114. offset_color = 0,
  11115. offset_skin = 0,
  11116. offset_morphTarget = 0,
  11117. offset_custom = 0,
  11118. offset_customSrc = 0,
  11119. value,
  11120. vertexArray = geometryGroup.__vertexArray,
  11121. uvArray = geometryGroup.__uvArray,
  11122. uv2Array = geometryGroup.__uv2Array,
  11123. normalArray = geometryGroup.__normalArray,
  11124. tangentArray = geometryGroup.__tangentArray,
  11125. colorArray = geometryGroup.__colorArray,
  11126. skinIndexArray = geometryGroup.__skinIndexArray,
  11127. skinWeightArray = geometryGroup.__skinWeightArray,
  11128. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  11129. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  11130. customAttributes = geometryGroup.__webglCustomAttributesList,
  11131. customAttribute,
  11132. faceArray = geometryGroup.__faceArray,
  11133. lineArray = geometryGroup.__lineArray,
  11134. geometry = object.geometry, // this is shared for all chunks
  11135. dirtyVertices = geometry.verticesNeedUpdate,
  11136. dirtyElements = geometry.elementsNeedUpdate,
  11137. dirtyUvs = geometry.uvsNeedUpdate,
  11138. dirtyNormals = geometry.normalsNeedUpdate,
  11139. dirtyTangents = geometry.tangentsNeedUpdate,
  11140. dirtyColors = geometry.colorsNeedUpdate,
  11141. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  11142. vertices = geometry.vertices,
  11143. chunk_faces3 = geometryGroup.faces3,
  11144. chunk_faces4 = geometryGroup.faces4,
  11145. obj_faces = geometry.faces,
  11146. obj_uvs = geometry.faceVertexUvs[ 0 ],
  11147. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  11148. obj_colors = geometry.colors,
  11149. obj_skinIndices = geometry.skinIndices,
  11150. obj_skinWeights = geometry.skinWeights,
  11151. morphTargets = geometry.morphTargets,
  11152. morphNormals = geometry.morphNormals;
  11153. if ( dirtyVertices ) {
  11154. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11155. face = obj_faces[ chunk_faces3[ f ] ];
  11156. v1 = vertices[ face.a ];
  11157. v2 = vertices[ face.b ];
  11158. v3 = vertices[ face.c ];
  11159. vertexArray[ offset ] = v1.x;
  11160. vertexArray[ offset + 1 ] = v1.y;
  11161. vertexArray[ offset + 2 ] = v1.z;
  11162. vertexArray[ offset + 3 ] = v2.x;
  11163. vertexArray[ offset + 4 ] = v2.y;
  11164. vertexArray[ offset + 5 ] = v2.z;
  11165. vertexArray[ offset + 6 ] = v3.x;
  11166. vertexArray[ offset + 7 ] = v3.y;
  11167. vertexArray[ offset + 8 ] = v3.z;
  11168. offset += 9;
  11169. }
  11170. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11171. face = obj_faces[ chunk_faces4[ f ] ];
  11172. v1 = vertices[ face.a ];
  11173. v2 = vertices[ face.b ];
  11174. v3 = vertices[ face.c ];
  11175. v4 = vertices[ face.d ];
  11176. vertexArray[ offset ] = v1.x;
  11177. vertexArray[ offset + 1 ] = v1.y;
  11178. vertexArray[ offset + 2 ] = v1.z;
  11179. vertexArray[ offset + 3 ] = v2.x;
  11180. vertexArray[ offset + 4 ] = v2.y;
  11181. vertexArray[ offset + 5 ] = v2.z;
  11182. vertexArray[ offset + 6 ] = v3.x;
  11183. vertexArray[ offset + 7 ] = v3.y;
  11184. vertexArray[ offset + 8 ] = v3.z;
  11185. vertexArray[ offset + 9 ] = v4.x;
  11186. vertexArray[ offset + 10 ] = v4.y;
  11187. vertexArray[ offset + 11 ] = v4.z;
  11188. offset += 12;
  11189. }
  11190. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11191. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11192. }
  11193. if ( dirtyMorphTargets ) {
  11194. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  11195. offset_morphTarget = 0;
  11196. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11197. chf = chunk_faces3[ f ];
  11198. face = obj_faces[ chf ];
  11199. // morph positions
  11200. v1 = morphTargets[ vk ].vertices[ face.a ];
  11201. v2 = morphTargets[ vk ].vertices[ face.b ];
  11202. v3 = morphTargets[ vk ].vertices[ face.c ];
  11203. vka = morphTargetsArrays[ vk ];
  11204. vka[ offset_morphTarget ] = v1.x;
  11205. vka[ offset_morphTarget + 1 ] = v1.y;
  11206. vka[ offset_morphTarget + 2 ] = v1.z;
  11207. vka[ offset_morphTarget + 3 ] = v2.x;
  11208. vka[ offset_morphTarget + 4 ] = v2.y;
  11209. vka[ offset_morphTarget + 5 ] = v2.z;
  11210. vka[ offset_morphTarget + 6 ] = v3.x;
  11211. vka[ offset_morphTarget + 7 ] = v3.y;
  11212. vka[ offset_morphTarget + 8 ] = v3.z;
  11213. // morph normals
  11214. if ( material.morphNormals ) {
  11215. if ( needsSmoothNormals ) {
  11216. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  11217. n1 = faceVertexNormals.a;
  11218. n2 = faceVertexNormals.b;
  11219. n3 = faceVertexNormals.c;
  11220. } else {
  11221. n1 = morphNormals[ vk ].faceNormals[ chf ];
  11222. n2 = n1;
  11223. n3 = n1;
  11224. }
  11225. nka = morphNormalsArrays[ vk ];
  11226. nka[ offset_morphTarget ] = n1.x;
  11227. nka[ offset_morphTarget + 1 ] = n1.y;
  11228. nka[ offset_morphTarget + 2 ] = n1.z;
  11229. nka[ offset_morphTarget + 3 ] = n2.x;
  11230. nka[ offset_morphTarget + 4 ] = n2.y;
  11231. nka[ offset_morphTarget + 5 ] = n2.z;
  11232. nka[ offset_morphTarget + 6 ] = n3.x;
  11233. nka[ offset_morphTarget + 7 ] = n3.y;
  11234. nka[ offset_morphTarget + 8 ] = n3.z;
  11235. }
  11236. //
  11237. offset_morphTarget += 9;
  11238. }
  11239. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11240. chf = chunk_faces4[ f ];
  11241. face = obj_faces[ chf ];
  11242. // morph positions
  11243. v1 = morphTargets[ vk ].vertices[ face.a ];
  11244. v2 = morphTargets[ vk ].vertices[ face.b ];
  11245. v3 = morphTargets[ vk ].vertices[ face.c ];
  11246. v4 = morphTargets[ vk ].vertices[ face.d ];
  11247. vka = morphTargetsArrays[ vk ];
  11248. vka[ offset_morphTarget ] = v1.x;
  11249. vka[ offset_morphTarget + 1 ] = v1.y;
  11250. vka[ offset_morphTarget + 2 ] = v1.z;
  11251. vka[ offset_morphTarget + 3 ] = v2.x;
  11252. vka[ offset_morphTarget + 4 ] = v2.y;
  11253. vka[ offset_morphTarget + 5 ] = v2.z;
  11254. vka[ offset_morphTarget + 6 ] = v3.x;
  11255. vka[ offset_morphTarget + 7 ] = v3.y;
  11256. vka[ offset_morphTarget + 8 ] = v3.z;
  11257. vka[ offset_morphTarget + 9 ] = v4.x;
  11258. vka[ offset_morphTarget + 10 ] = v4.y;
  11259. vka[ offset_morphTarget + 11 ] = v4.z;
  11260. // morph normals
  11261. if ( material.morphNormals ) {
  11262. if ( needsSmoothNormals ) {
  11263. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  11264. n1 = faceVertexNormals.a;
  11265. n2 = faceVertexNormals.b;
  11266. n3 = faceVertexNormals.c;
  11267. n4 = faceVertexNormals.d;
  11268. } else {
  11269. n1 = morphNormals[ vk ].faceNormals[ chf ];
  11270. n2 = n1;
  11271. n3 = n1;
  11272. n4 = n1;
  11273. }
  11274. nka = morphNormalsArrays[ vk ];
  11275. nka[ offset_morphTarget ] = n1.x;
  11276. nka[ offset_morphTarget + 1 ] = n1.y;
  11277. nka[ offset_morphTarget + 2 ] = n1.z;
  11278. nka[ offset_morphTarget + 3 ] = n2.x;
  11279. nka[ offset_morphTarget + 4 ] = n2.y;
  11280. nka[ offset_morphTarget + 5 ] = n2.z;
  11281. nka[ offset_morphTarget + 6 ] = n3.x;
  11282. nka[ offset_morphTarget + 7 ] = n3.y;
  11283. nka[ offset_morphTarget + 8 ] = n3.z;
  11284. nka[ offset_morphTarget + 9 ] = n4.x;
  11285. nka[ offset_morphTarget + 10 ] = n4.y;
  11286. nka[ offset_morphTarget + 11 ] = n4.z;
  11287. }
  11288. //
  11289. offset_morphTarget += 12;
  11290. }
  11291. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  11292. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  11293. if ( material.morphNormals ) {
  11294. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  11295. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  11296. }
  11297. }
  11298. }
  11299. if ( obj_skinWeights.length ) {
  11300. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11301. face = obj_faces[ chunk_faces3[ f ] ];
  11302. // weights
  11303. sw1 = obj_skinWeights[ face.a ];
  11304. sw2 = obj_skinWeights[ face.b ];
  11305. sw3 = obj_skinWeights[ face.c ];
  11306. skinWeightArray[ offset_skin ] = sw1.x;
  11307. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  11308. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  11309. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  11310. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  11311. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  11312. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  11313. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  11314. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  11315. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  11316. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  11317. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  11318. // indices
  11319. si1 = obj_skinIndices[ face.a ];
  11320. si2 = obj_skinIndices[ face.b ];
  11321. si3 = obj_skinIndices[ face.c ];
  11322. skinIndexArray[ offset_skin ] = si1.x;
  11323. skinIndexArray[ offset_skin + 1 ] = si1.y;
  11324. skinIndexArray[ offset_skin + 2 ] = si1.z;
  11325. skinIndexArray[ offset_skin + 3 ] = si1.w;
  11326. skinIndexArray[ offset_skin + 4 ] = si2.x;
  11327. skinIndexArray[ offset_skin + 5 ] = si2.y;
  11328. skinIndexArray[ offset_skin + 6 ] = si2.z;
  11329. skinIndexArray[ offset_skin + 7 ] = si2.w;
  11330. skinIndexArray[ offset_skin + 8 ] = si3.x;
  11331. skinIndexArray[ offset_skin + 9 ] = si3.y;
  11332. skinIndexArray[ offset_skin + 10 ] = si3.z;
  11333. skinIndexArray[ offset_skin + 11 ] = si3.w;
  11334. offset_skin += 12;
  11335. }
  11336. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11337. face = obj_faces[ chunk_faces4[ f ] ];
  11338. // weights
  11339. sw1 = obj_skinWeights[ face.a ];
  11340. sw2 = obj_skinWeights[ face.b ];
  11341. sw3 = obj_skinWeights[ face.c ];
  11342. sw4 = obj_skinWeights[ face.d ];
  11343. skinWeightArray[ offset_skin ] = sw1.x;
  11344. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  11345. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  11346. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  11347. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  11348. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  11349. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  11350. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  11351. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  11352. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  11353. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  11354. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  11355. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  11356. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  11357. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  11358. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  11359. // indices
  11360. si1 = obj_skinIndices[ face.a ];
  11361. si2 = obj_skinIndices[ face.b ];
  11362. si3 = obj_skinIndices[ face.c ];
  11363. si4 = obj_skinIndices[ face.d ];
  11364. skinIndexArray[ offset_skin ] = si1.x;
  11365. skinIndexArray[ offset_skin + 1 ] = si1.y;
  11366. skinIndexArray[ offset_skin + 2 ] = si1.z;
  11367. skinIndexArray[ offset_skin + 3 ] = si1.w;
  11368. skinIndexArray[ offset_skin + 4 ] = si2.x;
  11369. skinIndexArray[ offset_skin + 5 ] = si2.y;
  11370. skinIndexArray[ offset_skin + 6 ] = si2.z;
  11371. skinIndexArray[ offset_skin + 7 ] = si2.w;
  11372. skinIndexArray[ offset_skin + 8 ] = si3.x;
  11373. skinIndexArray[ offset_skin + 9 ] = si3.y;
  11374. skinIndexArray[ offset_skin + 10 ] = si3.z;
  11375. skinIndexArray[ offset_skin + 11 ] = si3.w;
  11376. skinIndexArray[ offset_skin + 12 ] = si4.x;
  11377. skinIndexArray[ offset_skin + 13 ] = si4.y;
  11378. skinIndexArray[ offset_skin + 14 ] = si4.z;
  11379. skinIndexArray[ offset_skin + 15 ] = si4.w;
  11380. offset_skin += 16;
  11381. }
  11382. if ( offset_skin > 0 ) {
  11383. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  11384. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  11385. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  11386. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  11387. }
  11388. }
  11389. if ( dirtyColors && vertexColorType ) {
  11390. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11391. face = obj_faces[ chunk_faces3[ f ] ];
  11392. vertexColors = face.vertexColors;
  11393. faceColor = face.color;
  11394. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  11395. c1 = vertexColors[ 0 ];
  11396. c2 = vertexColors[ 1 ];
  11397. c3 = vertexColors[ 2 ];
  11398. } else {
  11399. c1 = faceColor;
  11400. c2 = faceColor;
  11401. c3 = faceColor;
  11402. }
  11403. colorArray[ offset_color ] = c1.r;
  11404. colorArray[ offset_color + 1 ] = c1.g;
  11405. colorArray[ offset_color + 2 ] = c1.b;
  11406. colorArray[ offset_color + 3 ] = c2.r;
  11407. colorArray[ offset_color + 4 ] = c2.g;
  11408. colorArray[ offset_color + 5 ] = c2.b;
  11409. colorArray[ offset_color + 6 ] = c3.r;
  11410. colorArray[ offset_color + 7 ] = c3.g;
  11411. colorArray[ offset_color + 8 ] = c3.b;
  11412. offset_color += 9;
  11413. }
  11414. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11415. face = obj_faces[ chunk_faces4[ f ] ];
  11416. vertexColors = face.vertexColors;
  11417. faceColor = face.color;
  11418. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  11419. c1 = vertexColors[ 0 ];
  11420. c2 = vertexColors[ 1 ];
  11421. c3 = vertexColors[ 2 ];
  11422. c4 = vertexColors[ 3 ];
  11423. } else {
  11424. c1 = faceColor;
  11425. c2 = faceColor;
  11426. c3 = faceColor;
  11427. c4 = faceColor;
  11428. }
  11429. colorArray[ offset_color ] = c1.r;
  11430. colorArray[ offset_color + 1 ] = c1.g;
  11431. colorArray[ offset_color + 2 ] = c1.b;
  11432. colorArray[ offset_color + 3 ] = c2.r;
  11433. colorArray[ offset_color + 4 ] = c2.g;
  11434. colorArray[ offset_color + 5 ] = c2.b;
  11435. colorArray[ offset_color + 6 ] = c3.r;
  11436. colorArray[ offset_color + 7 ] = c3.g;
  11437. colorArray[ offset_color + 8 ] = c3.b;
  11438. colorArray[ offset_color + 9 ] = c4.r;
  11439. colorArray[ offset_color + 10 ] = c4.g;
  11440. colorArray[ offset_color + 11 ] = c4.b;
  11441. offset_color += 12;
  11442. }
  11443. if ( offset_color > 0 ) {
  11444. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  11445. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11446. }
  11447. }
  11448. if ( dirtyTangents && geometry.hasTangents ) {
  11449. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11450. face = obj_faces[ chunk_faces3[ f ] ];
  11451. vertexTangents = face.vertexTangents;
  11452. t1 = vertexTangents[ 0 ];
  11453. t2 = vertexTangents[ 1 ];
  11454. t3 = vertexTangents[ 2 ];
  11455. tangentArray[ offset_tangent ] = t1.x;
  11456. tangentArray[ offset_tangent + 1 ] = t1.y;
  11457. tangentArray[ offset_tangent + 2 ] = t1.z;
  11458. tangentArray[ offset_tangent + 3 ] = t1.w;
  11459. tangentArray[ offset_tangent + 4 ] = t2.x;
  11460. tangentArray[ offset_tangent + 5 ] = t2.y;
  11461. tangentArray[ offset_tangent + 6 ] = t2.z;
  11462. tangentArray[ offset_tangent + 7 ] = t2.w;
  11463. tangentArray[ offset_tangent + 8 ] = t3.x;
  11464. tangentArray[ offset_tangent + 9 ] = t3.y;
  11465. tangentArray[ offset_tangent + 10 ] = t3.z;
  11466. tangentArray[ offset_tangent + 11 ] = t3.w;
  11467. offset_tangent += 12;
  11468. }
  11469. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11470. face = obj_faces[ chunk_faces4[ f ] ];
  11471. vertexTangents = face.vertexTangents;
  11472. t1 = vertexTangents[ 0 ];
  11473. t2 = vertexTangents[ 1 ];
  11474. t3 = vertexTangents[ 2 ];
  11475. t4 = vertexTangents[ 3 ];
  11476. tangentArray[ offset_tangent ] = t1.x;
  11477. tangentArray[ offset_tangent + 1 ] = t1.y;
  11478. tangentArray[ offset_tangent + 2 ] = t1.z;
  11479. tangentArray[ offset_tangent + 3 ] = t1.w;
  11480. tangentArray[ offset_tangent + 4 ] = t2.x;
  11481. tangentArray[ offset_tangent + 5 ] = t2.y;
  11482. tangentArray[ offset_tangent + 6 ] = t2.z;
  11483. tangentArray[ offset_tangent + 7 ] = t2.w;
  11484. tangentArray[ offset_tangent + 8 ] = t3.x;
  11485. tangentArray[ offset_tangent + 9 ] = t3.y;
  11486. tangentArray[ offset_tangent + 10 ] = t3.z;
  11487. tangentArray[ offset_tangent + 11 ] = t3.w;
  11488. tangentArray[ offset_tangent + 12 ] = t4.x;
  11489. tangentArray[ offset_tangent + 13 ] = t4.y;
  11490. tangentArray[ offset_tangent + 14 ] = t4.z;
  11491. tangentArray[ offset_tangent + 15 ] = t4.w;
  11492. offset_tangent += 16;
  11493. }
  11494. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  11495. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  11496. }
  11497. if ( dirtyNormals && normalType ) {
  11498. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11499. face = obj_faces[ chunk_faces3[ f ] ];
  11500. vertexNormals = face.vertexNormals;
  11501. faceNormal = face.normal;
  11502. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  11503. for ( i = 0; i < 3; i ++ ) {
  11504. vn = vertexNormals[ i ];
  11505. normalArray[ offset_normal ] = vn.x;
  11506. normalArray[ offset_normal + 1 ] = vn.y;
  11507. normalArray[ offset_normal + 2 ] = vn.z;
  11508. offset_normal += 3;
  11509. }
  11510. } else {
  11511. for ( i = 0; i < 3; i ++ ) {
  11512. normalArray[ offset_normal ] = faceNormal.x;
  11513. normalArray[ offset_normal + 1 ] = faceNormal.y;
  11514. normalArray[ offset_normal + 2 ] = faceNormal.z;
  11515. offset_normal += 3;
  11516. }
  11517. }
  11518. }
  11519. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11520. face = obj_faces[ chunk_faces4[ f ] ];
  11521. vertexNormals = face.vertexNormals;
  11522. faceNormal = face.normal;
  11523. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  11524. for ( i = 0; i < 4; i ++ ) {
  11525. vn = vertexNormals[ i ];
  11526. normalArray[ offset_normal ] = vn.x;
  11527. normalArray[ offset_normal + 1 ] = vn.y;
  11528. normalArray[ offset_normal + 2 ] = vn.z;
  11529. offset_normal += 3;
  11530. }
  11531. } else {
  11532. for ( i = 0; i < 4; i ++ ) {
  11533. normalArray[ offset_normal ] = faceNormal.x;
  11534. normalArray[ offset_normal + 1 ] = faceNormal.y;
  11535. normalArray[ offset_normal + 2 ] = faceNormal.z;
  11536. offset_normal += 3;
  11537. }
  11538. }
  11539. }
  11540. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  11541. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  11542. }
  11543. if ( dirtyUvs && obj_uvs && uvType ) {
  11544. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11545. fi = chunk_faces3[ f ];
  11546. uv = obj_uvs[ fi ];
  11547. if ( uv === undefined ) continue;
  11548. for ( i = 0; i < 3; i ++ ) {
  11549. uvi = uv[ i ];
  11550. uvArray[ offset_uv ] = uvi.x;
  11551. uvArray[ offset_uv + 1 ] = uvi.y;
  11552. offset_uv += 2;
  11553. }
  11554. }
  11555. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11556. fi = chunk_faces4[ f ];
  11557. uv = obj_uvs[ fi ];
  11558. if ( uv === undefined ) continue;
  11559. for ( i = 0; i < 4; i ++ ) {
  11560. uvi = uv[ i ];
  11561. uvArray[ offset_uv ] = uvi.x;
  11562. uvArray[ offset_uv + 1 ] = uvi.y;
  11563. offset_uv += 2;
  11564. }
  11565. }
  11566. if ( offset_uv > 0 ) {
  11567. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  11568. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  11569. }
  11570. }
  11571. if ( dirtyUvs && obj_uvs2 && uvType ) {
  11572. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11573. fi = chunk_faces3[ f ];
  11574. uv2 = obj_uvs2[ fi ];
  11575. if ( uv2 === undefined ) continue;
  11576. for ( i = 0; i < 3; i ++ ) {
  11577. uv2i = uv2[ i ];
  11578. uv2Array[ offset_uv2 ] = uv2i.x;
  11579. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  11580. offset_uv2 += 2;
  11581. }
  11582. }
  11583. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11584. fi = chunk_faces4[ f ];
  11585. uv2 = obj_uvs2[ fi ];
  11586. if ( uv2 === undefined ) continue;
  11587. for ( i = 0; i < 4; i ++ ) {
  11588. uv2i = uv2[ i ];
  11589. uv2Array[ offset_uv2 ] = uv2i.x;
  11590. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  11591. offset_uv2 += 2;
  11592. }
  11593. }
  11594. if ( offset_uv2 > 0 ) {
  11595. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  11596. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  11597. }
  11598. }
  11599. if ( dirtyElements ) {
  11600. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11601. faceArray[ offset_face ] = vertexIndex;
  11602. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  11603. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  11604. offset_face += 3;
  11605. lineArray[ offset_line ] = vertexIndex;
  11606. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  11607. lineArray[ offset_line + 2 ] = vertexIndex;
  11608. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  11609. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  11610. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  11611. offset_line += 6;
  11612. vertexIndex += 3;
  11613. }
  11614. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11615. faceArray[ offset_face ] = vertexIndex;
  11616. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  11617. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  11618. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  11619. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  11620. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  11621. offset_face += 6;
  11622. lineArray[ offset_line ] = vertexIndex;
  11623. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  11624. lineArray[ offset_line + 2 ] = vertexIndex;
  11625. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  11626. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  11627. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  11628. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  11629. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  11630. offset_line += 8;
  11631. vertexIndex += 4;
  11632. }
  11633. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  11634. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  11635. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  11636. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  11637. }
  11638. if ( customAttributes ) {
  11639. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11640. customAttribute = customAttributes[ i ];
  11641. if ( ! customAttribute.__original.needsUpdate ) continue;
  11642. offset_custom = 0;
  11643. offset_customSrc = 0;
  11644. if ( customAttribute.size === 1 ) {
  11645. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11646. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11647. face = obj_faces[ chunk_faces3[ f ] ];
  11648. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  11649. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  11650. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  11651. offset_custom += 3;
  11652. }
  11653. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11654. face = obj_faces[ chunk_faces4[ f ] ];
  11655. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  11656. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  11657. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  11658. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  11659. offset_custom += 4;
  11660. }
  11661. } else if ( customAttribute.boundTo === "faces" ) {
  11662. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11663. value = customAttribute.value[ chunk_faces3[ f ] ];
  11664. customAttribute.array[ offset_custom ] = value;
  11665. customAttribute.array[ offset_custom + 1 ] = value;
  11666. customAttribute.array[ offset_custom + 2 ] = value;
  11667. offset_custom += 3;
  11668. }
  11669. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11670. value = customAttribute.value[ chunk_faces4[ f ] ];
  11671. customAttribute.array[ offset_custom ] = value;
  11672. customAttribute.array[ offset_custom + 1 ] = value;
  11673. customAttribute.array[ offset_custom + 2 ] = value;
  11674. customAttribute.array[ offset_custom + 3 ] = value;
  11675. offset_custom += 4;
  11676. }
  11677. }
  11678. } else if ( customAttribute.size === 2 ) {
  11679. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11680. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11681. face = obj_faces[ chunk_faces3[ f ] ];
  11682. v1 = customAttribute.value[ face.a ];
  11683. v2 = customAttribute.value[ face.b ];
  11684. v3 = customAttribute.value[ face.c ];
  11685. customAttribute.array[ offset_custom ] = v1.x;
  11686. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11687. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11688. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11689. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11690. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11691. offset_custom += 6;
  11692. }
  11693. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11694. face = obj_faces[ chunk_faces4[ f ] ];
  11695. v1 = customAttribute.value[ face.a ];
  11696. v2 = customAttribute.value[ face.b ];
  11697. v3 = customAttribute.value[ face.c ];
  11698. v4 = customAttribute.value[ face.d ];
  11699. customAttribute.array[ offset_custom ] = v1.x;
  11700. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11701. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11702. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11703. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11704. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11705. customAttribute.array[ offset_custom + 6 ] = v4.x;
  11706. customAttribute.array[ offset_custom + 7 ] = v4.y;
  11707. offset_custom += 8;
  11708. }
  11709. } else if ( customAttribute.boundTo === "faces" ) {
  11710. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11711. value = customAttribute.value[ chunk_faces3[ f ] ];
  11712. v1 = value;
  11713. v2 = value;
  11714. v3 = value;
  11715. customAttribute.array[ offset_custom ] = v1.x;
  11716. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11717. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11718. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11719. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11720. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11721. offset_custom += 6;
  11722. }
  11723. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11724. value = customAttribute.value[ chunk_faces4[ f ] ];
  11725. v1 = value;
  11726. v2 = value;
  11727. v3 = value;
  11728. v4 = value;
  11729. customAttribute.array[ offset_custom ] = v1.x;
  11730. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11731. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11732. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11733. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11734. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11735. customAttribute.array[ offset_custom + 6 ] = v4.x;
  11736. customAttribute.array[ offset_custom + 7 ] = v4.y;
  11737. offset_custom += 8;
  11738. }
  11739. }
  11740. } else if ( customAttribute.size === 3 ) {
  11741. var pp;
  11742. if ( customAttribute.type === "c" ) {
  11743. pp = [ "r", "g", "b" ];
  11744. } else {
  11745. pp = [ "x", "y", "z" ];
  11746. }
  11747. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11748. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11749. face = obj_faces[ chunk_faces3[ f ] ];
  11750. v1 = customAttribute.value[ face.a ];
  11751. v2 = customAttribute.value[ face.b ];
  11752. v3 = customAttribute.value[ face.c ];
  11753. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11754. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11755. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11756. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11757. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11758. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11759. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11760. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11761. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11762. offset_custom += 9;
  11763. }
  11764. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11765. face = obj_faces[ chunk_faces4[ f ] ];
  11766. v1 = customAttribute.value[ face.a ];
  11767. v2 = customAttribute.value[ face.b ];
  11768. v3 = customAttribute.value[ face.c ];
  11769. v4 = customAttribute.value[ face.d ];
  11770. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11771. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11772. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11773. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11774. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11775. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11776. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11777. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11778. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11779. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11780. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11781. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11782. offset_custom += 12;
  11783. }
  11784. } else if ( customAttribute.boundTo === "faces" ) {
  11785. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11786. value = customAttribute.value[ chunk_faces3[ f ] ];
  11787. v1 = value;
  11788. v2 = value;
  11789. v3 = value;
  11790. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11791. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11792. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11793. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11794. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11795. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11796. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11797. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11798. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11799. offset_custom += 9;
  11800. }
  11801. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11802. value = customAttribute.value[ chunk_faces4[ f ] ];
  11803. v1 = value;
  11804. v2 = value;
  11805. v3 = value;
  11806. v4 = value;
  11807. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11808. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11809. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11810. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11811. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11812. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11813. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11814. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11815. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11816. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11817. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11818. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11819. offset_custom += 12;
  11820. }
  11821. } else if ( customAttribute.boundTo === "faceVertices" ) {
  11822. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11823. value = customAttribute.value[ chunk_faces3[ f ] ];
  11824. v1 = value[ 0 ];
  11825. v2 = value[ 1 ];
  11826. v3 = value[ 2 ];
  11827. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11828. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11829. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11830. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11831. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11832. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11833. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11834. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11835. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11836. offset_custom += 9;
  11837. }
  11838. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11839. value = customAttribute.value[ chunk_faces4[ f ] ];
  11840. v1 = value[ 0 ];
  11841. v2 = value[ 1 ];
  11842. v3 = value[ 2 ];
  11843. v4 = value[ 3 ];
  11844. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11845. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11846. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11847. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11848. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11849. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11850. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11851. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11852. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11853. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11854. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11855. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11856. offset_custom += 12;
  11857. }
  11858. }
  11859. } else if ( customAttribute.size === 4 ) {
  11860. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11861. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11862. face = obj_faces[ chunk_faces3[ f ] ];
  11863. v1 = customAttribute.value[ face.a ];
  11864. v2 = customAttribute.value[ face.b ];
  11865. v3 = customAttribute.value[ face.c ];
  11866. customAttribute.array[ offset_custom ] = v1.x;
  11867. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11868. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11869. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11870. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11871. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11872. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11873. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11874. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11875. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11876. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11877. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11878. offset_custom += 12;
  11879. }
  11880. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11881. face = obj_faces[ chunk_faces4[ f ] ];
  11882. v1 = customAttribute.value[ face.a ];
  11883. v2 = customAttribute.value[ face.b ];
  11884. v3 = customAttribute.value[ face.c ];
  11885. v4 = customAttribute.value[ face.d ];
  11886. customAttribute.array[ offset_custom ] = v1.x;
  11887. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11888. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11889. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11890. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11891. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11892. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11893. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11894. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11895. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11896. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11897. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11898. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11899. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11900. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11901. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11902. offset_custom += 16;
  11903. }
  11904. } else if ( customAttribute.boundTo === "faces" ) {
  11905. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11906. value = customAttribute.value[ chunk_faces3[ f ] ];
  11907. v1 = value;
  11908. v2 = value;
  11909. v3 = value;
  11910. customAttribute.array[ offset_custom ] = v1.x;
  11911. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11912. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11913. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11914. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11915. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11916. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11917. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11918. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11919. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11920. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11921. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11922. offset_custom += 12;
  11923. }
  11924. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11925. value = customAttribute.value[ chunk_faces4[ f ] ];
  11926. v1 = value;
  11927. v2 = value;
  11928. v3 = value;
  11929. v4 = value;
  11930. customAttribute.array[ offset_custom ] = v1.x;
  11931. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11932. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11933. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11934. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11935. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11936. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11937. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11938. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11939. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11940. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11941. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11942. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11943. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11944. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11945. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11946. offset_custom += 16;
  11947. }
  11948. } else if ( customAttribute.boundTo === "faceVertices" ) {
  11949. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11950. value = customAttribute.value[ chunk_faces3[ f ] ];
  11951. v1 = value[ 0 ];
  11952. v2 = value[ 1 ];
  11953. v3 = value[ 2 ];
  11954. customAttribute.array[ offset_custom ] = v1.x;
  11955. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11956. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11957. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11958. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11959. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11960. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11961. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11962. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11963. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11964. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11965. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11966. offset_custom += 12;
  11967. }
  11968. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11969. value = customAttribute.value[ chunk_faces4[ f ] ];
  11970. v1 = value[ 0 ];
  11971. v2 = value[ 1 ];
  11972. v3 = value[ 2 ];
  11973. v4 = value[ 3 ];
  11974. customAttribute.array[ offset_custom ] = v1.x;
  11975. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11976. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11977. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11978. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11979. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11980. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11981. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11982. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11983. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11984. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11985. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11986. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11987. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11988. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11989. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11990. offset_custom += 16;
  11991. }
  11992. }
  11993. }
  11994. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11995. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11996. }
  11997. }
  11998. if ( dispose ) {
  11999. delete geometryGroup.__inittedArrays;
  12000. delete geometryGroup.__colorArray;
  12001. delete geometryGroup.__normalArray;
  12002. delete geometryGroup.__tangentArray;
  12003. delete geometryGroup.__uvArray;
  12004. delete geometryGroup.__uv2Array;
  12005. delete geometryGroup.__faceArray;
  12006. delete geometryGroup.__vertexArray;
  12007. delete geometryGroup.__lineArray;
  12008. delete geometryGroup.__skinIndexArray;
  12009. delete geometryGroup.__skinWeightArray;
  12010. }
  12011. };
  12012. function setDirectBuffers ( geometry, hint, dispose ) {
  12013. var attributes = geometry.attributes;
  12014. var index = attributes[ "index" ];
  12015. var position = attributes[ "position" ];
  12016. var normal = attributes[ "normal" ];
  12017. var uv = attributes[ "uv" ];
  12018. var color = attributes[ "color" ];
  12019. var tangent = attributes[ "tangent" ];
  12020. if ( geometry.elementsNeedUpdate && index !== undefined ) {
  12021. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12022. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, index.array, hint );
  12023. }
  12024. if ( geometry.verticesNeedUpdate && position !== undefined ) {
  12025. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12026. _gl.bufferData( _gl.ARRAY_BUFFER, position.array, hint );
  12027. }
  12028. if ( geometry.normalsNeedUpdate && normal !== undefined ) {
  12029. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  12030. _gl.bufferData( _gl.ARRAY_BUFFER, normal.array, hint );
  12031. }
  12032. if ( geometry.uvsNeedUpdate && uv !== undefined ) {
  12033. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  12034. _gl.bufferData( _gl.ARRAY_BUFFER, uv.array, hint );
  12035. }
  12036. if ( geometry.colorsNeedUpdate && color !== undefined ) {
  12037. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12038. _gl.bufferData( _gl.ARRAY_BUFFER, color.array, hint );
  12039. }
  12040. if ( geometry.tangentsNeedUpdate && tangent !== undefined ) {
  12041. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  12042. _gl.bufferData( _gl.ARRAY_BUFFER, tangent.array, hint );
  12043. }
  12044. if ( dispose ) {
  12045. for ( var i in geometry.attributes ) {
  12046. delete geometry.attributes[ i ].array;
  12047. }
  12048. }
  12049. };
  12050. // Buffer rendering
  12051. this.renderBufferImmediate = function ( object, program, material ) {
  12052. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  12053. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  12054. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  12055. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  12056. if ( object.hasPositions ) {
  12057. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  12058. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  12059. _gl.enableVertexAttribArray( program.attributes.position );
  12060. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12061. }
  12062. if ( object.hasNormals ) {
  12063. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  12064. if ( material.shading === THREE.FlatShading ) {
  12065. var nx, ny, nz,
  12066. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  12067. normalArray,
  12068. i, il = object.count * 3;
  12069. for( i = 0; i < il; i += 9 ) {
  12070. normalArray = object.normalArray;
  12071. nax = normalArray[ i ];
  12072. nay = normalArray[ i + 1 ];
  12073. naz = normalArray[ i + 2 ];
  12074. nbx = normalArray[ i + 3 ];
  12075. nby = normalArray[ i + 4 ];
  12076. nbz = normalArray[ i + 5 ];
  12077. ncx = normalArray[ i + 6 ];
  12078. ncy = normalArray[ i + 7 ];
  12079. ncz = normalArray[ i + 8 ];
  12080. nx = ( nax + nbx + ncx ) / 3;
  12081. ny = ( nay + nby + ncy ) / 3;
  12082. nz = ( naz + nbz + ncz ) / 3;
  12083. normalArray[ i ] = nx;
  12084. normalArray[ i + 1 ] = ny;
  12085. normalArray[ i + 2 ] = nz;
  12086. normalArray[ i + 3 ] = nx;
  12087. normalArray[ i + 4 ] = ny;
  12088. normalArray[ i + 5 ] = nz;
  12089. normalArray[ i + 6 ] = nx;
  12090. normalArray[ i + 7 ] = ny;
  12091. normalArray[ i + 8 ] = nz;
  12092. }
  12093. }
  12094. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  12095. _gl.enableVertexAttribArray( program.attributes.normal );
  12096. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12097. }
  12098. if ( object.hasUvs && material.map ) {
  12099. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  12100. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  12101. _gl.enableVertexAttribArray( program.attributes.uv );
  12102. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12103. }
  12104. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  12105. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  12106. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  12107. _gl.enableVertexAttribArray( program.attributes.color );
  12108. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12109. }
  12110. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  12111. object.count = 0;
  12112. };
  12113. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  12114. if ( material.visible === false ) return;
  12115. var program, attributes, linewidth, primitives, a, attribute;
  12116. program = setProgram( camera, lights, fog, material, object );
  12117. attributes = program.attributes;
  12118. var updateBuffers = false,
  12119. wireframeBit = material.wireframe ? 1 : 0,
  12120. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  12121. if ( geometryHash !== _currentGeometryGroupHash ) {
  12122. _currentGeometryGroupHash = geometryHash;
  12123. updateBuffers = true;
  12124. }
  12125. if ( updateBuffers ) {
  12126. disableAttributes();
  12127. }
  12128. // render mesh
  12129. if ( object instanceof THREE.Mesh ) {
  12130. var index = geometry.attributes[ "index" ];
  12131. // indexed triangles
  12132. if ( index ) {
  12133. var offsets = geometry.offsets;
  12134. // if there is more than 1 chunk
  12135. // must set attribute pointers to use new offsets for each chunk
  12136. // even if geometry and materials didn't change
  12137. if ( offsets.length > 1 ) updateBuffers = true;
  12138. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  12139. var startIndex = offsets[ i ].index;
  12140. if ( updateBuffers ) {
  12141. // vertices
  12142. var position = geometry.attributes[ "position" ];
  12143. var positionSize = position.itemSize;
  12144. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12145. enableAttribute( attributes.position );
  12146. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, startIndex * positionSize * 4 ); // 4 bytes per Float32
  12147. // normals
  12148. var normal = geometry.attributes[ "normal" ];
  12149. if ( attributes.normal >= 0 && normal ) {
  12150. var normalSize = normal.itemSize;
  12151. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  12152. enableAttribute( attributes.normal );
  12153. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, startIndex * normalSize * 4 );
  12154. }
  12155. // uvs
  12156. var uv = geometry.attributes[ "uv" ];
  12157. if ( attributes.uv >= 0 && uv ) {
  12158. var uvSize = uv.itemSize;
  12159. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  12160. enableAttribute( attributes.uv );
  12161. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, startIndex * uvSize * 4 );
  12162. }
  12163. // colors
  12164. var color = geometry.attributes[ "color" ];
  12165. if ( attributes.color >= 0 && color ) {
  12166. var colorSize = color.itemSize;
  12167. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12168. enableAttribute( attributes.color );
  12169. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, startIndex * colorSize * 4 );
  12170. }
  12171. // tangents
  12172. var tangent = geometry.attributes[ "tangent" ];
  12173. if ( attributes.tangent >= 0 && tangent ) {
  12174. var tangentSize = tangent.itemSize;
  12175. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  12176. enableAttribute( attributes.tangent );
  12177. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, startIndex * tangentSize * 4 );
  12178. }
  12179. // indices
  12180. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12181. }
  12182. // render indexed triangles
  12183. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  12184. _this.info.render.calls ++;
  12185. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  12186. _this.info.render.faces += offsets[ i ].count / 3;
  12187. }
  12188. // non-indexed triangles
  12189. } else {
  12190. if ( updateBuffers ) {
  12191. // vertices
  12192. var position = geometry.attributes[ "position" ];
  12193. var positionSize = position.itemSize;
  12194. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12195. enableAttribute( attributes.position );
  12196. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  12197. // normals
  12198. var normal = geometry.attributes[ "normal" ];
  12199. if ( attributes.normal >= 0 && normal ) {
  12200. var normalSize = normal.itemSize;
  12201. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  12202. enableAttribute( attributes.normal );
  12203. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, 0 );
  12204. }
  12205. // uvs
  12206. var uv = geometry.attributes[ "uv" ];
  12207. if ( attributes.uv >= 0 && uv ) {
  12208. var uvSize = uv.itemSize;
  12209. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  12210. enableAttribute( attributes.uv );
  12211. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, 0 );
  12212. }
  12213. // colors
  12214. var color = geometry.attributes[ "color" ];
  12215. if ( attributes.color >= 0 && color ) {
  12216. var colorSize = color.itemSize;
  12217. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12218. enableAttribute( attributes.color );
  12219. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  12220. }
  12221. // tangents
  12222. var tangent = geometry.attributes[ "tangent" ];
  12223. if ( attributes.tangent >= 0 && tangent ) {
  12224. var tangentSize = tangent.itemSize;
  12225. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  12226. enableAttribute( attributes.tangent );
  12227. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, 0 );
  12228. }
  12229. }
  12230. // render non-indexed triangles
  12231. _gl.drawArrays( _gl.TRIANGLES, 0, position.numItems / 3 );
  12232. _this.info.render.calls ++;
  12233. _this.info.render.vertices += position.numItems / 3;
  12234. _this.info.render.faces += position.numItems / 3 / 3;
  12235. }
  12236. // render particles
  12237. } else if ( object instanceof THREE.ParticleSystem ) {
  12238. if ( updateBuffers ) {
  12239. // vertices
  12240. var position = geometry.attributes[ "position" ];
  12241. var positionSize = position.itemSize;
  12242. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12243. enableAttribute( attributes.position );
  12244. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  12245. // colors
  12246. var color = geometry.attributes[ "color" ];
  12247. if ( attributes.color >= 0 && color ) {
  12248. var colorSize = color.itemSize;
  12249. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12250. enableAttribute( attributes.color );
  12251. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  12252. }
  12253. // render particles
  12254. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  12255. _this.info.render.calls ++;
  12256. _this.info.render.points += position.numItems / 3;
  12257. }
  12258. } else if ( object instanceof THREE.Line ) {
  12259. if ( updateBuffers ) {
  12260. // vertices
  12261. var position = geometry.attributes[ "position" ];
  12262. var positionSize = position.itemSize;
  12263. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12264. enableAttribute( attributes.position );
  12265. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  12266. // colors
  12267. var color = geometry.attributes[ "color" ];
  12268. if ( attributes.color >= 0 && color ) {
  12269. var colorSize = color.itemSize;
  12270. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12271. enableAttribute( attributes.color );
  12272. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  12273. }
  12274. // render lines
  12275. _gl.drawArrays( _gl.LINE_STRIP, 0, position.numItems / 3 );
  12276. _this.info.render.calls ++;
  12277. _this.info.render.points += position.numItems;
  12278. }
  12279. }
  12280. };
  12281. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  12282. if ( material.visible === false ) return;
  12283. var program, attributes, linewidth, primitives, a, attribute, i, il;
  12284. program = setProgram( camera, lights, fog, material, object );
  12285. attributes = program.attributes;
  12286. var updateBuffers = false,
  12287. wireframeBit = material.wireframe ? 1 : 0,
  12288. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  12289. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  12290. _currentGeometryGroupHash = geometryGroupHash;
  12291. updateBuffers = true;
  12292. }
  12293. if ( updateBuffers ) {
  12294. disableAttributes();
  12295. }
  12296. // vertices
  12297. if ( !material.morphTargets && attributes.position >= 0 ) {
  12298. if ( updateBuffers ) {
  12299. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12300. enableAttribute( attributes.position );
  12301. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12302. }
  12303. } else {
  12304. if ( object.morphTargetBase ) {
  12305. setupMorphTargets( material, geometryGroup, object );
  12306. }
  12307. }
  12308. if ( updateBuffers ) {
  12309. // custom attributes
  12310. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  12311. if ( geometryGroup.__webglCustomAttributesList ) {
  12312. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  12313. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  12314. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  12315. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  12316. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  12317. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  12318. }
  12319. }
  12320. }
  12321. // colors
  12322. if ( attributes.color >= 0 ) {
  12323. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12324. enableAttribute( attributes.color );
  12325. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12326. }
  12327. // normals
  12328. if ( attributes.normal >= 0 ) {
  12329. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12330. enableAttribute( attributes.normal );
  12331. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12332. }
  12333. // tangents
  12334. if ( attributes.tangent >= 0 ) {
  12335. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12336. enableAttribute( attributes.tangent );
  12337. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  12338. }
  12339. // uvs
  12340. if ( attributes.uv >= 0 ) {
  12341. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12342. enableAttribute( attributes.uv );
  12343. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12344. }
  12345. if ( attributes.uv2 >= 0 ) {
  12346. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12347. enableAttribute( attributes.uv2 );
  12348. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  12349. }
  12350. if ( material.skinning &&
  12351. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  12352. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  12353. enableAttribute( attributes.skinIndex );
  12354. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  12355. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  12356. enableAttribute( attributes.skinWeight );
  12357. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  12358. }
  12359. // line distances
  12360. if ( attributes.lineDistance >= 0 ) {
  12361. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  12362. enableAttribute( attributes.lineDistance );
  12363. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  12364. }
  12365. }
  12366. // render mesh
  12367. if ( object instanceof THREE.Mesh ) {
  12368. // wireframe
  12369. if ( material.wireframe ) {
  12370. setLineWidth( material.wireframeLinewidth );
  12371. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  12372. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  12373. // triangles
  12374. } else {
  12375. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12376. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  12377. }
  12378. _this.info.render.calls ++;
  12379. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  12380. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  12381. // render lines
  12382. } else if ( object instanceof THREE.Line ) {
  12383. primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  12384. setLineWidth( material.linewidth );
  12385. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  12386. _this.info.render.calls ++;
  12387. // render particles
  12388. } else if ( object instanceof THREE.ParticleSystem ) {
  12389. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  12390. _this.info.render.calls ++;
  12391. _this.info.render.points += geometryGroup.__webglParticleCount;
  12392. // render ribbon
  12393. } else if ( object instanceof THREE.Ribbon ) {
  12394. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  12395. _this.info.render.calls ++;
  12396. }
  12397. };
  12398. function enableAttribute( attribute ) {
  12399. if ( ! _enabledAttributes[ attribute ] ) {
  12400. _gl.enableVertexAttribArray( attribute );
  12401. _enabledAttributes[ attribute ] = true;
  12402. }
  12403. };
  12404. function disableAttributes() {
  12405. for ( var attribute in _enabledAttributes ) {
  12406. if ( _enabledAttributes[ attribute ] ) {
  12407. _gl.disableVertexAttribArray( attribute );
  12408. _enabledAttributes[ attribute ] = false;
  12409. }
  12410. }
  12411. };
  12412. function setupMorphTargets ( material, geometryGroup, object ) {
  12413. // set base
  12414. var attributes = material.program.attributes;
  12415. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  12416. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  12417. enableAttribute( attributes.position );
  12418. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12419. } else if ( attributes.position >= 0 ) {
  12420. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12421. enableAttribute( attributes.position );
  12422. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12423. }
  12424. if ( object.morphTargetForcedOrder.length ) {
  12425. // set forced order
  12426. var m = 0;
  12427. var order = object.morphTargetForcedOrder;
  12428. var influences = object.morphTargetInfluences;
  12429. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  12430. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  12431. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  12432. enableAttribute( attributes[ "morphTarget" + m ] );
  12433. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12434. }
  12435. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  12436. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  12437. enableAttribute( attributes[ "morphNormal" + m ] );
  12438. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12439. }
  12440. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  12441. m ++;
  12442. }
  12443. } else {
  12444. // find the most influencing
  12445. var influence, activeInfluenceIndices = [];
  12446. var influences = object.morphTargetInfluences;
  12447. var i, il = influences.length;
  12448. for ( i = 0; i < il; i ++ ) {
  12449. influence = influences[ i ];
  12450. if ( influence > 0 ) {
  12451. activeInfluenceIndices.push( [ influence, i ] );
  12452. }
  12453. }
  12454. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  12455. activeInfluenceIndices.sort( numericalSort );
  12456. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  12457. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  12458. activeInfluenceIndices.sort( numericalSort );
  12459. } else if ( activeInfluenceIndices.length === 0 ) {
  12460. activeInfluenceIndices.push( [ 0, 0 ] );
  12461. };
  12462. var influenceIndex, m = 0;
  12463. while ( m < material.numSupportedMorphTargets ) {
  12464. if ( activeInfluenceIndices[ m ] ) {
  12465. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  12466. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  12467. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  12468. enableAttribute( attributes[ "morphTarget" + m ] );
  12469. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12470. }
  12471. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  12472. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  12473. enableAttribute( attributes[ "morphNormal" + m ] );
  12474. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12475. }
  12476. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  12477. } else {
  12478. /*
  12479. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12480. if ( material.morphNormals ) {
  12481. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12482. }
  12483. */
  12484. object.__webglMorphTargetInfluences[ m ] = 0;
  12485. }
  12486. m ++;
  12487. }
  12488. }
  12489. // load updated influences uniform
  12490. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  12491. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  12492. }
  12493. };
  12494. // Sorting
  12495. function painterSortStable ( a, b ) {
  12496. if ( a.z !== b.z ) {
  12497. return b.z - a.z;
  12498. } else {
  12499. return b.id - a.id;
  12500. }
  12501. };
  12502. function numericalSort ( a, b ) {
  12503. return b[ 0 ] - a[ 0 ];
  12504. };
  12505. // Rendering
  12506. this.render = function ( scene, camera, renderTarget, forceClear ) {
  12507. if ( camera instanceof THREE.Camera === false ) {
  12508. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  12509. return;
  12510. }
  12511. var i, il,
  12512. webglObject, object,
  12513. renderList,
  12514. lights = scene.__lights,
  12515. fog = scene.fog;
  12516. // reset caching for this frame
  12517. _currentMaterialId = -1;
  12518. _lightsNeedUpdate = true;
  12519. // update scene graph
  12520. if ( this.autoUpdateScene ) scene.updateMatrixWorld();
  12521. // update camera matrices and frustum
  12522. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  12523. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  12524. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  12525. _frustum.setFromMatrix( _projScreenMatrix );
  12526. // update WebGL objects
  12527. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  12528. // custom render plugins (pre pass)
  12529. renderPlugins( this.renderPluginsPre, scene, camera );
  12530. //
  12531. _this.info.render.calls = 0;
  12532. _this.info.render.vertices = 0;
  12533. _this.info.render.faces = 0;
  12534. _this.info.render.points = 0;
  12535. this.setRenderTarget( renderTarget );
  12536. if ( this.autoClear || forceClear ) {
  12537. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  12538. }
  12539. // set matrices for regular objects (frustum culled)
  12540. renderList = scene.__webglObjects;
  12541. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  12542. webglObject = renderList[ i ];
  12543. object = webglObject.object;
  12544. webglObject.render = false;
  12545. if ( object.visible ) {
  12546. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  12547. setupMatrices( object, camera );
  12548. unrollBufferMaterial( webglObject );
  12549. webglObject.render = true;
  12550. if ( this.sortObjects === true ) {
  12551. if ( object.renderDepth !== null ) {
  12552. webglObject.z = object.renderDepth;
  12553. } else {
  12554. _vector3.copy( object.matrixWorld.getPosition() );
  12555. _vector3.applyMatrix4( _projScreenMatrix );
  12556. webglObject.z = _vector3.z;
  12557. }
  12558. webglObject.id = object.id;
  12559. }
  12560. }
  12561. }
  12562. }
  12563. if ( this.sortObjects ) {
  12564. renderList.sort( painterSortStable );
  12565. }
  12566. // set matrices for immediate objects
  12567. renderList = scene.__webglObjectsImmediate;
  12568. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  12569. webglObject = renderList[ i ];
  12570. object = webglObject.object;
  12571. if ( object.visible ) {
  12572. setupMatrices( object, camera );
  12573. unrollImmediateBufferMaterial( webglObject );
  12574. }
  12575. }
  12576. if ( scene.overrideMaterial ) {
  12577. var material = scene.overrideMaterial;
  12578. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  12579. this.setDepthTest( material.depthTest );
  12580. this.setDepthWrite( material.depthWrite );
  12581. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12582. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  12583. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  12584. } else {
  12585. var material = null;
  12586. // opaque pass (front-to-back order)
  12587. this.setBlending( THREE.NoBlending );
  12588. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  12589. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  12590. // transparent pass (back-to-front order)
  12591. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  12592. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  12593. }
  12594. // custom render plugins (post pass)
  12595. renderPlugins( this.renderPluginsPost, scene, camera );
  12596. // Generate mipmap if we're using any kind of mipmap filtering
  12597. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  12598. updateRenderTargetMipmap( renderTarget );
  12599. }
  12600. // Ensure depth buffer writing is enabled so it can be cleared on next render
  12601. this.setDepthTest( true );
  12602. this.setDepthWrite( true );
  12603. // _gl.finish();
  12604. };
  12605. function renderPlugins( plugins, scene, camera ) {
  12606. if ( ! plugins.length ) return;
  12607. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  12608. // reset state for plugin (to start from clean slate)
  12609. _currentProgram = null;
  12610. _currentCamera = null;
  12611. _oldBlending = -1;
  12612. _oldDepthTest = -1;
  12613. _oldDepthWrite = -1;
  12614. _oldDoubleSided = -1;
  12615. _oldFlipSided = -1;
  12616. _currentGeometryGroupHash = -1;
  12617. _currentMaterialId = -1;
  12618. _lightsNeedUpdate = true;
  12619. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  12620. // reset state after plugin (anything could have changed)
  12621. _currentProgram = null;
  12622. _currentCamera = null;
  12623. _oldBlending = -1;
  12624. _oldDepthTest = -1;
  12625. _oldDepthWrite = -1;
  12626. _oldDoubleSided = -1;
  12627. _oldFlipSided = -1;
  12628. _currentGeometryGroupHash = -1;
  12629. _currentMaterialId = -1;
  12630. _lightsNeedUpdate = true;
  12631. }
  12632. };
  12633. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  12634. var webglObject, object, buffer, material, start, end, delta;
  12635. if ( reverse ) {
  12636. start = renderList.length - 1;
  12637. end = -1;
  12638. delta = -1;
  12639. } else {
  12640. start = 0;
  12641. end = renderList.length;
  12642. delta = 1;
  12643. }
  12644. for ( var i = start; i !== end; i += delta ) {
  12645. webglObject = renderList[ i ];
  12646. if ( webglObject.render ) {
  12647. object = webglObject.object;
  12648. buffer = webglObject.buffer;
  12649. if ( overrideMaterial ) {
  12650. material = overrideMaterial;
  12651. } else {
  12652. material = webglObject[ materialType ];
  12653. if ( ! material ) continue;
  12654. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  12655. _this.setDepthTest( material.depthTest );
  12656. _this.setDepthWrite( material.depthWrite );
  12657. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12658. }
  12659. _this.setMaterialFaces( material );
  12660. if ( buffer instanceof THREE.BufferGeometry ) {
  12661. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  12662. } else {
  12663. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  12664. }
  12665. }
  12666. }
  12667. };
  12668. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  12669. var webglObject, object, material, program;
  12670. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  12671. webglObject = renderList[ i ];
  12672. object = webglObject.object;
  12673. if ( object.visible ) {
  12674. if ( overrideMaterial ) {
  12675. material = overrideMaterial;
  12676. } else {
  12677. material = webglObject[ materialType ];
  12678. if ( ! material ) continue;
  12679. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  12680. _this.setDepthTest( material.depthTest );
  12681. _this.setDepthWrite( material.depthWrite );
  12682. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12683. }
  12684. _this.renderImmediateObject( camera, lights, fog, material, object );
  12685. }
  12686. }
  12687. };
  12688. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  12689. var program = setProgram( camera, lights, fog, material, object );
  12690. _currentGeometryGroupHash = -1;
  12691. _this.setMaterialFaces( material );
  12692. if ( object.immediateRenderCallback ) {
  12693. object.immediateRenderCallback( program, _gl, _frustum );
  12694. } else {
  12695. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  12696. }
  12697. };
  12698. function unrollImmediateBufferMaterial ( globject ) {
  12699. var object = globject.object,
  12700. material = object.material;
  12701. if ( material.transparent ) {
  12702. globject.transparent = material;
  12703. globject.opaque = null;
  12704. } else {
  12705. globject.opaque = material;
  12706. globject.transparent = null;
  12707. }
  12708. };
  12709. function unrollBufferMaterial ( globject ) {
  12710. var object = globject.object,
  12711. buffer = globject.buffer,
  12712. material, materialIndex, meshMaterial;
  12713. meshMaterial = object.material;
  12714. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  12715. materialIndex = buffer.materialIndex;
  12716. material = meshMaterial.materials[ materialIndex ];
  12717. if ( material.transparent ) {
  12718. globject.transparent = material;
  12719. globject.opaque = null;
  12720. } else {
  12721. globject.opaque = material;
  12722. globject.transparent = null;
  12723. }
  12724. } else {
  12725. material = meshMaterial;
  12726. if ( material ) {
  12727. if ( material.transparent ) {
  12728. globject.transparent = material;
  12729. globject.opaque = null;
  12730. } else {
  12731. globject.opaque = material;
  12732. globject.transparent = null;
  12733. }
  12734. }
  12735. }
  12736. };
  12737. // Geometry splitting
  12738. function sortFacesByMaterial ( geometry, material ) {
  12739. var f, fl, face, materialIndex, vertices,
  12740. groupHash, hash_map = {};
  12741. var numMorphTargets = geometry.morphTargets.length;
  12742. var numMorphNormals = geometry.morphNormals.length;
  12743. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  12744. geometry.geometryGroups = {};
  12745. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  12746. face = geometry.faces[ f ];
  12747. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  12748. if ( hash_map[ materialIndex ] === undefined ) {
  12749. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  12750. }
  12751. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  12752. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  12753. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  12754. }
  12755. vertices = face instanceof THREE.Face3 ? 3 : 4;
  12756. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  12757. hash_map[ materialIndex ].counter += 1;
  12758. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  12759. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  12760. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  12761. }
  12762. }
  12763. if ( face instanceof THREE.Face3 ) {
  12764. geometry.geometryGroups[ groupHash ].faces3.push( f );
  12765. } else {
  12766. geometry.geometryGroups[ groupHash ].faces4.push( f );
  12767. }
  12768. geometry.geometryGroups[ groupHash ].vertices += vertices;
  12769. }
  12770. geometry.geometryGroupsList = [];
  12771. for ( var g in geometry.geometryGroups ) {
  12772. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  12773. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  12774. }
  12775. };
  12776. // Objects refresh
  12777. this.initWebGLObjects = function ( scene ) {
  12778. if ( !scene.__webglObjects ) {
  12779. scene.__webglObjects = [];
  12780. scene.__webglObjectsImmediate = [];
  12781. scene.__webglSprites = [];
  12782. scene.__webglFlares = [];
  12783. }
  12784. while ( scene.__objectsAdded.length ) {
  12785. addObject( scene.__objectsAdded[ 0 ], scene );
  12786. scene.__objectsAdded.splice( 0, 1 );
  12787. }
  12788. while ( scene.__objectsRemoved.length ) {
  12789. removeObject( scene.__objectsRemoved[ 0 ], scene );
  12790. scene.__objectsRemoved.splice( 0, 1 );
  12791. }
  12792. // update must be called after objects adding / removal
  12793. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  12794. updateObject( scene.__webglObjects[ o ].object );
  12795. }
  12796. };
  12797. // Objects adding
  12798. function addObject ( object, scene ) {
  12799. var g, geometry, material, geometryGroup;
  12800. if ( ! object.__webglInit ) {
  12801. object.__webglInit = true;
  12802. object._modelViewMatrix = new THREE.Matrix4();
  12803. object._normalMatrix = new THREE.Matrix3();
  12804. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  12805. object.geometry.__webglInit = true;
  12806. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  12807. }
  12808. if ( object instanceof THREE.Mesh ) {
  12809. geometry = object.geometry;
  12810. material = object.material;
  12811. if ( geometry instanceof THREE.Geometry ) {
  12812. if ( geometry.geometryGroups === undefined ) {
  12813. sortFacesByMaterial( geometry, material );
  12814. }
  12815. // create separate VBOs per geometry chunk
  12816. for ( g in geometry.geometryGroups ) {
  12817. geometryGroup = geometry.geometryGroups[ g ];
  12818. // initialise VBO on the first access
  12819. if ( ! geometryGroup.__webglVertexBuffer ) {
  12820. createMeshBuffers( geometryGroup );
  12821. initMeshBuffers( geometryGroup, object );
  12822. geometry.verticesNeedUpdate = true;
  12823. geometry.morphTargetsNeedUpdate = true;
  12824. geometry.elementsNeedUpdate = true;
  12825. geometry.uvsNeedUpdate = true;
  12826. geometry.normalsNeedUpdate = true;
  12827. geometry.tangentsNeedUpdate = true;
  12828. geometry.colorsNeedUpdate = true;
  12829. }
  12830. }
  12831. } else if ( geometry instanceof THREE.BufferGeometry ) {
  12832. initDirectBuffers( geometry );
  12833. }
  12834. } else if ( object instanceof THREE.Ribbon ) {
  12835. geometry = object.geometry;
  12836. if ( ! geometry.__webglVertexBuffer ) {
  12837. createRibbonBuffers( geometry );
  12838. initRibbonBuffers( geometry, object );
  12839. geometry.verticesNeedUpdate = true;
  12840. geometry.colorsNeedUpdate = true;
  12841. geometry.normalsNeedUpdate = true;
  12842. }
  12843. } else if ( object instanceof THREE.Line ) {
  12844. geometry = object.geometry;
  12845. if ( ! geometry.__webglVertexBuffer ) {
  12846. if ( geometry instanceof THREE.Geometry ) {
  12847. createLineBuffers( geometry );
  12848. initLineBuffers( geometry, object );
  12849. geometry.verticesNeedUpdate = true;
  12850. geometry.colorsNeedUpdate = true;
  12851. geometry.lineDistancesNeedUpdate = true;
  12852. } else if ( geometry instanceof THREE.BufferGeometry ) {
  12853. initDirectBuffers( geometry );
  12854. }
  12855. }
  12856. } else if ( object instanceof THREE.ParticleSystem ) {
  12857. geometry = object.geometry;
  12858. if ( ! geometry.__webglVertexBuffer ) {
  12859. if ( geometry instanceof THREE.Geometry ) {
  12860. createParticleBuffers( geometry );
  12861. initParticleBuffers( geometry, object );
  12862. geometry.verticesNeedUpdate = true;
  12863. geometry.colorsNeedUpdate = true;
  12864. } else if ( geometry instanceof THREE.BufferGeometry ) {
  12865. initDirectBuffers( geometry );
  12866. }
  12867. }
  12868. }
  12869. }
  12870. if ( ! object.__webglActive ) {
  12871. if ( object instanceof THREE.Mesh ) {
  12872. geometry = object.geometry;
  12873. if ( geometry instanceof THREE.BufferGeometry ) {
  12874. addBuffer( scene.__webglObjects, geometry, object );
  12875. } else if ( geometry instanceof THREE.Geometry ) {
  12876. for ( g in geometry.geometryGroups ) {
  12877. geometryGroup = geometry.geometryGroups[ g ];
  12878. addBuffer( scene.__webglObjects, geometryGroup, object );
  12879. }
  12880. }
  12881. } else if ( object instanceof THREE.Ribbon ||
  12882. object instanceof THREE.Line ||
  12883. object instanceof THREE.ParticleSystem ) {
  12884. geometry = object.geometry;
  12885. addBuffer( scene.__webglObjects, geometry, object );
  12886. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  12887. addBufferImmediate( scene.__webglObjectsImmediate, object );
  12888. } else if ( object instanceof THREE.Sprite ) {
  12889. scene.__webglSprites.push( object );
  12890. } else if ( object instanceof THREE.LensFlare ) {
  12891. scene.__webglFlares.push( object );
  12892. }
  12893. object.__webglActive = true;
  12894. }
  12895. };
  12896. function addBuffer ( objlist, buffer, object ) {
  12897. objlist.push(
  12898. {
  12899. buffer: buffer,
  12900. object: object,
  12901. opaque: null,
  12902. transparent: null
  12903. }
  12904. );
  12905. };
  12906. function addBufferImmediate ( objlist, object ) {
  12907. objlist.push(
  12908. {
  12909. object: object,
  12910. opaque: null,
  12911. transparent: null
  12912. }
  12913. );
  12914. };
  12915. // Objects updates
  12916. function updateObject ( object ) {
  12917. var geometry = object.geometry,
  12918. geometryGroup, customAttributesDirty, material;
  12919. if ( object instanceof THREE.Mesh ) {
  12920. if ( geometry instanceof THREE.BufferGeometry ) {
  12921. if ( geometry.verticesNeedUpdate || geometry.elementsNeedUpdate ||
  12922. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  12923. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate ) {
  12924. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  12925. }
  12926. geometry.verticesNeedUpdate = false;
  12927. geometry.elementsNeedUpdate = false;
  12928. geometry.uvsNeedUpdate = false;
  12929. geometry.normalsNeedUpdate = false;
  12930. geometry.colorsNeedUpdate = false;
  12931. geometry.tangentsNeedUpdate = false;
  12932. } else {
  12933. // check all geometry groups
  12934. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  12935. geometryGroup = geometry.geometryGroupsList[ i ];
  12936. material = getBufferMaterial( object, geometryGroup );
  12937. if ( geometry.buffersNeedUpdate ) {
  12938. initMeshBuffers( geometryGroup, object );
  12939. }
  12940. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12941. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  12942. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  12943. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  12944. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  12945. }
  12946. }
  12947. geometry.verticesNeedUpdate = false;
  12948. geometry.morphTargetsNeedUpdate = false;
  12949. geometry.elementsNeedUpdate = false;
  12950. geometry.uvsNeedUpdate = false;
  12951. geometry.normalsNeedUpdate = false;
  12952. geometry.colorsNeedUpdate = false;
  12953. geometry.tangentsNeedUpdate = false;
  12954. geometry.buffersNeedUpdate = false;
  12955. material.attributes && clearCustomAttributes( material );
  12956. }
  12957. } else if ( object instanceof THREE.Ribbon ) {
  12958. material = getBufferMaterial( object, geometry );
  12959. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12960. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.normalsNeedUpdate || customAttributesDirty ) {
  12961. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  12962. }
  12963. geometry.verticesNeedUpdate = false;
  12964. geometry.colorsNeedUpdate = false;
  12965. geometry.normalsNeedUpdate = false;
  12966. material.attributes && clearCustomAttributes( material );
  12967. } else if ( object instanceof THREE.Line ) {
  12968. if ( geometry instanceof THREE.BufferGeometry ) {
  12969. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  12970. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  12971. }
  12972. geometry.verticesNeedUpdate = false;
  12973. geometry.colorsNeedUpdate = false;
  12974. } else {
  12975. material = getBufferMaterial( object, geometry );
  12976. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12977. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  12978. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  12979. }
  12980. geometry.verticesNeedUpdate = false;
  12981. geometry.colorsNeedUpdate = false;
  12982. geometry.lineDistancesNeedUpdate = false;
  12983. material.attributes && clearCustomAttributes( material );
  12984. }
  12985. } else if ( object instanceof THREE.ParticleSystem ) {
  12986. if ( geometry instanceof THREE.BufferGeometry ) {
  12987. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  12988. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  12989. }
  12990. geometry.verticesNeedUpdate = false;
  12991. geometry.colorsNeedUpdate = false;
  12992. } else {
  12993. material = getBufferMaterial( object, geometry );
  12994. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12995. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  12996. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  12997. }
  12998. geometry.verticesNeedUpdate = false;
  12999. geometry.colorsNeedUpdate = false;
  13000. material.attributes && clearCustomAttributes( material );
  13001. }
  13002. }
  13003. };
  13004. // Objects updates - custom attributes check
  13005. function areCustomAttributesDirty ( material ) {
  13006. for ( var a in material.attributes ) {
  13007. if ( material.attributes[ a ].needsUpdate ) return true;
  13008. }
  13009. return false;
  13010. };
  13011. function clearCustomAttributes ( material ) {
  13012. for ( var a in material.attributes ) {
  13013. material.attributes[ a ].needsUpdate = false;
  13014. }
  13015. };
  13016. // Objects removal
  13017. function removeObject ( object, scene ) {
  13018. if ( object instanceof THREE.Mesh ||
  13019. object instanceof THREE.ParticleSystem ||
  13020. object instanceof THREE.Ribbon ||
  13021. object instanceof THREE.Line ) {
  13022. removeInstances( scene.__webglObjects, object );
  13023. } else if ( object instanceof THREE.Sprite ) {
  13024. removeInstancesDirect( scene.__webglSprites, object );
  13025. } else if ( object instanceof THREE.LensFlare ) {
  13026. removeInstancesDirect( scene.__webglFlares, object );
  13027. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  13028. removeInstances( scene.__webglObjectsImmediate, object );
  13029. }
  13030. object.__webglActive = false;
  13031. };
  13032. function removeInstances ( objlist, object ) {
  13033. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13034. if ( objlist[ o ].object === object ) {
  13035. objlist.splice( o, 1 );
  13036. }
  13037. }
  13038. };
  13039. function removeInstancesDirect ( objlist, object ) {
  13040. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  13041. if ( objlist[ o ] === object ) {
  13042. objlist.splice( o, 1 );
  13043. }
  13044. }
  13045. };
  13046. // Materials
  13047. this.initMaterial = function ( material, lights, fog, object ) {
  13048. material.addEventListener( 'dispose', onMaterialDispose );
  13049. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  13050. if ( material instanceof THREE.MeshDepthMaterial ) {
  13051. shaderID = 'depth';
  13052. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13053. shaderID = 'normal';
  13054. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  13055. shaderID = 'basic';
  13056. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13057. shaderID = 'lambert';
  13058. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13059. shaderID = 'phong';
  13060. } else if ( material instanceof THREE.LineBasicMaterial ) {
  13061. shaderID = 'basic';
  13062. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13063. shaderID = 'dashed';
  13064. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  13065. shaderID = 'particle_basic';
  13066. }
  13067. if ( shaderID ) {
  13068. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  13069. }
  13070. // heuristics to create shader parameters according to lights in the scene
  13071. // (not to blow over maxLights budget)
  13072. maxLightCount = allocateLights( lights );
  13073. maxShadows = allocateShadows( lights );
  13074. maxBones = allocateBones( object );
  13075. parameters = {
  13076. map: !!material.map,
  13077. envMap: !!material.envMap,
  13078. lightMap: !!material.lightMap,
  13079. bumpMap: !!material.bumpMap,
  13080. normalMap: !!material.normalMap,
  13081. specularMap: !!material.specularMap,
  13082. vertexColors: material.vertexColors,
  13083. fog: fog,
  13084. useFog: material.fog,
  13085. fogExp: fog instanceof THREE.FogExp2,
  13086. sizeAttenuation: material.sizeAttenuation,
  13087. skinning: material.skinning,
  13088. maxBones: maxBones,
  13089. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  13090. boneTextureWidth: object && object.boneTextureWidth,
  13091. boneTextureHeight: object && object.boneTextureHeight,
  13092. morphTargets: material.morphTargets,
  13093. morphNormals: material.morphNormals,
  13094. maxMorphTargets: this.maxMorphTargets,
  13095. maxMorphNormals: this.maxMorphNormals,
  13096. maxDirLights: maxLightCount.directional,
  13097. maxPointLights: maxLightCount.point,
  13098. maxSpotLights: maxLightCount.spot,
  13099. maxHemiLights: maxLightCount.hemi,
  13100. maxShadows: maxShadows,
  13101. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  13102. shadowMapType: this.shadowMapType,
  13103. shadowMapDebug: this.shadowMapDebug,
  13104. shadowMapCascade: this.shadowMapCascade,
  13105. alphaTest: material.alphaTest,
  13106. metal: material.metal,
  13107. perPixel: material.perPixel,
  13108. wrapAround: material.wrapAround,
  13109. doubleSided: material.side === THREE.DoubleSide,
  13110. flipSided: material.side === THREE.BackSide
  13111. };
  13112. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters );
  13113. var attributes = material.program.attributes;
  13114. if ( material.morphTargets ) {
  13115. material.numSupportedMorphTargets = 0;
  13116. var id, base = "morphTarget";
  13117. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  13118. id = base + i;
  13119. if ( attributes[ id ] >= 0 ) {
  13120. material.numSupportedMorphTargets ++;
  13121. }
  13122. }
  13123. }
  13124. if ( material.morphNormals ) {
  13125. material.numSupportedMorphNormals = 0;
  13126. var id, base = "morphNormal";
  13127. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  13128. id = base + i;
  13129. if ( attributes[ id ] >= 0 ) {
  13130. material.numSupportedMorphNormals ++;
  13131. }
  13132. }
  13133. }
  13134. material.uniformsList = [];
  13135. for ( u in material.uniforms ) {
  13136. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  13137. }
  13138. };
  13139. function setMaterialShaders( material, shaders ) {
  13140. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  13141. material.vertexShader = shaders.vertexShader;
  13142. material.fragmentShader = shaders.fragmentShader;
  13143. };
  13144. function setProgram( camera, lights, fog, material, object ) {
  13145. _usedTextureUnits = 0;
  13146. if ( material.needsUpdate ) {
  13147. if ( material.program ) deallocateMaterial( material );
  13148. _this.initMaterial( material, lights, fog, object );
  13149. material.needsUpdate = false;
  13150. }
  13151. if ( material.morphTargets ) {
  13152. if ( ! object.__webglMorphTargetInfluences ) {
  13153. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  13154. }
  13155. }
  13156. var refreshMaterial = false;
  13157. var program = material.program,
  13158. p_uniforms = program.uniforms,
  13159. m_uniforms = material.uniforms;
  13160. if ( program !== _currentProgram ) {
  13161. _gl.useProgram( program );
  13162. _currentProgram = program;
  13163. refreshMaterial = true;
  13164. }
  13165. if ( material.id !== _currentMaterialId ) {
  13166. _currentMaterialId = material.id;
  13167. refreshMaterial = true;
  13168. }
  13169. if ( refreshMaterial || camera !== _currentCamera ) {
  13170. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  13171. if ( camera !== _currentCamera ) _currentCamera = camera;
  13172. }
  13173. // skinning uniforms must be set even if material didn't change
  13174. // auto-setting of texture unit for bone texture must go before other textures
  13175. // not sure why, but otherwise weird things happen
  13176. if ( material.skinning ) {
  13177. if ( _supportsBoneTextures && object.useVertexTexture ) {
  13178. if ( p_uniforms.boneTexture !== null ) {
  13179. var textureUnit = getTextureUnit();
  13180. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  13181. _this.setTexture( object.boneTexture, textureUnit );
  13182. }
  13183. } else {
  13184. if ( p_uniforms.boneGlobalMatrices !== null ) {
  13185. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  13186. }
  13187. }
  13188. }
  13189. if ( refreshMaterial ) {
  13190. // refresh uniforms common to several materials
  13191. if ( fog && material.fog ) {
  13192. refreshUniformsFog( m_uniforms, fog );
  13193. }
  13194. if ( material instanceof THREE.MeshPhongMaterial ||
  13195. material instanceof THREE.MeshLambertMaterial ||
  13196. material.lights ) {
  13197. if ( _lightsNeedUpdate ) {
  13198. setupLights( program, lights );
  13199. _lightsNeedUpdate = false;
  13200. }
  13201. refreshUniformsLights( m_uniforms, _lights );
  13202. }
  13203. if ( material instanceof THREE.MeshBasicMaterial ||
  13204. material instanceof THREE.MeshLambertMaterial ||
  13205. material instanceof THREE.MeshPhongMaterial ) {
  13206. refreshUniformsCommon( m_uniforms, material );
  13207. }
  13208. // refresh single material specific uniforms
  13209. if ( material instanceof THREE.LineBasicMaterial ) {
  13210. refreshUniformsLine( m_uniforms, material );
  13211. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13212. refreshUniformsLine( m_uniforms, material );
  13213. refreshUniformsDash( m_uniforms, material );
  13214. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  13215. refreshUniformsParticle( m_uniforms, material );
  13216. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13217. refreshUniformsPhong( m_uniforms, material );
  13218. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13219. refreshUniformsLambert( m_uniforms, material );
  13220. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  13221. m_uniforms.mNear.value = camera.near;
  13222. m_uniforms.mFar.value = camera.far;
  13223. m_uniforms.opacity.value = material.opacity;
  13224. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13225. m_uniforms.opacity.value = material.opacity;
  13226. }
  13227. if ( object.receiveShadow && ! material._shadowPass ) {
  13228. refreshUniformsShadow( m_uniforms, lights );
  13229. }
  13230. // load common uniforms
  13231. loadUniformsGeneric( program, material.uniformsList );
  13232. // load material specific uniforms
  13233. // (shader material also gets them for the sake of genericity)
  13234. if ( material instanceof THREE.ShaderMaterial ||
  13235. material instanceof THREE.MeshPhongMaterial ||
  13236. material.envMap ) {
  13237. if ( p_uniforms.cameraPosition !== null ) {
  13238. var position = camera.matrixWorld.getPosition();
  13239. _gl.uniform3f( p_uniforms.cameraPosition, position.x, position.y, position.z );
  13240. }
  13241. }
  13242. if ( material instanceof THREE.MeshPhongMaterial ||
  13243. material instanceof THREE.MeshLambertMaterial ||
  13244. material instanceof THREE.ShaderMaterial ||
  13245. material.skinning ) {
  13246. if ( p_uniforms.viewMatrix !== null ) {
  13247. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  13248. }
  13249. }
  13250. }
  13251. loadUniformsMatrices( p_uniforms, object );
  13252. if ( p_uniforms.modelMatrix !== null ) {
  13253. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  13254. }
  13255. return program;
  13256. };
  13257. // Uniforms (refresh uniforms objects)
  13258. function refreshUniformsCommon ( uniforms, material ) {
  13259. uniforms.opacity.value = material.opacity;
  13260. if ( _this.gammaInput ) {
  13261. uniforms.diffuse.value.copyGammaToLinear( material.color );
  13262. } else {
  13263. uniforms.diffuse.value = material.color;
  13264. }
  13265. uniforms.map.value = material.map;
  13266. uniforms.lightMap.value = material.lightMap;
  13267. uniforms.specularMap.value = material.specularMap;
  13268. if ( material.bumpMap ) {
  13269. uniforms.bumpMap.value = material.bumpMap;
  13270. uniforms.bumpScale.value = material.bumpScale;
  13271. }
  13272. if ( material.normalMap ) {
  13273. uniforms.normalMap.value = material.normalMap;
  13274. uniforms.normalScale.value.copy( material.normalScale );
  13275. }
  13276. // uv repeat and offset setting priorities
  13277. // 1. color map
  13278. // 2. specular map
  13279. // 3. normal map
  13280. // 4. bump map
  13281. var uvScaleMap;
  13282. if ( material.map ) {
  13283. uvScaleMap = material.map;
  13284. } else if ( material.specularMap ) {
  13285. uvScaleMap = material.specularMap;
  13286. } else if ( material.normalMap ) {
  13287. uvScaleMap = material.normalMap;
  13288. } else if ( material.bumpMap ) {
  13289. uvScaleMap = material.bumpMap;
  13290. }
  13291. if ( uvScaleMap !== undefined ) {
  13292. var offset = uvScaleMap.offset;
  13293. var repeat = uvScaleMap.repeat;
  13294. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  13295. }
  13296. uniforms.envMap.value = material.envMap;
  13297. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  13298. if ( _this.gammaInput ) {
  13299. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  13300. uniforms.reflectivity.value = material.reflectivity;
  13301. } else {
  13302. uniforms.reflectivity.value = material.reflectivity;
  13303. }
  13304. uniforms.refractionRatio.value = material.refractionRatio;
  13305. uniforms.combine.value = material.combine;
  13306. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  13307. };
  13308. function refreshUniformsLine ( uniforms, material ) {
  13309. uniforms.diffuse.value = material.color;
  13310. uniforms.opacity.value = material.opacity;
  13311. };
  13312. function refreshUniformsDash ( uniforms, material ) {
  13313. uniforms.dashSize.value = material.dashSize;
  13314. uniforms.totalSize.value = material.dashSize + material.gapSize;
  13315. uniforms.scale.value = material.scale;
  13316. };
  13317. function refreshUniformsParticle ( uniforms, material ) {
  13318. uniforms.psColor.value = material.color;
  13319. uniforms.opacity.value = material.opacity;
  13320. uniforms.size.value = material.size;
  13321. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  13322. uniforms.map.value = material.map;
  13323. };
  13324. function refreshUniformsFog ( uniforms, fog ) {
  13325. uniforms.fogColor.value = fog.color;
  13326. if ( fog instanceof THREE.Fog ) {
  13327. uniforms.fogNear.value = fog.near;
  13328. uniforms.fogFar.value = fog.far;
  13329. } else if ( fog instanceof THREE.FogExp2 ) {
  13330. uniforms.fogDensity.value = fog.density;
  13331. }
  13332. };
  13333. function refreshUniformsPhong ( uniforms, material ) {
  13334. uniforms.shininess.value = material.shininess;
  13335. if ( _this.gammaInput ) {
  13336. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  13337. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  13338. uniforms.specular.value.copyGammaToLinear( material.specular );
  13339. } else {
  13340. uniforms.ambient.value = material.ambient;
  13341. uniforms.emissive.value = material.emissive;
  13342. uniforms.specular.value = material.specular;
  13343. }
  13344. if ( material.wrapAround ) {
  13345. uniforms.wrapRGB.value.copy( material.wrapRGB );
  13346. }
  13347. };
  13348. function refreshUniformsLambert ( uniforms, material ) {
  13349. if ( _this.gammaInput ) {
  13350. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  13351. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  13352. } else {
  13353. uniforms.ambient.value = material.ambient;
  13354. uniforms.emissive.value = material.emissive;
  13355. }
  13356. if ( material.wrapAround ) {
  13357. uniforms.wrapRGB.value.copy( material.wrapRGB );
  13358. }
  13359. };
  13360. function refreshUniformsLights ( uniforms, lights ) {
  13361. uniforms.ambientLightColor.value = lights.ambient;
  13362. uniforms.directionalLightColor.value = lights.directional.colors;
  13363. uniforms.directionalLightDirection.value = lights.directional.positions;
  13364. uniforms.pointLightColor.value = lights.point.colors;
  13365. uniforms.pointLightPosition.value = lights.point.positions;
  13366. uniforms.pointLightDistance.value = lights.point.distances;
  13367. uniforms.spotLightColor.value = lights.spot.colors;
  13368. uniforms.spotLightPosition.value = lights.spot.positions;
  13369. uniforms.spotLightDistance.value = lights.spot.distances;
  13370. uniforms.spotLightDirection.value = lights.spot.directions;
  13371. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  13372. uniforms.spotLightExponent.value = lights.spot.exponents;
  13373. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  13374. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  13375. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  13376. };
  13377. function refreshUniformsShadow ( uniforms, lights ) {
  13378. if ( uniforms.shadowMatrix ) {
  13379. var j = 0;
  13380. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  13381. var light = lights[ i ];
  13382. if ( ! light.castShadow ) continue;
  13383. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  13384. uniforms.shadowMap.value[ j ] = light.shadowMap;
  13385. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  13386. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  13387. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  13388. uniforms.shadowBias.value[ j ] = light.shadowBias;
  13389. j ++;
  13390. }
  13391. }
  13392. }
  13393. };
  13394. // Uniforms (load to GPU)
  13395. function loadUniformsMatrices ( uniforms, object ) {
  13396. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  13397. if ( uniforms.normalMatrix ) {
  13398. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  13399. }
  13400. };
  13401. function getTextureUnit() {
  13402. var textureUnit = _usedTextureUnits;
  13403. if ( textureUnit >= _maxTextures ) {
  13404. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  13405. }
  13406. _usedTextureUnits += 1;
  13407. return textureUnit;
  13408. };
  13409. function loadUniformsGeneric ( program, uniforms ) {
  13410. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  13411. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  13412. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  13413. if ( !location ) continue;
  13414. uniform = uniforms[ j ][ 0 ];
  13415. type = uniform.type;
  13416. value = uniform.value;
  13417. if ( type === "i" ) { // single integer
  13418. _gl.uniform1i( location, value );
  13419. } else if ( type === "f" ) { // single float
  13420. _gl.uniform1f( location, value );
  13421. } else if ( type === "v2" ) { // single THREE.Vector2
  13422. _gl.uniform2f( location, value.x, value.y );
  13423. } else if ( type === "v3" ) { // single THREE.Vector3
  13424. _gl.uniform3f( location, value.x, value.y, value.z );
  13425. } else if ( type === "v4" ) { // single THREE.Vector4
  13426. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  13427. } else if ( type === "c" ) { // single THREE.Color
  13428. _gl.uniform3f( location, value.r, value.g, value.b );
  13429. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  13430. _gl.uniform1iv( location, value );
  13431. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  13432. _gl.uniform3iv( location, value );
  13433. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  13434. _gl.uniform1fv( location, value );
  13435. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  13436. _gl.uniform3fv( location, value );
  13437. } else if ( type === "v2v" ) { // array of THREE.Vector2
  13438. if ( uniform._array === undefined ) {
  13439. uniform._array = new Float32Array( 2 * value.length );
  13440. }
  13441. for ( i = 0, il = value.length; i < il; i ++ ) {
  13442. offset = i * 2;
  13443. uniform._array[ offset ] = value[ i ].x;
  13444. uniform._array[ offset + 1 ] = value[ i ].y;
  13445. }
  13446. _gl.uniform2fv( location, uniform._array );
  13447. } else if ( type === "v3v" ) { // array of THREE.Vector3
  13448. if ( uniform._array === undefined ) {
  13449. uniform._array = new Float32Array( 3 * value.length );
  13450. }
  13451. for ( i = 0, il = value.length; i < il; i ++ ) {
  13452. offset = i * 3;
  13453. uniform._array[ offset ] = value[ i ].x;
  13454. uniform._array[ offset + 1 ] = value[ i ].y;
  13455. uniform._array[ offset + 2 ] = value[ i ].z;
  13456. }
  13457. _gl.uniform3fv( location, uniform._array );
  13458. } else if ( type === "v4v" ) { // array of THREE.Vector4
  13459. if ( uniform._array === undefined ) {
  13460. uniform._array = new Float32Array( 4 * value.length );
  13461. }
  13462. for ( i = 0, il = value.length; i < il; i ++ ) {
  13463. offset = i * 4;
  13464. uniform._array[ offset ] = value[ i ].x;
  13465. uniform._array[ offset + 1 ] = value[ i ].y;
  13466. uniform._array[ offset + 2 ] = value[ i ].z;
  13467. uniform._array[ offset + 3 ] = value[ i ].w;
  13468. }
  13469. _gl.uniform4fv( location, uniform._array );
  13470. } else if ( type === "m4") { // single THREE.Matrix4
  13471. if ( uniform._array === undefined ) {
  13472. uniform._array = new Float32Array( 16 );
  13473. }
  13474. value.flattenToArray( uniform._array );
  13475. _gl.uniformMatrix4fv( location, false, uniform._array );
  13476. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  13477. if ( uniform._array === undefined ) {
  13478. uniform._array = new Float32Array( 16 * value.length );
  13479. }
  13480. for ( i = 0, il = value.length; i < il; i ++ ) {
  13481. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  13482. }
  13483. _gl.uniformMatrix4fv( location, false, uniform._array );
  13484. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  13485. texture = value;
  13486. textureUnit = getTextureUnit();
  13487. _gl.uniform1i( location, textureUnit );
  13488. if ( !texture ) continue;
  13489. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  13490. setCubeTexture( texture, textureUnit );
  13491. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  13492. setCubeTextureDynamic( texture, textureUnit );
  13493. } else {
  13494. _this.setTexture( texture, textureUnit );
  13495. }
  13496. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  13497. if ( uniform._array === undefined ) {
  13498. uniform._array = [];
  13499. }
  13500. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  13501. uniform._array[ i ] = getTextureUnit();
  13502. }
  13503. _gl.uniform1iv( location, uniform._array );
  13504. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  13505. texture = uniform.value[ i ];
  13506. textureUnit = uniform._array[ i ];
  13507. if ( !texture ) continue;
  13508. _this.setTexture( texture, textureUnit );
  13509. }
  13510. }
  13511. }
  13512. };
  13513. function setupMatrices ( object, camera ) {
  13514. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  13515. object._normalMatrix.getInverse( object._modelViewMatrix );
  13516. object._normalMatrix.transpose();
  13517. };
  13518. //
  13519. function setColorGamma( array, offset, color, intensitySq ) {
  13520. array[ offset ] = color.r * color.r * intensitySq;
  13521. array[ offset + 1 ] = color.g * color.g * intensitySq;
  13522. array[ offset + 2 ] = color.b * color.b * intensitySq;
  13523. };
  13524. function setColorLinear( array, offset, color, intensity ) {
  13525. array[ offset ] = color.r * intensity;
  13526. array[ offset + 1 ] = color.g * intensity;
  13527. array[ offset + 2 ] = color.b * intensity;
  13528. };
  13529. function setupLights ( program, lights ) {
  13530. var l, ll, light, n,
  13531. r = 0, g = 0, b = 0,
  13532. color, skyColor, groundColor,
  13533. intensity, intensitySq,
  13534. position,
  13535. distance,
  13536. zlights = _lights,
  13537. dirColors = zlights.directional.colors,
  13538. dirPositions = zlights.directional.positions,
  13539. pointColors = zlights.point.colors,
  13540. pointPositions = zlights.point.positions,
  13541. pointDistances = zlights.point.distances,
  13542. spotColors = zlights.spot.colors,
  13543. spotPositions = zlights.spot.positions,
  13544. spotDistances = zlights.spot.distances,
  13545. spotDirections = zlights.spot.directions,
  13546. spotAnglesCos = zlights.spot.anglesCos,
  13547. spotExponents = zlights.spot.exponents,
  13548. hemiSkyColors = zlights.hemi.skyColors,
  13549. hemiGroundColors = zlights.hemi.groundColors,
  13550. hemiPositions = zlights.hemi.positions,
  13551. dirLength = 0,
  13552. pointLength = 0,
  13553. spotLength = 0,
  13554. hemiLength = 0,
  13555. dirCount = 0,
  13556. pointCount = 0,
  13557. spotCount = 0,
  13558. hemiCount = 0,
  13559. dirOffset = 0,
  13560. pointOffset = 0,
  13561. spotOffset = 0,
  13562. hemiOffset = 0;
  13563. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  13564. light = lights[ l ];
  13565. if ( light.onlyShadow ) continue;
  13566. color = light.color;
  13567. intensity = light.intensity;
  13568. distance = light.distance;
  13569. if ( light instanceof THREE.AmbientLight ) {
  13570. if ( ! light.visible ) continue;
  13571. if ( _this.gammaInput ) {
  13572. r += color.r * color.r;
  13573. g += color.g * color.g;
  13574. b += color.b * color.b;
  13575. } else {
  13576. r += color.r;
  13577. g += color.g;
  13578. b += color.b;
  13579. }
  13580. } else if ( light instanceof THREE.DirectionalLight ) {
  13581. dirCount += 1;
  13582. if ( ! light.visible ) continue;
  13583. _direction.copy( light.matrixWorld.getPosition() );
  13584. _direction.sub( light.target.matrixWorld.getPosition() );
  13585. _direction.normalize();
  13586. // skip lights with undefined direction
  13587. // these create troubles in OpenGL (making pixel black)
  13588. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  13589. dirOffset = dirLength * 3;
  13590. dirPositions[ dirOffset ] = _direction.x;
  13591. dirPositions[ dirOffset + 1 ] = _direction.y;
  13592. dirPositions[ dirOffset + 2 ] = _direction.z;
  13593. if ( _this.gammaInput ) {
  13594. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  13595. } else {
  13596. setColorLinear( dirColors, dirOffset, color, intensity );
  13597. }
  13598. dirLength += 1;
  13599. } else if ( light instanceof THREE.PointLight ) {
  13600. pointCount += 1;
  13601. if ( ! light.visible ) continue;
  13602. pointOffset = pointLength * 3;
  13603. if ( _this.gammaInput ) {
  13604. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  13605. } else {
  13606. setColorLinear( pointColors, pointOffset, color, intensity );
  13607. }
  13608. position = light.matrixWorld.getPosition();
  13609. pointPositions[ pointOffset ] = position.x;
  13610. pointPositions[ pointOffset + 1 ] = position.y;
  13611. pointPositions[ pointOffset + 2 ] = position.z;
  13612. pointDistances[ pointLength ] = distance;
  13613. pointLength += 1;
  13614. } else if ( light instanceof THREE.SpotLight ) {
  13615. spotCount += 1;
  13616. if ( ! light.visible ) continue;
  13617. spotOffset = spotLength * 3;
  13618. if ( _this.gammaInput ) {
  13619. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  13620. } else {
  13621. setColorLinear( spotColors, spotOffset, color, intensity );
  13622. }
  13623. position = light.matrixWorld.getPosition();
  13624. spotPositions[ spotOffset ] = position.x;
  13625. spotPositions[ spotOffset + 1 ] = position.y;
  13626. spotPositions[ spotOffset + 2 ] = position.z;
  13627. spotDistances[ spotLength ] = distance;
  13628. _direction.copy( position );
  13629. _direction.sub( light.target.matrixWorld.getPosition() );
  13630. _direction.normalize();
  13631. spotDirections[ spotOffset ] = _direction.x;
  13632. spotDirections[ spotOffset + 1 ] = _direction.y;
  13633. spotDirections[ spotOffset + 2 ] = _direction.z;
  13634. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  13635. spotExponents[ spotLength ] = light.exponent;
  13636. spotLength += 1;
  13637. } else if ( light instanceof THREE.HemisphereLight ) {
  13638. hemiCount += 1;
  13639. if ( ! light.visible ) continue;
  13640. _direction.copy( light.matrixWorld.getPosition() );
  13641. _direction.normalize();
  13642. // skip lights with undefined direction
  13643. // these create troubles in OpenGL (making pixel black)
  13644. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  13645. hemiOffset = hemiLength * 3;
  13646. hemiPositions[ hemiOffset ] = _direction.x;
  13647. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  13648. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  13649. skyColor = light.color;
  13650. groundColor = light.groundColor;
  13651. if ( _this.gammaInput ) {
  13652. intensitySq = intensity * intensity;
  13653. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  13654. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  13655. } else {
  13656. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  13657. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  13658. }
  13659. hemiLength += 1;
  13660. }
  13661. }
  13662. // null eventual remains from removed lights
  13663. // (this is to avoid if in shader)
  13664. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  13665. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  13666. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  13667. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  13668. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  13669. zlights.directional.length = dirLength;
  13670. zlights.point.length = pointLength;
  13671. zlights.spot.length = spotLength;
  13672. zlights.hemi.length = hemiLength;
  13673. zlights.ambient[ 0 ] = r;
  13674. zlights.ambient[ 1 ] = g;
  13675. zlights.ambient[ 2 ] = b;
  13676. };
  13677. // GL state setting
  13678. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  13679. if ( cullFace === THREE.CullFaceNone ) {
  13680. _gl.disable( _gl.CULL_FACE );
  13681. } else {
  13682. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  13683. _gl.frontFace( _gl.CW );
  13684. } else {
  13685. _gl.frontFace( _gl.CCW );
  13686. }
  13687. if ( cullFace === THREE.CullFaceBack ) {
  13688. _gl.cullFace( _gl.BACK );
  13689. } else if ( cullFace === THREE.CullFaceFront ) {
  13690. _gl.cullFace( _gl.FRONT );
  13691. } else {
  13692. _gl.cullFace( _gl.FRONT_AND_BACK );
  13693. }
  13694. _gl.enable( _gl.CULL_FACE );
  13695. }
  13696. };
  13697. this.setMaterialFaces = function ( material ) {
  13698. var doubleSided = material.side === THREE.DoubleSide;
  13699. var flipSided = material.side === THREE.BackSide;
  13700. if ( _oldDoubleSided !== doubleSided ) {
  13701. if ( doubleSided ) {
  13702. _gl.disable( _gl.CULL_FACE );
  13703. } else {
  13704. _gl.enable( _gl.CULL_FACE );
  13705. }
  13706. _oldDoubleSided = doubleSided;
  13707. }
  13708. if ( _oldFlipSided !== flipSided ) {
  13709. if ( flipSided ) {
  13710. _gl.frontFace( _gl.CW );
  13711. } else {
  13712. _gl.frontFace( _gl.CCW );
  13713. }
  13714. _oldFlipSided = flipSided;
  13715. }
  13716. };
  13717. this.setDepthTest = function ( depthTest ) {
  13718. if ( _oldDepthTest !== depthTest ) {
  13719. if ( depthTest ) {
  13720. _gl.enable( _gl.DEPTH_TEST );
  13721. } else {
  13722. _gl.disable( _gl.DEPTH_TEST );
  13723. }
  13724. _oldDepthTest = depthTest;
  13725. }
  13726. };
  13727. this.setDepthWrite = function ( depthWrite ) {
  13728. if ( _oldDepthWrite !== depthWrite ) {
  13729. _gl.depthMask( depthWrite );
  13730. _oldDepthWrite = depthWrite;
  13731. }
  13732. };
  13733. function setLineWidth ( width ) {
  13734. if ( width !== _oldLineWidth ) {
  13735. _gl.lineWidth( width );
  13736. _oldLineWidth = width;
  13737. }
  13738. };
  13739. function setPolygonOffset ( polygonoffset, factor, units ) {
  13740. if ( _oldPolygonOffset !== polygonoffset ) {
  13741. if ( polygonoffset ) {
  13742. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  13743. } else {
  13744. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  13745. }
  13746. _oldPolygonOffset = polygonoffset;
  13747. }
  13748. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  13749. _gl.polygonOffset( factor, units );
  13750. _oldPolygonOffsetFactor = factor;
  13751. _oldPolygonOffsetUnits = units;
  13752. }
  13753. };
  13754. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  13755. if ( blending !== _oldBlending ) {
  13756. if ( blending === THREE.NoBlending ) {
  13757. _gl.disable( _gl.BLEND );
  13758. } else if ( blending === THREE.AdditiveBlending ) {
  13759. _gl.enable( _gl.BLEND );
  13760. _gl.blendEquation( _gl.FUNC_ADD );
  13761. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  13762. } else if ( blending === THREE.SubtractiveBlending ) {
  13763. // TODO: Find blendFuncSeparate() combination
  13764. _gl.enable( _gl.BLEND );
  13765. _gl.blendEquation( _gl.FUNC_ADD );
  13766. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  13767. } else if ( blending === THREE.MultiplyBlending ) {
  13768. // TODO: Find blendFuncSeparate() combination
  13769. _gl.enable( _gl.BLEND );
  13770. _gl.blendEquation( _gl.FUNC_ADD );
  13771. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  13772. } else if ( blending === THREE.CustomBlending ) {
  13773. _gl.enable( _gl.BLEND );
  13774. } else {
  13775. _gl.enable( _gl.BLEND );
  13776. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  13777. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  13778. }
  13779. _oldBlending = blending;
  13780. }
  13781. if ( blending === THREE.CustomBlending ) {
  13782. if ( blendEquation !== _oldBlendEquation ) {
  13783. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  13784. _oldBlendEquation = blendEquation;
  13785. }
  13786. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  13787. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  13788. _oldBlendSrc = blendSrc;
  13789. _oldBlendDst = blendDst;
  13790. }
  13791. } else {
  13792. _oldBlendEquation = null;
  13793. _oldBlendSrc = null;
  13794. _oldBlendDst = null;
  13795. }
  13796. };
  13797. // Defines
  13798. function generateDefines ( defines ) {
  13799. var value, chunk, chunks = [];
  13800. for ( var d in defines ) {
  13801. value = defines[ d ];
  13802. if ( value === false ) continue;
  13803. chunk = "#define " + d + " " + value;
  13804. chunks.push( chunk );
  13805. }
  13806. return chunks.join( "\n" );
  13807. };
  13808. // Shaders
  13809. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters ) {
  13810. var p, pl, d, program, code;
  13811. var chunks = [];
  13812. // Generate code
  13813. if ( shaderID ) {
  13814. chunks.push( shaderID );
  13815. } else {
  13816. chunks.push( fragmentShader );
  13817. chunks.push( vertexShader );
  13818. }
  13819. for ( d in defines ) {
  13820. chunks.push( d );
  13821. chunks.push( defines[ d ] );
  13822. }
  13823. for ( p in parameters ) {
  13824. chunks.push( p );
  13825. chunks.push( parameters[ p ] );
  13826. }
  13827. code = chunks.join();
  13828. // Check if code has been already compiled
  13829. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  13830. var programInfo = _programs[ p ];
  13831. if ( programInfo.code === code ) {
  13832. //console.log( "Code already compiled." /*: \n\n" + code*/ );
  13833. programInfo.usedTimes ++;
  13834. return programInfo.program;
  13835. }
  13836. }
  13837. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  13838. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  13839. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  13840. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  13841. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  13842. }
  13843. //console.log( "building new program " );
  13844. //
  13845. var customDefines = generateDefines( defines );
  13846. //
  13847. program = _gl.createProgram();
  13848. var prefix_vertex = [
  13849. "precision " + _precision + " float;",
  13850. customDefines,
  13851. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  13852. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  13853. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  13854. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  13855. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  13856. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  13857. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  13858. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  13859. "#define MAX_SHADOWS " + parameters.maxShadows,
  13860. "#define MAX_BONES " + parameters.maxBones,
  13861. parameters.map ? "#define USE_MAP" : "",
  13862. parameters.envMap ? "#define USE_ENVMAP" : "",
  13863. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  13864. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  13865. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  13866. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  13867. parameters.vertexColors ? "#define USE_COLOR" : "",
  13868. parameters.skinning ? "#define USE_SKINNING" : "",
  13869. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  13870. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  13871. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  13872. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  13873. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  13874. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  13875. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  13876. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  13877. parameters.flipSided ? "#define FLIP_SIDED" : "",
  13878. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  13879. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  13880. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  13881. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  13882. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  13883. "uniform mat4 modelMatrix;",
  13884. "uniform mat4 modelViewMatrix;",
  13885. "uniform mat4 projectionMatrix;",
  13886. "uniform mat4 viewMatrix;",
  13887. "uniform mat3 normalMatrix;",
  13888. "uniform vec3 cameraPosition;",
  13889. "attribute vec3 position;",
  13890. "attribute vec3 normal;",
  13891. "attribute vec2 uv;",
  13892. "attribute vec2 uv2;",
  13893. "#ifdef USE_COLOR",
  13894. "attribute vec3 color;",
  13895. "#endif",
  13896. "#ifdef USE_MORPHTARGETS",
  13897. "attribute vec3 morphTarget0;",
  13898. "attribute vec3 morphTarget1;",
  13899. "attribute vec3 morphTarget2;",
  13900. "attribute vec3 morphTarget3;",
  13901. "#ifdef USE_MORPHNORMALS",
  13902. "attribute vec3 morphNormal0;",
  13903. "attribute vec3 morphNormal1;",
  13904. "attribute vec3 morphNormal2;",
  13905. "attribute vec3 morphNormal3;",
  13906. "#else",
  13907. "attribute vec3 morphTarget4;",
  13908. "attribute vec3 morphTarget5;",
  13909. "attribute vec3 morphTarget6;",
  13910. "attribute vec3 morphTarget7;",
  13911. "#endif",
  13912. "#endif",
  13913. "#ifdef USE_SKINNING",
  13914. "attribute vec4 skinIndex;",
  13915. "attribute vec4 skinWeight;",
  13916. "#endif",
  13917. ""
  13918. ].join("\n");
  13919. var prefix_fragment = [
  13920. "precision " + _precision + " float;",
  13921. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  13922. customDefines,
  13923. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  13924. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  13925. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  13926. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  13927. "#define MAX_SHADOWS " + parameters.maxShadows,
  13928. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  13929. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  13930. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  13931. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  13932. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  13933. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  13934. parameters.map ? "#define USE_MAP" : "",
  13935. parameters.envMap ? "#define USE_ENVMAP" : "",
  13936. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  13937. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  13938. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  13939. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  13940. parameters.vertexColors ? "#define USE_COLOR" : "",
  13941. parameters.metal ? "#define METAL" : "",
  13942. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  13943. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  13944. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  13945. parameters.flipSided ? "#define FLIP_SIDED" : "",
  13946. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  13947. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  13948. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  13949. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  13950. "uniform mat4 viewMatrix;",
  13951. "uniform vec3 cameraPosition;",
  13952. ""
  13953. ].join("\n");
  13954. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  13955. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  13956. _gl.attachShader( program, glVertexShader );
  13957. _gl.attachShader( program, glFragmentShader );
  13958. _gl.linkProgram( program );
  13959. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  13960. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  13961. }
  13962. // clean up
  13963. _gl.deleteShader( glFragmentShader );
  13964. _gl.deleteShader( glVertexShader );
  13965. //console.log( prefix_fragment + fragmentShader );
  13966. //console.log( prefix_vertex + vertexShader );
  13967. program.uniforms = {};
  13968. program.attributes = {};
  13969. var identifiers, u, a, i;
  13970. // cache uniform locations
  13971. identifiers = [
  13972. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  13973. 'morphTargetInfluences'
  13974. ];
  13975. if ( parameters.useVertexTexture ) {
  13976. identifiers.push( 'boneTexture' );
  13977. } else {
  13978. identifiers.push( 'boneGlobalMatrices' );
  13979. }
  13980. for ( u in uniforms ) {
  13981. identifiers.push( u );
  13982. }
  13983. cacheUniformLocations( program, identifiers );
  13984. // cache attributes locations
  13985. identifiers = [
  13986. "position", "normal", "uv", "uv2", "tangent", "color",
  13987. "skinIndex", "skinWeight", "lineDistance"
  13988. ];
  13989. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  13990. identifiers.push( "morphTarget" + i );
  13991. }
  13992. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  13993. identifiers.push( "morphNormal" + i );
  13994. }
  13995. for ( a in attributes ) {
  13996. identifiers.push( a );
  13997. }
  13998. cacheAttributeLocations( program, identifiers );
  13999. program.id = _programs_counter ++;
  14000. _programs.push( { program: program, code: code, usedTimes: 1 } );
  14001. _this.info.memory.programs = _programs.length;
  14002. return program;
  14003. };
  14004. // Shader parameters cache
  14005. function cacheUniformLocations ( program, identifiers ) {
  14006. var i, l, id;
  14007. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14008. id = identifiers[ i ];
  14009. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  14010. }
  14011. };
  14012. function cacheAttributeLocations ( program, identifiers ) {
  14013. var i, l, id;
  14014. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  14015. id = identifiers[ i ];
  14016. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  14017. }
  14018. };
  14019. function addLineNumbers ( string ) {
  14020. var chunks = string.split( "\n" );
  14021. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  14022. // Chrome reports shader errors on lines
  14023. // starting counting from 1
  14024. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  14025. }
  14026. return chunks.join( "\n" );
  14027. };
  14028. function getShader ( type, string ) {
  14029. var shader;
  14030. if ( type === "fragment" ) {
  14031. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  14032. } else if ( type === "vertex" ) {
  14033. shader = _gl.createShader( _gl.VERTEX_SHADER );
  14034. }
  14035. _gl.shaderSource( shader, string );
  14036. _gl.compileShader( shader );
  14037. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  14038. console.error( _gl.getShaderInfoLog( shader ) );
  14039. console.error( addLineNumbers( string ) );
  14040. return null;
  14041. }
  14042. return shader;
  14043. };
  14044. // Textures
  14045. function isPowerOfTwo ( value ) {
  14046. return ( value & ( value - 1 ) ) === 0;
  14047. };
  14048. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  14049. if ( isImagePowerOfTwo ) {
  14050. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  14051. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  14052. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  14053. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  14054. } else {
  14055. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  14056. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  14057. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  14058. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  14059. }
  14060. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  14061. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  14062. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  14063. texture.__oldAnisotropy = texture.anisotropy;
  14064. }
  14065. }
  14066. };
  14067. this.setTexture = function ( texture, slot ) {
  14068. if ( texture.needsUpdate ) {
  14069. if ( ! texture.__webglInit ) {
  14070. texture.__webglInit = true;
  14071. texture.addEventListener( 'dispose', onTextureDispose );
  14072. texture.__webglTexture = _gl.createTexture();
  14073. _this.info.memory.textures ++;
  14074. }
  14075. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14076. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14077. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14078. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14079. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14080. var image = texture.image,
  14081. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  14082. glFormat = paramThreeToGL( texture.format ),
  14083. glType = paramThreeToGL( texture.type );
  14084. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  14085. var mipmap, mipmaps = texture.mipmaps;
  14086. if ( texture instanceof THREE.DataTexture ) {
  14087. // use manually created mipmaps if available
  14088. // if there are no manual mipmaps
  14089. // set 0 level mipmap and then use GL to generate other mipmap levels
  14090. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14091. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14092. mipmap = mipmaps[ i ];
  14093. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14094. }
  14095. texture.generateMipmaps = false;
  14096. } else {
  14097. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14098. }
  14099. } else if ( texture instanceof THREE.CompressedTexture ) {
  14100. // compressed textures can only use manually created mipmaps
  14101. // WebGL can't generate mipmaps for DDS textures
  14102. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14103. mipmap = mipmaps[ i ];
  14104. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14105. }
  14106. } else { // regular Texture (image, video, canvas)
  14107. // use manually created mipmaps if available
  14108. // if there are no manual mipmaps
  14109. // set 0 level mipmap and then use GL to generate other mipmap levels
  14110. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14111. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14112. mipmap = mipmaps[ i ];
  14113. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  14114. }
  14115. texture.generateMipmaps = false;
  14116. } else {
  14117. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  14118. }
  14119. }
  14120. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14121. texture.needsUpdate = false;
  14122. if ( texture.onUpdate ) texture.onUpdate();
  14123. } else {
  14124. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14125. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14126. }
  14127. };
  14128. function clampToMaxSize ( image, maxSize ) {
  14129. if ( image.width <= maxSize && image.height <= maxSize ) {
  14130. return image;
  14131. }
  14132. // Warning: Scaling through the canvas will only work with images that use
  14133. // premultiplied alpha.
  14134. var maxDimension = Math.max( image.width, image.height );
  14135. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  14136. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  14137. var canvas = document.createElement( 'canvas' );
  14138. canvas.width = newWidth;
  14139. canvas.height = newHeight;
  14140. var ctx = canvas.getContext( "2d" );
  14141. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  14142. return canvas;
  14143. }
  14144. function setCubeTexture ( texture, slot ) {
  14145. if ( texture.image.length === 6 ) {
  14146. if ( texture.needsUpdate ) {
  14147. if ( ! texture.image.__webglTextureCube ) {
  14148. texture.image.__webglTextureCube = _gl.createTexture();
  14149. _this.info.memory.textures ++;
  14150. }
  14151. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14152. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  14153. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14154. var isCompressed = texture instanceof THREE.CompressedTexture;
  14155. var cubeImage = [];
  14156. for ( var i = 0; i < 6; i ++ ) {
  14157. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  14158. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  14159. } else {
  14160. cubeImage[ i ] = texture.image[ i ];
  14161. }
  14162. }
  14163. var image = cubeImage[ 0 ],
  14164. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  14165. glFormat = paramThreeToGL( texture.format ),
  14166. glType = paramThreeToGL( texture.type );
  14167. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  14168. for ( var i = 0; i < 6; i ++ ) {
  14169. if ( isCompressed ) {
  14170. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  14171. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  14172. mipmap = mipmaps[ j ];
  14173. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14174. }
  14175. } else {
  14176. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  14177. }
  14178. }
  14179. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  14180. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14181. }
  14182. texture.needsUpdate = false;
  14183. if ( texture.onUpdate ) texture.onUpdate();
  14184. } else {
  14185. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14186. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  14187. }
  14188. }
  14189. };
  14190. function setCubeTextureDynamic ( texture, slot ) {
  14191. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14192. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  14193. };
  14194. // Render targets
  14195. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  14196. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14197. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  14198. };
  14199. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  14200. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  14201. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14202. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  14203. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14204. /* For some reason this is not working. Defaulting to RGBA4.
  14205. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14206. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  14207. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14208. */
  14209. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14210. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  14211. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14212. } else {
  14213. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  14214. }
  14215. };
  14216. this.setRenderTarget = function ( renderTarget ) {
  14217. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  14218. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  14219. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  14220. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  14221. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  14222. renderTarget.__webglTexture = _gl.createTexture();
  14223. _this.info.memory.textures ++;
  14224. // Setup texture, create render and frame buffers
  14225. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  14226. glFormat = paramThreeToGL( renderTarget.format ),
  14227. glType = paramThreeToGL( renderTarget.type );
  14228. if ( isCube ) {
  14229. renderTarget.__webglFramebuffer = [];
  14230. renderTarget.__webglRenderbuffer = [];
  14231. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  14232. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  14233. for ( var i = 0; i < 6; i ++ ) {
  14234. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  14235. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  14236. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14237. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  14238. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  14239. }
  14240. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14241. } else {
  14242. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  14243. if ( renderTarget.shareDepthFrom ) {
  14244. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  14245. } else {
  14246. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  14247. }
  14248. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  14249. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  14250. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14251. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  14252. if ( renderTarget.shareDepthFrom ) {
  14253. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14254. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  14255. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14256. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  14257. }
  14258. } else {
  14259. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  14260. }
  14261. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14262. }
  14263. // Release everything
  14264. if ( isCube ) {
  14265. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  14266. } else {
  14267. _gl.bindTexture( _gl.TEXTURE_2D, null );
  14268. }
  14269. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  14270. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14271. }
  14272. var framebuffer, width, height, vx, vy;
  14273. if ( renderTarget ) {
  14274. if ( isCube ) {
  14275. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  14276. } else {
  14277. framebuffer = renderTarget.__webglFramebuffer;
  14278. }
  14279. width = renderTarget.width;
  14280. height = renderTarget.height;
  14281. vx = 0;
  14282. vy = 0;
  14283. } else {
  14284. framebuffer = null;
  14285. width = _viewportWidth;
  14286. height = _viewportHeight;
  14287. vx = _viewportX;
  14288. vy = _viewportY;
  14289. }
  14290. if ( framebuffer !== _currentFramebuffer ) {
  14291. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14292. _gl.viewport( vx, vy, width, height );
  14293. _currentFramebuffer = framebuffer;
  14294. }
  14295. _currentWidth = width;
  14296. _currentHeight = height;
  14297. };
  14298. function updateRenderTargetMipmap ( renderTarget ) {
  14299. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  14300. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  14301. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14302. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  14303. } else {
  14304. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  14305. _gl.generateMipmap( _gl.TEXTURE_2D );
  14306. _gl.bindTexture( _gl.TEXTURE_2D, null );
  14307. }
  14308. };
  14309. // Fallback filters for non-power-of-2 textures
  14310. function filterFallback ( f ) {
  14311. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  14312. return _gl.NEAREST;
  14313. }
  14314. return _gl.LINEAR;
  14315. };
  14316. // Map three.js constants to WebGL constants
  14317. function paramThreeToGL ( p ) {
  14318. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  14319. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  14320. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  14321. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  14322. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  14323. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  14324. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  14325. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  14326. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  14327. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  14328. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  14329. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  14330. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  14331. if ( p === THREE.ByteType ) return _gl.BYTE;
  14332. if ( p === THREE.ShortType ) return _gl.SHORT;
  14333. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  14334. if ( p === THREE.IntType ) return _gl.INT;
  14335. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  14336. if ( p === THREE.FloatType ) return _gl.FLOAT;
  14337. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  14338. if ( p === THREE.RGBFormat ) return _gl.RGB;
  14339. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  14340. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  14341. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  14342. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  14343. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  14344. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  14345. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  14346. if ( p === THREE.OneFactor ) return _gl.ONE;
  14347. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  14348. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  14349. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  14350. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  14351. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  14352. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  14353. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  14354. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  14355. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  14356. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  14357. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14358. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14359. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14360. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14361. }
  14362. return 0;
  14363. };
  14364. // Allocations
  14365. function allocateBones ( object ) {
  14366. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  14367. return 1024;
  14368. } else {
  14369. // default for when object is not specified
  14370. // ( for example when prebuilding shader
  14371. // to be used with multiple objects )
  14372. //
  14373. // - leave some extra space for other uniforms
  14374. // - limit here is ANGLE's 254 max uniform vectors
  14375. // (up to 54 should be safe)
  14376. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  14377. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  14378. var maxBones = nVertexMatrices;
  14379. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  14380. maxBones = Math.min( object.bones.length, maxBones );
  14381. if ( maxBones < object.bones.length ) {
  14382. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  14383. }
  14384. }
  14385. return maxBones;
  14386. }
  14387. };
  14388. function allocateLights ( lights ) {
  14389. var l, ll, light, dirLights, pointLights, spotLights, hemiLights;
  14390. dirLights = pointLights = spotLights = hemiLights = 0;
  14391. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14392. light = lights[ l ];
  14393. if ( light.onlyShadow ) continue;
  14394. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  14395. if ( light instanceof THREE.PointLight ) pointLights ++;
  14396. if ( light instanceof THREE.SpotLight ) spotLights ++;
  14397. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  14398. }
  14399. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  14400. };
  14401. function allocateShadows ( lights ) {
  14402. var l, ll, light, maxShadows = 0;
  14403. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  14404. light = lights[ l ];
  14405. if ( ! light.castShadow ) continue;
  14406. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  14407. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  14408. }
  14409. return maxShadows;
  14410. };
  14411. // Initialization
  14412. function initGL () {
  14413. try {
  14414. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  14415. throw 'Error creating WebGL context.';
  14416. }
  14417. } catch ( error ) {
  14418. console.error( error );
  14419. }
  14420. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  14421. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  14422. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) ||
  14423. _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) ||
  14424. _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  14425. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) ||
  14426. _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) ||
  14427. _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  14428. if ( ! _glExtensionTextureFloat ) {
  14429. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  14430. }
  14431. if ( ! _glExtensionStandardDerivatives ) {
  14432. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  14433. }
  14434. if ( ! _glExtensionTextureFilterAnisotropic ) {
  14435. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  14436. }
  14437. if ( ! _glExtensionCompressedTextureS3TC ) {
  14438. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  14439. }
  14440. };
  14441. function setDefaultGLState () {
  14442. _gl.clearColor( 0, 0, 0, 1 );
  14443. _gl.clearDepth( 1 );
  14444. _gl.clearStencil( 0 );
  14445. _gl.enable( _gl.DEPTH_TEST );
  14446. _gl.depthFunc( _gl.LEQUAL );
  14447. _gl.frontFace( _gl.CCW );
  14448. _gl.cullFace( _gl.BACK );
  14449. _gl.enable( _gl.CULL_FACE );
  14450. _gl.enable( _gl.BLEND );
  14451. _gl.blendEquation( _gl.FUNC_ADD );
  14452. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  14453. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  14454. };
  14455. // default plugins (order is important)
  14456. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  14457. this.addPrePlugin( this.shadowMapPlugin );
  14458. this.addPostPlugin( new THREE.SpritePlugin() );
  14459. this.addPostPlugin( new THREE.LensFlarePlugin() );
  14460. };
  14461. /**
  14462. * @author szimek / https://github.com/szimek/
  14463. * @author alteredq / http://alteredqualia.com/
  14464. */
  14465. THREE.WebGLRenderTarget = function ( width, height, options ) {
  14466. THREE.EventDispatcher.call( this );
  14467. this.width = width;
  14468. this.height = height;
  14469. options = options || {};
  14470. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  14471. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  14472. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  14473. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  14474. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  14475. this.offset = new THREE.Vector2( 0, 0 );
  14476. this.repeat = new THREE.Vector2( 1, 1 );
  14477. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  14478. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  14479. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  14480. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  14481. this.generateMipmaps = true;
  14482. this.shareDepthFrom = null;
  14483. };
  14484. THREE.WebGLRenderTarget.prototype.clone = function() {
  14485. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  14486. tmp.wrapS = this.wrapS;
  14487. tmp.wrapT = this.wrapT;
  14488. tmp.magFilter = this.magFilter;
  14489. tmp.minFilter = this.minFilter;
  14490. tmp.anisotropy = this.anisotropy;
  14491. tmp.offset.copy( this.offset );
  14492. tmp.repeat.copy( this.repeat );
  14493. tmp.format = this.format;
  14494. tmp.type = this.type;
  14495. tmp.depthBuffer = this.depthBuffer;
  14496. tmp.stencilBuffer = this.stencilBuffer;
  14497. tmp.generateMipmaps = this.generateMipmaps;
  14498. tmp.shareDepthFrom = this.shareDepthFrom;
  14499. return tmp;
  14500. };
  14501. THREE.WebGLRenderTarget.prototype.dispose = function () {
  14502. this.dispatchEvent( { type: 'dispose' } );
  14503. };
  14504. /**
  14505. * @author alteredq / http://alteredqualia.com
  14506. */
  14507. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  14508. THREE.WebGLRenderTarget.call( this, width, height, options );
  14509. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  14510. };
  14511. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  14512. /**
  14513. * @author mrdoob / http://mrdoob.com/
  14514. */
  14515. THREE.RenderableVertex = function () {
  14516. this.positionWorld = new THREE.Vector3();
  14517. this.positionScreen = new THREE.Vector4();
  14518. this.visible = true;
  14519. };
  14520. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  14521. this.positionWorld.copy( vertex.positionWorld );
  14522. this.positionScreen.copy( vertex.positionScreen );
  14523. };
  14524. /**
  14525. * @author mrdoob / http://mrdoob.com/
  14526. */
  14527. THREE.RenderableFace3 = function () {
  14528. this.v1 = new THREE.RenderableVertex();
  14529. this.v2 = new THREE.RenderableVertex();
  14530. this.v3 = new THREE.RenderableVertex();
  14531. this.centroidModel = new THREE.Vector3();
  14532. this.normalModel = new THREE.Vector3();
  14533. this.normalModelView = new THREE.Vector3();
  14534. this.vertexNormalsLength = 0;
  14535. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  14536. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  14537. this.color = null;
  14538. this.material = null;
  14539. this.uvs = [[]];
  14540. this.z = null;
  14541. };
  14542. /**
  14543. * @author mrdoob / http://mrdoob.com/
  14544. */
  14545. THREE.RenderableFace4 = function () {
  14546. this.v1 = new THREE.RenderableVertex();
  14547. this.v2 = new THREE.RenderableVertex();
  14548. this.v3 = new THREE.RenderableVertex();
  14549. this.v4 = new THREE.RenderableVertex();
  14550. this.centroidModel = new THREE.Vector3();
  14551. this.normalModel = new THREE.Vector3();
  14552. this.normalModelView = new THREE.Vector3();
  14553. this.vertexNormalsLength = 0;
  14554. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  14555. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  14556. this.color = null;
  14557. this.material = null;
  14558. this.uvs = [[]];
  14559. this.z = null;
  14560. };
  14561. /**
  14562. * @author mrdoob / http://mrdoob.com/
  14563. */
  14564. THREE.RenderableObject = function () {
  14565. this.object = null;
  14566. this.z = null;
  14567. };
  14568. /**
  14569. * @author mrdoob / http://mrdoob.com/
  14570. */
  14571. THREE.RenderableParticle = function () {
  14572. this.object = null;
  14573. this.x = null;
  14574. this.y = null;
  14575. this.z = null;
  14576. this.rotation = null;
  14577. this.scale = new THREE.Vector2();
  14578. this.material = null;
  14579. };
  14580. /**
  14581. * @author mrdoob / http://mrdoob.com/
  14582. */
  14583. THREE.RenderableLine = function () {
  14584. this.z = null;
  14585. this.v1 = new THREE.RenderableVertex();
  14586. this.v2 = new THREE.RenderableVertex();
  14587. this.material = null;
  14588. };
  14589. /**
  14590. * @author alteredq / http://alteredqualia.com/
  14591. */
  14592. THREE.ColorUtils = {
  14593. adjustHSV : function ( color, h, s, v ) {
  14594. var hsv = THREE.ColorUtils.__hsv;
  14595. color.getHSV( hsv );
  14596. hsv.h = THREE.Math.clamp( hsv.h + h, 0, 1 );
  14597. hsv.s = THREE.Math.clamp( hsv.s + s, 0, 1 );
  14598. hsv.v = THREE.Math.clamp( hsv.v + v, 0, 1 );
  14599. color.setHSV( hsv.h, hsv.s, hsv.v );
  14600. }
  14601. };
  14602. THREE.ColorUtils.__hsv = { h: 0, s: 0, v: 0 };/**
  14603. * @author mrdoob / http://mrdoob.com/
  14604. * @author alteredq / http://alteredqualia.com/
  14605. */
  14606. THREE.GeometryUtils = {
  14607. // Merge two geometries or geometry and geometry from object (using object's transform)
  14608. merge: function ( geometry1, object2 /* mesh | geometry */ ) {
  14609. var matrix, normalMatrix,
  14610. vertexOffset = geometry1.vertices.length,
  14611. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  14612. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  14613. vertices1 = geometry1.vertices,
  14614. vertices2 = geometry2.vertices,
  14615. faces1 = geometry1.faces,
  14616. faces2 = geometry2.faces,
  14617. uvs1 = geometry1.faceVertexUvs[ 0 ],
  14618. uvs2 = geometry2.faceVertexUvs[ 0 ];
  14619. if ( object2 instanceof THREE.Mesh ) {
  14620. object2.matrixAutoUpdate && object2.updateMatrix();
  14621. matrix = object2.matrix;
  14622. normalMatrix = new THREE.Matrix3();
  14623. normalMatrix.getInverse( matrix );
  14624. normalMatrix.transpose();
  14625. }
  14626. // vertices
  14627. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  14628. var vertex = vertices2[ i ];
  14629. var vertexCopy = vertex.clone();
  14630. if ( matrix ) vertexCopy.applyMatrix4( matrix );
  14631. vertices1.push( vertexCopy );
  14632. }
  14633. // faces
  14634. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  14635. var face = faces2[ i ], faceCopy, normal, color,
  14636. faceVertexNormals = face.vertexNormals,
  14637. faceVertexColors = face.vertexColors;
  14638. if ( face instanceof THREE.Face3 ) {
  14639. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  14640. } else if ( face instanceof THREE.Face4 ) {
  14641. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  14642. }
  14643. faceCopy.normal.copy( face.normal );
  14644. if ( normalMatrix ) {
  14645. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  14646. }
  14647. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  14648. normal = faceVertexNormals[ j ].clone();
  14649. if ( normalMatrix ) {
  14650. normal.applyMatrix3( normalMatrix ).normalize();
  14651. }
  14652. faceCopy.vertexNormals.push( normal );
  14653. }
  14654. faceCopy.color.copy( face.color );
  14655. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  14656. color = faceVertexColors[ j ];
  14657. faceCopy.vertexColors.push( color.clone() );
  14658. }
  14659. faceCopy.materialIndex = face.materialIndex;
  14660. faceCopy.centroid.copy( face.centroid );
  14661. if ( matrix ) {
  14662. faceCopy.centroid.applyMatrix4( matrix );
  14663. }
  14664. faces1.push( faceCopy );
  14665. }
  14666. // uvs
  14667. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  14668. var uv = uvs2[ i ], uvCopy = [];
  14669. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  14670. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  14671. }
  14672. uvs1.push( uvCopy );
  14673. }
  14674. },
  14675. removeMaterials: function ( geometry, materialIndexArray ) {
  14676. var materialIndexMap = {};
  14677. for ( var i = 0, il = materialIndexArray.length; i < il; i ++ ) {
  14678. materialIndexMap[ materialIndexArray[i] ] = true;
  14679. }
  14680. var face, newFaces = [];
  14681. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14682. face = geometry.faces[ i ];
  14683. if ( ! ( face.materialIndex in materialIndexMap ) ) newFaces.push( face );
  14684. }
  14685. geometry.faces = newFaces;
  14686. },
  14687. // Get random point in triangle (via barycentric coordinates)
  14688. // (uniform distribution)
  14689. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  14690. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  14691. var a, b, c,
  14692. point = new THREE.Vector3(),
  14693. tmp = THREE.GeometryUtils.__v1;
  14694. a = THREE.GeometryUtils.random();
  14695. b = THREE.GeometryUtils.random();
  14696. if ( ( a + b ) > 1 ) {
  14697. a = 1 - a;
  14698. b = 1 - b;
  14699. }
  14700. c = 1 - a - b;
  14701. point.copy( vectorA );
  14702. point.multiplyScalar( a );
  14703. tmp.copy( vectorB );
  14704. tmp.multiplyScalar( b );
  14705. point.add( tmp );
  14706. tmp.copy( vectorC );
  14707. tmp.multiplyScalar( c );
  14708. point.add( tmp );
  14709. return point;
  14710. },
  14711. // Get random point in face (triangle / quad)
  14712. // (uniform distribution)
  14713. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  14714. var vA, vB, vC, vD;
  14715. if ( face instanceof THREE.Face3 ) {
  14716. vA = geometry.vertices[ face.a ];
  14717. vB = geometry.vertices[ face.b ];
  14718. vC = geometry.vertices[ face.c ];
  14719. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  14720. } else if ( face instanceof THREE.Face4 ) {
  14721. vA = geometry.vertices[ face.a ];
  14722. vB = geometry.vertices[ face.b ];
  14723. vC = geometry.vertices[ face.c ];
  14724. vD = geometry.vertices[ face.d ];
  14725. var area1, area2;
  14726. if ( useCachedAreas ) {
  14727. if ( face._area1 && face._area2 ) {
  14728. area1 = face._area1;
  14729. area2 = face._area2;
  14730. } else {
  14731. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  14732. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  14733. face._area1 = area1;
  14734. face._area2 = area2;
  14735. }
  14736. } else {
  14737. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  14738. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  14739. }
  14740. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  14741. if ( r < area1 ) {
  14742. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  14743. } else {
  14744. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  14745. }
  14746. }
  14747. },
  14748. // Get uniformly distributed random points in mesh
  14749. // - create array with cumulative sums of face areas
  14750. // - pick random number from 0 to total area
  14751. // - find corresponding place in area array by binary search
  14752. // - get random point in face
  14753. randomPointsInGeometry: function ( geometry, n ) {
  14754. var face, i,
  14755. faces = geometry.faces,
  14756. vertices = geometry.vertices,
  14757. il = faces.length,
  14758. totalArea = 0,
  14759. cumulativeAreas = [],
  14760. vA, vB, vC, vD;
  14761. // precompute face areas
  14762. for ( i = 0; i < il; i ++ ) {
  14763. face = faces[ i ];
  14764. if ( face instanceof THREE.Face3 ) {
  14765. vA = vertices[ face.a ];
  14766. vB = vertices[ face.b ];
  14767. vC = vertices[ face.c ];
  14768. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  14769. } else if ( face instanceof THREE.Face4 ) {
  14770. vA = vertices[ face.a ];
  14771. vB = vertices[ face.b ];
  14772. vC = vertices[ face.c ];
  14773. vD = vertices[ face.d ];
  14774. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  14775. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  14776. face._area = face._area1 + face._area2;
  14777. }
  14778. totalArea += face._area;
  14779. cumulativeAreas[ i ] = totalArea;
  14780. }
  14781. // binary search cumulative areas array
  14782. function binarySearchIndices( value ) {
  14783. function binarySearch( start, end ) {
  14784. // return closest larger index
  14785. // if exact number is not found
  14786. if ( end < start )
  14787. return start;
  14788. var mid = start + Math.floor( ( end - start ) / 2 );
  14789. if ( cumulativeAreas[ mid ] > value ) {
  14790. return binarySearch( start, mid - 1 );
  14791. } else if ( cumulativeAreas[ mid ] < value ) {
  14792. return binarySearch( mid + 1, end );
  14793. } else {
  14794. return mid;
  14795. }
  14796. }
  14797. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  14798. return result;
  14799. }
  14800. // pick random face weighted by face area
  14801. var r, index,
  14802. result = [];
  14803. var stats = {};
  14804. for ( i = 0; i < n; i ++ ) {
  14805. r = THREE.GeometryUtils.random() * totalArea;
  14806. index = binarySearchIndices( r );
  14807. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  14808. if ( ! stats[ index ] ) {
  14809. stats[ index ] = 1;
  14810. } else {
  14811. stats[ index ] += 1;
  14812. }
  14813. }
  14814. return result;
  14815. },
  14816. // Get triangle area (half of parallelogram)
  14817. // http://mathworld.wolfram.com/TriangleArea.html
  14818. triangleArea: function ( vectorA, vectorB, vectorC ) {
  14819. var tmp1 = THREE.GeometryUtils.__v1,
  14820. tmp2 = THREE.GeometryUtils.__v2;
  14821. tmp1.subVectors( vectorB, vectorA );
  14822. tmp2.subVectors( vectorC, vectorA );
  14823. tmp1.cross( tmp2 );
  14824. return 0.5 * tmp1.length();
  14825. },
  14826. // Center geometry so that 0,0,0 is in center of bounding box
  14827. center: function ( geometry ) {
  14828. geometry.computeBoundingBox();
  14829. var bb = geometry.boundingBox;
  14830. var offset = new THREE.Vector3();
  14831. offset.addVectors( bb.min, bb.max );
  14832. offset.multiplyScalar( -0.5 );
  14833. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset ) );
  14834. geometry.computeBoundingBox();
  14835. return offset;
  14836. },
  14837. // Normalize UVs to be from <0,1>
  14838. // (for now just the first set of UVs)
  14839. normalizeUVs: function ( geometry ) {
  14840. var uvSet = geometry.faceVertexUvs[ 0 ];
  14841. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  14842. var uvs = uvSet[ i ];
  14843. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  14844. // texture repeat
  14845. if( uvs[ j ].x !== 1.0 ) uvs[ j ].x = uvs[ j ].x - Math.floor( uvs[ j ].x );
  14846. if( uvs[ j ].y !== 1.0 ) uvs[ j ].y = uvs[ j ].y - Math.floor( uvs[ j ].y );
  14847. }
  14848. }
  14849. },
  14850. triangulateQuads: function ( geometry ) {
  14851. var i, il, j, jl;
  14852. var faces = [];
  14853. var faceUvs = [];
  14854. var faceVertexUvs = [];
  14855. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  14856. faceUvs[ i ] = [];
  14857. }
  14858. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  14859. faceVertexUvs[ i ] = [];
  14860. }
  14861. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14862. var face = geometry.faces[ i ];
  14863. if ( face instanceof THREE.Face4 ) {
  14864. var a = face.a;
  14865. var b = face.b;
  14866. var c = face.c;
  14867. var d = face.d;
  14868. var triA = new THREE.Face3();
  14869. var triB = new THREE.Face3();
  14870. triA.color.copy( face.color );
  14871. triB.color.copy( face.color );
  14872. triA.materialIndex = face.materialIndex;
  14873. triB.materialIndex = face.materialIndex;
  14874. triA.a = a;
  14875. triA.b = b;
  14876. triA.c = d;
  14877. triB.a = b;
  14878. triB.b = c;
  14879. triB.c = d;
  14880. if ( face.vertexColors.length === 4 ) {
  14881. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  14882. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  14883. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  14884. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  14885. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  14886. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  14887. }
  14888. faces.push( triA, triB );
  14889. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14890. if ( geometry.faceVertexUvs[ j ].length ) {
  14891. var uvs = geometry.faceVertexUvs[ j ][ i ];
  14892. var uvA = uvs[ 0 ];
  14893. var uvB = uvs[ 1 ];
  14894. var uvC = uvs[ 2 ];
  14895. var uvD = uvs[ 3 ];
  14896. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  14897. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  14898. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  14899. }
  14900. }
  14901. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  14902. if ( geometry.faceUvs[ j ].length ) {
  14903. var faceUv = geometry.faceUvs[ j ][ i ];
  14904. faceUvs[ j ].push( faceUv, faceUv );
  14905. }
  14906. }
  14907. } else {
  14908. faces.push( face );
  14909. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  14910. faceUvs[ j ].push( geometry.faceUvs[ j ][ i ] );
  14911. }
  14912. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14913. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  14914. }
  14915. }
  14916. }
  14917. geometry.faces = faces;
  14918. geometry.faceUvs = faceUvs;
  14919. geometry.faceVertexUvs = faceVertexUvs;
  14920. geometry.computeCentroids();
  14921. geometry.computeFaceNormals();
  14922. geometry.computeVertexNormals();
  14923. if ( geometry.hasTangents ) geometry.computeTangents();
  14924. },
  14925. setMaterialIndex: function ( geometry, index, startFace, endFace ){
  14926. var faces = geometry.faces;
  14927. var start = startFace || 0;
  14928. var end = endFace || faces.length - 1;
  14929. for ( var i = start; i <= end; i ++ ) {
  14930. faces[i].materialIndex = index;
  14931. }
  14932. }
  14933. };
  14934. THREE.GeometryUtils.random = THREE.Math.random16;
  14935. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  14936. THREE.GeometryUtils.__v2 = new THREE.Vector3();
  14937. /**
  14938. * @author alteredq / http://alteredqualia.com/
  14939. * @author mrdoob / http://mrdoob.com/
  14940. */
  14941. THREE.ImageUtils = {
  14942. crossOrigin: 'anonymous',
  14943. loadTexture: function ( url, mapping, onLoad, onError ) {
  14944. var image = new Image();
  14945. var texture = new THREE.Texture( image, mapping );
  14946. var loader = new THREE.ImageLoader();
  14947. loader.addEventListener( 'load', function ( event ) {
  14948. texture.image = event.content;
  14949. texture.needsUpdate = true;
  14950. if ( onLoad ) onLoad( texture );
  14951. } );
  14952. loader.addEventListener( 'error', function ( event ) {
  14953. if ( onError ) onError( event.message );
  14954. } );
  14955. loader.crossOrigin = this.crossOrigin;
  14956. loader.load( url, image );
  14957. texture.sourceFile = url;
  14958. return texture;
  14959. },
  14960. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  14961. var texture = new THREE.CompressedTexture();
  14962. texture.mapping = mapping;
  14963. var request = new XMLHttpRequest();
  14964. request.onload = function () {
  14965. var buffer = request.response;
  14966. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  14967. texture.format = dds.format;
  14968. texture.mipmaps = dds.mipmaps;
  14969. texture.image.width = dds.width;
  14970. texture.image.height = dds.height;
  14971. // gl.generateMipmap fails for compressed textures
  14972. // mipmaps must be embedded in the DDS file
  14973. // or texture filters must not use mipmapping
  14974. texture.generateMipmaps = false;
  14975. texture.needsUpdate = true;
  14976. if ( onLoad ) onLoad( texture );
  14977. }
  14978. request.onerror = onError;
  14979. request.open( 'GET', url, true );
  14980. request.responseType = "arraybuffer";
  14981. request.send( null );
  14982. return texture;
  14983. },
  14984. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  14985. var images = [];
  14986. images.loadCount = 0;
  14987. var texture = new THREE.Texture();
  14988. texture.image = images;
  14989. if ( mapping !== undefined ) texture.mapping = mapping;
  14990. // no flipping needed for cube textures
  14991. texture.flipY = false;
  14992. for ( var i = 0, il = array.length; i < il; ++ i ) {
  14993. var cubeImage = new Image();
  14994. images[ i ] = cubeImage;
  14995. cubeImage.onload = function () {
  14996. images.loadCount += 1;
  14997. if ( images.loadCount === 6 ) {
  14998. texture.needsUpdate = true;
  14999. if ( onLoad ) onLoad( texture );
  15000. }
  15001. };
  15002. cubeImage.onerror = onError;
  15003. cubeImage.crossOrigin = this.crossOrigin;
  15004. cubeImage.src = array[ i ];
  15005. }
  15006. return texture;
  15007. },
  15008. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  15009. var images = [];
  15010. images.loadCount = 0;
  15011. var texture = new THREE.CompressedTexture();
  15012. texture.image = images;
  15013. if ( mapping !== undefined ) texture.mapping = mapping;
  15014. // no flipping for cube textures
  15015. // (also flipping doesn't work for compressed textures )
  15016. texture.flipY = false;
  15017. // can't generate mipmaps for compressed textures
  15018. // mips must be embedded in DDS files
  15019. texture.generateMipmaps = false;
  15020. var generateCubeFaceCallback = function ( rq, img ) {
  15021. return function () {
  15022. var buffer = rq.response;
  15023. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15024. img.format = dds.format;
  15025. img.mipmaps = dds.mipmaps;
  15026. img.width = dds.width;
  15027. img.height = dds.height;
  15028. images.loadCount += 1;
  15029. if ( images.loadCount === 6 ) {
  15030. texture.format = dds.format;
  15031. texture.needsUpdate = true;
  15032. if ( onLoad ) onLoad( texture );
  15033. }
  15034. }
  15035. }
  15036. // compressed cubemap textures as 6 separate DDS files
  15037. if ( array instanceof Array ) {
  15038. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15039. var cubeImage = {};
  15040. images[ i ] = cubeImage;
  15041. var request = new XMLHttpRequest();
  15042. request.onload = generateCubeFaceCallback( request, cubeImage );
  15043. request.onerror = onError;
  15044. var url = array[ i ];
  15045. request.open( 'GET', url, true );
  15046. request.responseType = "arraybuffer";
  15047. request.send( null );
  15048. }
  15049. // compressed cubemap texture stored in a single DDS file
  15050. } else {
  15051. var url = array;
  15052. var request = new XMLHttpRequest();
  15053. request.onload = function( ) {
  15054. var buffer = request.response;
  15055. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15056. if ( dds.isCubemap ) {
  15057. var faces = dds.mipmaps.length / dds.mipmapCount;
  15058. for ( var f = 0; f < faces; f ++ ) {
  15059. images[ f ] = { mipmaps : [] };
  15060. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15061. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  15062. images[ f ].format = dds.format;
  15063. images[ f ].width = dds.width;
  15064. images[ f ].height = dds.height;
  15065. }
  15066. }
  15067. texture.format = dds.format;
  15068. texture.needsUpdate = true;
  15069. if ( onLoad ) onLoad( texture );
  15070. }
  15071. }
  15072. request.onerror = onError;
  15073. request.open( 'GET', url, true );
  15074. request.responseType = "arraybuffer";
  15075. request.send( null );
  15076. }
  15077. return texture;
  15078. },
  15079. parseDDS: function ( buffer, loadMipmaps ) {
  15080. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  15081. // Adapted from @toji's DDS utils
  15082. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  15083. // All values and structures referenced from:
  15084. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  15085. var DDS_MAGIC = 0x20534444;
  15086. var DDSD_CAPS = 0x1,
  15087. DDSD_HEIGHT = 0x2,
  15088. DDSD_WIDTH = 0x4,
  15089. DDSD_PITCH = 0x8,
  15090. DDSD_PIXELFORMAT = 0x1000,
  15091. DDSD_MIPMAPCOUNT = 0x20000,
  15092. DDSD_LINEARSIZE = 0x80000,
  15093. DDSD_DEPTH = 0x800000;
  15094. var DDSCAPS_COMPLEX = 0x8,
  15095. DDSCAPS_MIPMAP = 0x400000,
  15096. DDSCAPS_TEXTURE = 0x1000;
  15097. var DDSCAPS2_CUBEMAP = 0x200,
  15098. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  15099. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  15100. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  15101. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  15102. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  15103. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  15104. DDSCAPS2_VOLUME = 0x200000;
  15105. var DDPF_ALPHAPIXELS = 0x1,
  15106. DDPF_ALPHA = 0x2,
  15107. DDPF_FOURCC = 0x4,
  15108. DDPF_RGB = 0x40,
  15109. DDPF_YUV = 0x200,
  15110. DDPF_LUMINANCE = 0x20000;
  15111. function fourCCToInt32( value ) {
  15112. return value.charCodeAt(0) +
  15113. (value.charCodeAt(1) << 8) +
  15114. (value.charCodeAt(2) << 16) +
  15115. (value.charCodeAt(3) << 24);
  15116. }
  15117. function int32ToFourCC( value ) {
  15118. return String.fromCharCode(
  15119. value & 0xff,
  15120. (value >> 8) & 0xff,
  15121. (value >> 16) & 0xff,
  15122. (value >> 24) & 0xff
  15123. );
  15124. }
  15125. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  15126. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  15127. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  15128. var headerLengthInt = 31; // The header length in 32 bit ints
  15129. // Offsets into the header array
  15130. var off_magic = 0;
  15131. var off_size = 1;
  15132. var off_flags = 2;
  15133. var off_height = 3;
  15134. var off_width = 4;
  15135. var off_mipmapCount = 7;
  15136. var off_pfFlags = 20;
  15137. var off_pfFourCC = 21;
  15138. var off_caps = 27;
  15139. var off_caps2 = 28;
  15140. var off_caps3 = 29;
  15141. var off_caps4 = 30;
  15142. // Parse header
  15143. var header = new Int32Array( buffer, 0, headerLengthInt );
  15144. if ( header[ off_magic ] !== DDS_MAGIC ) {
  15145. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  15146. return dds;
  15147. }
  15148. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  15149. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  15150. return dds;
  15151. }
  15152. var blockBytes;
  15153. var fourCC = header[ off_pfFourCC ];
  15154. switch ( fourCC ) {
  15155. case FOURCC_DXT1:
  15156. blockBytes = 8;
  15157. dds.format = THREE.RGB_S3TC_DXT1_Format;
  15158. break;
  15159. case FOURCC_DXT3:
  15160. blockBytes = 16;
  15161. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  15162. break;
  15163. case FOURCC_DXT5:
  15164. blockBytes = 16;
  15165. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  15166. break;
  15167. default:
  15168. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  15169. return dds;
  15170. }
  15171. dds.mipmapCount = 1;
  15172. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  15173. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  15174. }
  15175. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  15176. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  15177. dds.width = header[ off_width ];
  15178. dds.height = header[ off_height ];
  15179. var dataOffset = header[ off_size ] + 4;
  15180. // Extract mipmaps buffers
  15181. var width = dds.width;
  15182. var height = dds.height;
  15183. var faces = dds.isCubemap ? 6 : 1;
  15184. for ( var face = 0; face < faces; face ++ ) {
  15185. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15186. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  15187. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  15188. var mipmap = { "data": byteArray, "width": width, "height": height };
  15189. dds.mipmaps.push( mipmap );
  15190. dataOffset += dataLength;
  15191. width = Math.max( width * 0.5, 1 );
  15192. height = Math.max( height * 0.5, 1 );
  15193. }
  15194. width = dds.width;
  15195. height = dds.height;
  15196. }
  15197. return dds;
  15198. },
  15199. getNormalMap: function ( image, depth ) {
  15200. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  15201. var cross = function ( a, b ) {
  15202. 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 ] ];
  15203. }
  15204. var subtract = function ( a, b ) {
  15205. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  15206. }
  15207. var normalize = function ( a ) {
  15208. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  15209. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  15210. }
  15211. depth = depth | 1;
  15212. var width = image.width;
  15213. var height = image.height;
  15214. var canvas = document.createElement( 'canvas' );
  15215. canvas.width = width;
  15216. canvas.height = height;
  15217. var context = canvas.getContext( '2d' );
  15218. context.drawImage( image, 0, 0 );
  15219. var data = context.getImageData( 0, 0, width, height ).data;
  15220. var imageData = context.createImageData( width, height );
  15221. var output = imageData.data;
  15222. for ( var x = 0; x < width; x ++ ) {
  15223. for ( var y = 0; y < height; y ++ ) {
  15224. var ly = y - 1 < 0 ? 0 : y - 1;
  15225. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  15226. var lx = x - 1 < 0 ? 0 : x - 1;
  15227. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  15228. var points = [];
  15229. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  15230. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  15231. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  15232. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  15233. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  15234. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  15235. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  15236. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  15237. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  15238. var normals = [];
  15239. var num_points = points.length;
  15240. for ( var i = 0; i < num_points; i ++ ) {
  15241. var v1 = points[ i ];
  15242. var v2 = points[ ( i + 1 ) % num_points ];
  15243. v1 = subtract( v1, origin );
  15244. v2 = subtract( v2, origin );
  15245. normals.push( normalize( cross( v1, v2 ) ) );
  15246. }
  15247. var normal = [ 0, 0, 0 ];
  15248. for ( var i = 0; i < normals.length; i ++ ) {
  15249. normal[ 0 ] += normals[ i ][ 0 ];
  15250. normal[ 1 ] += normals[ i ][ 1 ];
  15251. normal[ 2 ] += normals[ i ][ 2 ];
  15252. }
  15253. normal[ 0 ] /= normals.length;
  15254. normal[ 1 ] /= normals.length;
  15255. normal[ 2 ] /= normals.length;
  15256. var idx = ( y * width + x ) * 4;
  15257. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15258. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15259. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  15260. output[ idx + 3 ] = 255;
  15261. }
  15262. }
  15263. context.putImageData( imageData, 0, 0 );
  15264. return canvas;
  15265. },
  15266. generateDataTexture: function ( width, height, color ) {
  15267. var size = width * height;
  15268. var data = new Uint8Array( 3 * size );
  15269. var r = Math.floor( color.r * 255 );
  15270. var g = Math.floor( color.g * 255 );
  15271. var b = Math.floor( color.b * 255 );
  15272. for ( var i = 0; i < size; i ++ ) {
  15273. data[ i * 3 ] = r;
  15274. data[ i * 3 + 1 ] = g;
  15275. data[ i * 3 + 2 ] = b;
  15276. }
  15277. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  15278. texture.needsUpdate = true;
  15279. return texture;
  15280. }
  15281. };
  15282. /**
  15283. * @author alteredq / http://alteredqualia.com/
  15284. */
  15285. THREE.SceneUtils = {
  15286. createMultiMaterialObject: function ( geometry, materials ) {
  15287. var group = new THREE.Object3D();
  15288. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  15289. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  15290. }
  15291. return group;
  15292. },
  15293. detach : function ( child, parent, scene ) {
  15294. child.applyMatrix( parent.matrixWorld );
  15295. parent.remove( child );
  15296. scene.add( child );
  15297. },
  15298. attach: function ( child, scene, parent ) {
  15299. var matrixWorldInverse = new THREE.Matrix4();
  15300. matrixWorldInverse.getInverse( parent.matrixWorld );
  15301. child.applyMatrix( matrixWorldInverse );
  15302. scene.remove( child );
  15303. parent.add( child );
  15304. }
  15305. };
  15306. /**
  15307. * @author alteredq / http://alteredqualia.com/
  15308. * @author mrdoob / http://mrdoob.com/
  15309. *
  15310. * ShaderUtils currently contains:
  15311. *
  15312. * fresnel
  15313. * normal
  15314. * cube
  15315. *
  15316. */
  15317. THREE.ShaderUtils = {
  15318. lib: {
  15319. /* -------------------------------------------------------------------------
  15320. // Fresnel shader
  15321. // - based on Nvidia Cg tutorial
  15322. ------------------------------------------------------------------------- */
  15323. 'fresnel': {
  15324. uniforms: {
  15325. "mRefractionRatio": { type: "f", value: 1.02 },
  15326. "mFresnelBias": { type: "f", value: 0.1 },
  15327. "mFresnelPower": { type: "f", value: 2.0 },
  15328. "mFresnelScale": { type: "f", value: 1.0 },
  15329. "tCube": { type: "t", value: null }
  15330. },
  15331. fragmentShader: [
  15332. "uniform samplerCube tCube;",
  15333. "varying vec3 vReflect;",
  15334. "varying vec3 vRefract[3];",
  15335. "varying float vReflectionFactor;",
  15336. "void main() {",
  15337. "vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  15338. "vec4 refractedColor = vec4( 1.0 );",
  15339. "refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;",
  15340. "refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;",
  15341. "refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;",
  15342. "gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );",
  15343. "}"
  15344. ].join("\n"),
  15345. vertexShader: [
  15346. "uniform float mRefractionRatio;",
  15347. "uniform float mFresnelBias;",
  15348. "uniform float mFresnelScale;",
  15349. "uniform float mFresnelPower;",
  15350. "varying vec3 vReflect;",
  15351. "varying vec3 vRefract[3];",
  15352. "varying float vReflectionFactor;",
  15353. "void main() {",
  15354. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  15355. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  15356. "vec3 worldNormal = normalize( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );",
  15357. "vec3 I = worldPosition.xyz - cameraPosition;",
  15358. "vReflect = reflect( I, worldNormal );",
  15359. "vRefract[0] = refract( normalize( I ), worldNormal, mRefractionRatio );",
  15360. "vRefract[1] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.99 );",
  15361. "vRefract[2] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.98 );",
  15362. "vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), worldNormal ), mFresnelPower );",
  15363. "gl_Position = projectionMatrix * mvPosition;",
  15364. "}"
  15365. ].join("\n")
  15366. },
  15367. /* -------------------------------------------------------------------------
  15368. // Normal map shader
  15369. // - Blinn-Phong
  15370. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  15371. // - point and directional lights (use with "lights: true" material option)
  15372. ------------------------------------------------------------------------- */
  15373. 'normal' : {
  15374. uniforms: THREE.UniformsUtils.merge( [
  15375. THREE.UniformsLib[ "fog" ],
  15376. THREE.UniformsLib[ "lights" ],
  15377. THREE.UniformsLib[ "shadowmap" ],
  15378. {
  15379. "enableAO" : { type: "i", value: 0 },
  15380. "enableDiffuse" : { type: "i", value: 0 },
  15381. "enableSpecular" : { type: "i", value: 0 },
  15382. "enableReflection": { type: "i", value: 0 },
  15383. "enableDisplacement": { type: "i", value: 0 },
  15384. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  15385. "tDiffuse" : { type: "t", value: null },
  15386. "tCube" : { type: "t", value: null },
  15387. "tNormal" : { type: "t", value: null },
  15388. "tSpecular" : { type: "t", value: null },
  15389. "tAO" : { type: "t", value: null },
  15390. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  15391. "uDisplacementBias": { type: "f", value: 0.0 },
  15392. "uDisplacementScale": { type: "f", value: 1.0 },
  15393. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  15394. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  15395. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  15396. "uShininess": { type: "f", value: 30 },
  15397. "uOpacity": { type: "f", value: 1 },
  15398. "useRefract": { type: "i", value: 0 },
  15399. "uRefractionRatio": { type: "f", value: 0.98 },
  15400. "uReflectivity": { type: "f", value: 0.5 },
  15401. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  15402. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  15403. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  15404. }
  15405. ] ),
  15406. fragmentShader: [
  15407. "uniform vec3 uAmbientColor;",
  15408. "uniform vec3 uDiffuseColor;",
  15409. "uniform vec3 uSpecularColor;",
  15410. "uniform float uShininess;",
  15411. "uniform float uOpacity;",
  15412. "uniform bool enableDiffuse;",
  15413. "uniform bool enableSpecular;",
  15414. "uniform bool enableAO;",
  15415. "uniform bool enableReflection;",
  15416. "uniform sampler2D tDiffuse;",
  15417. "uniform sampler2D tNormal;",
  15418. "uniform sampler2D tSpecular;",
  15419. "uniform sampler2D tAO;",
  15420. "uniform samplerCube tCube;",
  15421. "uniform vec2 uNormalScale;",
  15422. "uniform bool useRefract;",
  15423. "uniform float uRefractionRatio;",
  15424. "uniform float uReflectivity;",
  15425. "varying vec3 vTangent;",
  15426. "varying vec3 vBinormal;",
  15427. "varying vec3 vNormal;",
  15428. "varying vec2 vUv;",
  15429. "uniform vec3 ambientLightColor;",
  15430. "#if MAX_DIR_LIGHTS > 0",
  15431. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  15432. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  15433. "#endif",
  15434. "#if MAX_HEMI_LIGHTS > 0",
  15435. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  15436. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  15437. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  15438. "#endif",
  15439. "#if MAX_POINT_LIGHTS > 0",
  15440. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  15441. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  15442. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  15443. "#endif",
  15444. "#if MAX_SPOT_LIGHTS > 0",
  15445. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  15446. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  15447. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  15448. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  15449. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  15450. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  15451. "#endif",
  15452. "#ifdef WRAP_AROUND",
  15453. "uniform vec3 wrapRGB;",
  15454. "#endif",
  15455. "varying vec3 vWorldPosition;",
  15456. "varying vec3 vViewPosition;",
  15457. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  15458. THREE.ShaderChunk[ "fog_pars_fragment" ],
  15459. "void main() {",
  15460. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  15461. "vec3 specularTex = vec3( 1.0 );",
  15462. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  15463. "normalTex.xy *= uNormalScale;",
  15464. "normalTex = normalize( normalTex );",
  15465. "if( enableDiffuse ) {",
  15466. "#ifdef GAMMA_INPUT",
  15467. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  15468. "texelColor.xyz *= texelColor.xyz;",
  15469. "gl_FragColor = gl_FragColor * texelColor;",
  15470. "#else",
  15471. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  15472. "#endif",
  15473. "}",
  15474. "if( enableAO ) {",
  15475. "#ifdef GAMMA_INPUT",
  15476. "vec4 aoColor = texture2D( tAO, vUv );",
  15477. "aoColor.xyz *= aoColor.xyz;",
  15478. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  15479. "#else",
  15480. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  15481. "#endif",
  15482. "}",
  15483. "if( enableSpecular )",
  15484. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  15485. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  15486. "vec3 finalNormal = tsb * normalTex;",
  15487. "#ifdef FLIP_SIDED",
  15488. "finalNormal = -finalNormal;",
  15489. "#endif",
  15490. "vec3 normal = normalize( finalNormal );",
  15491. "vec3 viewPosition = normalize( vViewPosition );",
  15492. // point lights
  15493. "#if MAX_POINT_LIGHTS > 0",
  15494. "vec3 pointDiffuse = vec3( 0.0 );",
  15495. "vec3 pointSpecular = vec3( 0.0 );",
  15496. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  15497. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  15498. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  15499. "float pointDistance = 1.0;",
  15500. "if ( pointLightDistance[ i ] > 0.0 )",
  15501. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  15502. "pointVector = normalize( pointVector );",
  15503. // diffuse
  15504. "#ifdef WRAP_AROUND",
  15505. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  15506. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  15507. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  15508. "#else",
  15509. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  15510. "#endif",
  15511. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  15512. // specular
  15513. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  15514. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  15515. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  15516. "#ifdef PHYSICALLY_BASED_SHADING",
  15517. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15518. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15519. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  15520. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  15521. "#else",
  15522. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  15523. "#endif",
  15524. "}",
  15525. "#endif",
  15526. // spot lights
  15527. "#if MAX_SPOT_LIGHTS > 0",
  15528. "vec3 spotDiffuse = vec3( 0.0 );",
  15529. "vec3 spotSpecular = vec3( 0.0 );",
  15530. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  15531. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  15532. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  15533. "float spotDistance = 1.0;",
  15534. "if ( spotLightDistance[ i ] > 0.0 )",
  15535. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  15536. "spotVector = normalize( spotVector );",
  15537. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  15538. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  15539. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  15540. // diffuse
  15541. "#ifdef WRAP_AROUND",
  15542. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  15543. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  15544. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  15545. "#else",
  15546. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  15547. "#endif",
  15548. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  15549. // specular
  15550. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  15551. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  15552. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  15553. "#ifdef PHYSICALLY_BASED_SHADING",
  15554. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15555. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15556. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  15557. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  15558. "#else",
  15559. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  15560. "#endif",
  15561. "}",
  15562. "}",
  15563. "#endif",
  15564. // directional lights
  15565. "#if MAX_DIR_LIGHTS > 0",
  15566. "vec3 dirDiffuse = vec3( 0.0 );",
  15567. "vec3 dirSpecular = vec3( 0.0 );",
  15568. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  15569. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  15570. "vec3 dirVector = normalize( lDirection.xyz );",
  15571. // diffuse
  15572. "#ifdef WRAP_AROUND",
  15573. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  15574. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  15575. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  15576. "#else",
  15577. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  15578. "#endif",
  15579. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  15580. // specular
  15581. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  15582. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  15583. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  15584. "#ifdef PHYSICALLY_BASED_SHADING",
  15585. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15586. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15587. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  15588. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  15589. "#else",
  15590. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  15591. "#endif",
  15592. "}",
  15593. "#endif",
  15594. // hemisphere lights
  15595. "#if MAX_HEMI_LIGHTS > 0",
  15596. "vec3 hemiDiffuse = vec3( 0.0 );",
  15597. "vec3 hemiSpecular = vec3( 0.0 );" ,
  15598. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  15599. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  15600. "vec3 lVector = normalize( lDirection.xyz );",
  15601. // diffuse
  15602. "float dotProduct = dot( normal, lVector );",
  15603. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  15604. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  15605. "hemiDiffuse += uDiffuseColor * hemiColor;",
  15606. // specular (sky light)
  15607. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  15608. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  15609. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  15610. // specular (ground light)
  15611. "vec3 lVectorGround = -lVector;",
  15612. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  15613. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  15614. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  15615. "#ifdef PHYSICALLY_BASED_SHADING",
  15616. "float dotProductGround = dot( normal, lVectorGround );",
  15617. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15618. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15619. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  15620. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  15621. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  15622. "#else",
  15623. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  15624. "#endif",
  15625. "}",
  15626. "#endif",
  15627. // all lights contribution summation
  15628. "vec3 totalDiffuse = vec3( 0.0 );",
  15629. "vec3 totalSpecular = vec3( 0.0 );",
  15630. "#if MAX_DIR_LIGHTS > 0",
  15631. "totalDiffuse += dirDiffuse;",
  15632. "totalSpecular += dirSpecular;",
  15633. "#endif",
  15634. "#if MAX_HEMI_LIGHTS > 0",
  15635. "totalDiffuse += hemiDiffuse;",
  15636. "totalSpecular += hemiSpecular;",
  15637. "#endif",
  15638. "#if MAX_POINT_LIGHTS > 0",
  15639. "totalDiffuse += pointDiffuse;",
  15640. "totalSpecular += pointSpecular;",
  15641. "#endif",
  15642. "#if MAX_SPOT_LIGHTS > 0",
  15643. "totalDiffuse += spotDiffuse;",
  15644. "totalSpecular += spotSpecular;",
  15645. "#endif",
  15646. "#ifdef METAL",
  15647. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  15648. "#else",
  15649. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  15650. "#endif",
  15651. "if ( enableReflection ) {",
  15652. "vec3 vReflect;",
  15653. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  15654. "if ( useRefract ) {",
  15655. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  15656. "} else {",
  15657. "vReflect = reflect( cameraToVertex, normal );",
  15658. "}",
  15659. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  15660. "#ifdef GAMMA_INPUT",
  15661. "cubeColor.xyz *= cubeColor.xyz;",
  15662. "#endif",
  15663. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  15664. "}",
  15665. THREE.ShaderChunk[ "shadowmap_fragment" ],
  15666. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  15667. THREE.ShaderChunk[ "fog_fragment" ],
  15668. "}"
  15669. ].join("\n"),
  15670. vertexShader: [
  15671. "attribute vec4 tangent;",
  15672. "uniform vec2 uOffset;",
  15673. "uniform vec2 uRepeat;",
  15674. "uniform bool enableDisplacement;",
  15675. "#ifdef VERTEX_TEXTURES",
  15676. "uniform sampler2D tDisplacement;",
  15677. "uniform float uDisplacementScale;",
  15678. "uniform float uDisplacementBias;",
  15679. "#endif",
  15680. "varying vec3 vTangent;",
  15681. "varying vec3 vBinormal;",
  15682. "varying vec3 vNormal;",
  15683. "varying vec2 vUv;",
  15684. "varying vec3 vWorldPosition;",
  15685. "varying vec3 vViewPosition;",
  15686. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  15687. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  15688. "void main() {",
  15689. THREE.ShaderChunk[ "skinbase_vertex" ],
  15690. THREE.ShaderChunk[ "skinnormal_vertex" ],
  15691. // normal, tangent and binormal vectors
  15692. "#ifdef USE_SKINNING",
  15693. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  15694. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  15695. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  15696. "#else",
  15697. "vNormal = normalize( normalMatrix * normal );",
  15698. "vTangent = normalize( normalMatrix * tangent.xyz );",
  15699. "#endif",
  15700. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  15701. "vUv = uv * uRepeat + uOffset;",
  15702. // displacement mapping
  15703. "vec3 displacedPosition;",
  15704. "#ifdef VERTEX_TEXTURES",
  15705. "if ( enableDisplacement ) {",
  15706. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  15707. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  15708. "displacedPosition = position + normalize( normal ) * df;",
  15709. "} else {",
  15710. "#ifdef USE_SKINNING",
  15711. "vec4 skinVertex = vec4( position, 1.0 );",
  15712. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  15713. "skinned += boneMatY * skinVertex * skinWeight.y;",
  15714. "displacedPosition = skinned.xyz;",
  15715. "#else",
  15716. "displacedPosition = position;",
  15717. "#endif",
  15718. "}",
  15719. "#else",
  15720. "#ifdef USE_SKINNING",
  15721. "vec4 skinVertex = vec4( position, 1.0 );",
  15722. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  15723. "skinned += boneMatY * skinVertex * skinWeight.y;",
  15724. "displacedPosition = skinned.xyz;",
  15725. "#else",
  15726. "displacedPosition = position;",
  15727. "#endif",
  15728. "#endif",
  15729. //
  15730. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  15731. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  15732. "gl_Position = projectionMatrix * mvPosition;",
  15733. //
  15734. "vWorldPosition = worldPosition.xyz;",
  15735. "vViewPosition = -mvPosition.xyz;",
  15736. // shadows
  15737. "#ifdef USE_SHADOWMAP",
  15738. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  15739. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  15740. "}",
  15741. "#endif",
  15742. "}"
  15743. ].join("\n")
  15744. },
  15745. /* -------------------------------------------------------------------------
  15746. // Cube map shader
  15747. ------------------------------------------------------------------------- */
  15748. 'cube': {
  15749. uniforms: { "tCube": { type: "t", value: null },
  15750. "tFlip": { type: "f", value: -1 } },
  15751. vertexShader: [
  15752. "varying vec3 vWorldPosition;",
  15753. "void main() {",
  15754. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  15755. "vWorldPosition = worldPosition.xyz;",
  15756. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  15757. "}"
  15758. ].join("\n"),
  15759. fragmentShader: [
  15760. "uniform samplerCube tCube;",
  15761. "uniform float tFlip;",
  15762. "varying vec3 vWorldPosition;",
  15763. "void main() {",
  15764. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  15765. "}"
  15766. ].join("\n")
  15767. }
  15768. }
  15769. };
  15770. /**
  15771. * @author zz85 / http://www.lab4games.net/zz85/blog
  15772. * @author alteredq / http://alteredqualia.com/
  15773. *
  15774. * For Text operations in three.js (See TextGeometry)
  15775. *
  15776. * It uses techniques used in:
  15777. *
  15778. * typeface.js and canvastext
  15779. * For converting fonts and rendering with javascript
  15780. * http://typeface.neocracy.org
  15781. *
  15782. * Triangulation ported from AS3
  15783. * Simple Polygon Triangulation
  15784. * http://actionsnippet.com/?p=1462
  15785. *
  15786. * A Method to triangulate shapes with holes
  15787. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  15788. *
  15789. */
  15790. THREE.FontUtils = {
  15791. faces : {},
  15792. // Just for now. face[weight][style]
  15793. face : "helvetiker",
  15794. weight: "normal",
  15795. style : "normal",
  15796. size : 150,
  15797. divisions : 10,
  15798. getFace : function() {
  15799. return this.faces[ this.face ][ this.weight ][ this.style ];
  15800. },
  15801. loadFace : function( data ) {
  15802. var family = data.familyName.toLowerCase();
  15803. var ThreeFont = this;
  15804. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  15805. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  15806. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15807. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15808. return data;
  15809. },
  15810. drawText : function( text ) {
  15811. var characterPts = [], allPts = [];
  15812. // RenderText
  15813. var i, p,
  15814. face = this.getFace(),
  15815. scale = this.size / face.resolution,
  15816. offset = 0,
  15817. chars = String( text ).split( '' ),
  15818. length = chars.length;
  15819. var fontPaths = [];
  15820. for ( i = 0; i < length; i ++ ) {
  15821. var path = new THREE.Path();
  15822. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  15823. offset += ret.offset;
  15824. fontPaths.push( ret.path );
  15825. }
  15826. // get the width
  15827. var width = offset / 2;
  15828. //
  15829. // for ( p = 0; p < allPts.length; p++ ) {
  15830. //
  15831. // allPts[ p ].x -= width;
  15832. //
  15833. // }
  15834. //var extract = this.extractPoints( allPts, characterPts );
  15835. //extract.contour = allPts;
  15836. //extract.paths = fontPaths;
  15837. //extract.offset = width;
  15838. return { paths : fontPaths, offset : width };
  15839. },
  15840. extractGlyphPoints : function( c, face, scale, offset, path ) {
  15841. var pts = [];
  15842. var i, i2, divisions,
  15843. outline, action, length,
  15844. scaleX, scaleY,
  15845. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  15846. laste,
  15847. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  15848. if ( !glyph ) return;
  15849. if ( glyph.o ) {
  15850. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  15851. length = outline.length;
  15852. scaleX = scale;
  15853. scaleY = scale;
  15854. for ( i = 0; i < length; ) {
  15855. action = outline[ i ++ ];
  15856. //console.log( action );
  15857. switch( action ) {
  15858. case 'm':
  15859. // Move To
  15860. x = outline[ i++ ] * scaleX + offset;
  15861. y = outline[ i++ ] * scaleY;
  15862. path.moveTo( x, y );
  15863. break;
  15864. case 'l':
  15865. // Line To
  15866. x = outline[ i++ ] * scaleX + offset;
  15867. y = outline[ i++ ] * scaleY;
  15868. path.lineTo(x,y);
  15869. break;
  15870. case 'q':
  15871. // QuadraticCurveTo
  15872. cpx = outline[ i++ ] * scaleX + offset;
  15873. cpy = outline[ i++ ] * scaleY;
  15874. cpx1 = outline[ i++ ] * scaleX + offset;
  15875. cpy1 = outline[ i++ ] * scaleY;
  15876. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  15877. laste = pts[ pts.length - 1 ];
  15878. if ( laste ) {
  15879. cpx0 = laste.x;
  15880. cpy0 = laste.y;
  15881. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15882. var t = i2 / divisions;
  15883. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  15884. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  15885. }
  15886. }
  15887. break;
  15888. case 'b':
  15889. // Cubic Bezier Curve
  15890. cpx = outline[ i++ ] * scaleX + offset;
  15891. cpy = outline[ i++ ] * scaleY;
  15892. cpx1 = outline[ i++ ] * scaleX + offset;
  15893. cpy1 = outline[ i++ ] * -scaleY;
  15894. cpx2 = outline[ i++ ] * scaleX + offset;
  15895. cpy2 = outline[ i++ ] * -scaleY;
  15896. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  15897. laste = pts[ pts.length - 1 ];
  15898. if ( laste ) {
  15899. cpx0 = laste.x;
  15900. cpy0 = laste.y;
  15901. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15902. var t = i2 / divisions;
  15903. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  15904. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  15905. }
  15906. }
  15907. break;
  15908. }
  15909. }
  15910. }
  15911. return { offset: glyph.ha*scale, path:path};
  15912. }
  15913. };
  15914. THREE.FontUtils.generateShapes = function( text, parameters ) {
  15915. // Parameters
  15916. parameters = parameters || {};
  15917. var size = parameters.size !== undefined ? parameters.size : 100;
  15918. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  15919. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  15920. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  15921. var style = parameters.style !== undefined ? parameters.style : "normal";
  15922. THREE.FontUtils.size = size;
  15923. THREE.FontUtils.divisions = curveSegments;
  15924. THREE.FontUtils.face = font;
  15925. THREE.FontUtils.weight = weight;
  15926. THREE.FontUtils.style = style;
  15927. // Get a Font data json object
  15928. var data = THREE.FontUtils.drawText( text );
  15929. var paths = data.paths;
  15930. var shapes = [];
  15931. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  15932. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  15933. }
  15934. return shapes;
  15935. };
  15936. /**
  15937. * This code is a quick port of code written in C++ which was submitted to
  15938. * flipcode.com by John W. Ratcliff // July 22, 2000
  15939. * See original code and more information here:
  15940. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  15941. *
  15942. * ported to actionscript by Zevan Rosser
  15943. * www.actionsnippet.com
  15944. *
  15945. * ported to javascript by Joshua Koo
  15946. * http://www.lab4games.net/zz85/blog
  15947. *
  15948. */
  15949. ( function( namespace ) {
  15950. var EPSILON = 0.0000000001;
  15951. // takes in an contour array and returns
  15952. var process = function( contour, indices ) {
  15953. var n = contour.length;
  15954. if ( n < 3 ) return null;
  15955. var result = [],
  15956. verts = [],
  15957. vertIndices = [];
  15958. /* we want a counter-clockwise polygon in verts */
  15959. var u, v, w;
  15960. if ( area( contour ) > 0.0 ) {
  15961. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  15962. } else {
  15963. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  15964. }
  15965. var nv = n;
  15966. /* remove nv - 2 vertices, creating 1 triangle every time */
  15967. var count = 2 * nv; /* error detection */
  15968. for( v = nv - 1; nv > 2; ) {
  15969. /* if we loop, it is probably a non-simple polygon */
  15970. if ( ( count-- ) <= 0 ) {
  15971. //** Triangulate: ERROR - probable bad polygon!
  15972. //throw ( "Warning, unable to triangulate polygon!" );
  15973. //return null;
  15974. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  15975. console.log( "Warning, unable to triangulate polygon!" );
  15976. if ( indices ) return vertIndices;
  15977. return result;
  15978. }
  15979. /* three consecutive vertices in current polygon, <u,v,w> */
  15980. u = v; if ( nv <= u ) u = 0; /* previous */
  15981. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  15982. w = v + 1; if ( nv <= w ) w = 0; /* next */
  15983. if ( snip( contour, u, v, w, nv, verts ) ) {
  15984. var a, b, c, s, t;
  15985. /* true names of the vertices */
  15986. a = verts[ u ];
  15987. b = verts[ v ];
  15988. c = verts[ w ];
  15989. /* output Triangle */
  15990. result.push( [ contour[ a ],
  15991. contour[ b ],
  15992. contour[ c ] ] );
  15993. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  15994. /* remove v from the remaining polygon */
  15995. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  15996. verts[ s ] = verts[ t ];
  15997. }
  15998. nv--;
  15999. /* reset error detection counter */
  16000. count = 2 * nv;
  16001. }
  16002. }
  16003. if ( indices ) return vertIndices;
  16004. return result;
  16005. };
  16006. // calculate area of the contour polygon
  16007. var area = function ( contour ) {
  16008. var n = contour.length;
  16009. var a = 0.0;
  16010. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16011. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16012. }
  16013. return a * 0.5;
  16014. };
  16015. var snip = function ( contour, u, v, w, n, verts ) {
  16016. var p;
  16017. var ax, ay, bx, by;
  16018. var cx, cy, px, py;
  16019. ax = contour[ verts[ u ] ].x;
  16020. ay = contour[ verts[ u ] ].y;
  16021. bx = contour[ verts[ v ] ].x;
  16022. by = contour[ verts[ v ] ].y;
  16023. cx = contour[ verts[ w ] ].x;
  16024. cy = contour[ verts[ w ] ].y;
  16025. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16026. var aX, aY, bX, bY, cX, cY;
  16027. var apx, apy, bpx, bpy, cpx, cpy;
  16028. var cCROSSap, bCROSScp, aCROSSbp;
  16029. aX = cx - bx; aY = cy - by;
  16030. bX = ax - cx; bY = ay - cy;
  16031. cX = bx - ax; cY = by - ay;
  16032. for ( p = 0; p < n; p++ ) {
  16033. if( (p === u) || (p === v) || (p === w) ) continue;
  16034. px = contour[ verts[ p ] ].x
  16035. py = contour[ verts[ p ] ].y
  16036. apx = px - ax; apy = py - ay;
  16037. bpx = px - bx; bpy = py - by;
  16038. cpx = px - cx; cpy = py - cy;
  16039. // see if p is inside triangle abc
  16040. aCROSSbp = aX*bpy - aY*bpx;
  16041. cCROSSap = cX*apy - cY*apx;
  16042. bCROSScp = bX*cpy - bY*cpx;
  16043. if ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) ) return false;
  16044. }
  16045. return true;
  16046. };
  16047. namespace.Triangulate = process;
  16048. namespace.Triangulate.area = area;
  16049. return namespace;
  16050. })(THREE.FontUtils);
  16051. // To use the typeface.js face files, hook up the API
  16052. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };/**
  16053. * @author zz85 / http://www.lab4games.net/zz85/blog
  16054. * Extensible curve object
  16055. *
  16056. * Some common of Curve methods
  16057. * .getPoint(t), getTangent(t)
  16058. * .getPointAt(u), getTagentAt(u)
  16059. * .getPoints(), .getSpacedPoints()
  16060. * .getLength()
  16061. * .updateArcLengths()
  16062. *
  16063. * This file contains following classes:
  16064. *
  16065. * -- 2d classes --
  16066. * THREE.Curve
  16067. * THREE.LineCurve
  16068. * THREE.QuadraticBezierCurve
  16069. * THREE.CubicBezierCurve
  16070. * THREE.SplineCurve
  16071. * THREE.ArcCurve
  16072. * THREE.EllipseCurve
  16073. *
  16074. * -- 3d classes --
  16075. * THREE.LineCurve3
  16076. * THREE.QuadraticBezierCurve3
  16077. * THREE.CubicBezierCurve3
  16078. * THREE.SplineCurve3
  16079. * THREE.ClosedSplineCurve3
  16080. *
  16081. * A series of curves can be represented as a THREE.CurvePath
  16082. *
  16083. **/
  16084. /**************************************************************
  16085. * Abstract Curve base class
  16086. **************************************************************/
  16087. THREE.Curve = function () {
  16088. };
  16089. // Virtual base class method to overwrite and implement in subclasses
  16090. // - t [0 .. 1]
  16091. THREE.Curve.prototype.getPoint = function ( t ) {
  16092. console.log( "Warning, getPoint() not implemented!" );
  16093. return null;
  16094. };
  16095. // Get point at relative position in curve according to arc length
  16096. // - u [0 .. 1]
  16097. THREE.Curve.prototype.getPointAt = function ( u ) {
  16098. var t = this.getUtoTmapping( u );
  16099. return this.getPoint( t );
  16100. };
  16101. // Get sequence of points using getPoint( t )
  16102. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16103. if ( !divisions ) divisions = 5;
  16104. var d, pts = [];
  16105. for ( d = 0; d <= divisions; d ++ ) {
  16106. pts.push( this.getPoint( d / divisions ) );
  16107. }
  16108. return pts;
  16109. };
  16110. // Get sequence of points using getPointAt( u )
  16111. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16112. if ( !divisions ) divisions = 5;
  16113. var d, pts = [];
  16114. for ( d = 0; d <= divisions; d ++ ) {
  16115. pts.push( this.getPointAt( d / divisions ) );
  16116. }
  16117. return pts;
  16118. };
  16119. // Get total curve arc length
  16120. THREE.Curve.prototype.getLength = function () {
  16121. var lengths = this.getLengths();
  16122. return lengths[ lengths.length - 1 ];
  16123. };
  16124. // Get list of cumulative segment lengths
  16125. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16126. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16127. if ( this.cacheArcLengths
  16128. && ( this.cacheArcLengths.length == divisions + 1 )
  16129. && !this.needsUpdate) {
  16130. //console.log( "cached", this.cacheArcLengths );
  16131. return this.cacheArcLengths;
  16132. }
  16133. this.needsUpdate = false;
  16134. var cache = [];
  16135. var current, last = this.getPoint( 0 );
  16136. var p, sum = 0;
  16137. cache.push( 0 );
  16138. for ( p = 1; p <= divisions; p ++ ) {
  16139. current = this.getPoint ( p / divisions );
  16140. sum += current.distanceTo( last );
  16141. cache.push( sum );
  16142. last = current;
  16143. }
  16144. this.cacheArcLengths = cache;
  16145. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16146. };
  16147. THREE.Curve.prototype.updateArcLengths = function() {
  16148. this.needsUpdate = true;
  16149. this.getLengths();
  16150. };
  16151. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16152. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16153. var arcLengths = this.getLengths();
  16154. var i = 0, il = arcLengths.length;
  16155. var targetArcLength; // The targeted u distance value to get
  16156. if ( distance ) {
  16157. targetArcLength = distance;
  16158. } else {
  16159. targetArcLength = u * arcLengths[ il - 1 ];
  16160. }
  16161. //var time = Date.now();
  16162. // binary search for the index with largest value smaller than target u distance
  16163. var low = 0, high = il - 1, comparison;
  16164. while ( low <= high ) {
  16165. 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
  16166. comparison = arcLengths[ i ] - targetArcLength;
  16167. if ( comparison < 0 ) {
  16168. low = i + 1;
  16169. continue;
  16170. } else if ( comparison > 0 ) {
  16171. high = i - 1;
  16172. continue;
  16173. } else {
  16174. high = i;
  16175. break;
  16176. // DONE
  16177. }
  16178. }
  16179. i = high;
  16180. //console.log('b' , i, low, high, Date.now()- time);
  16181. if ( arcLengths[ i ] == targetArcLength ) {
  16182. var t = i / ( il - 1 );
  16183. return t;
  16184. }
  16185. // we could get finer grain at lengths, or use simple interpolatation between two points
  16186. var lengthBefore = arcLengths[ i ];
  16187. var lengthAfter = arcLengths[ i + 1 ];
  16188. var segmentLength = lengthAfter - lengthBefore;
  16189. // determine where we are between the 'before' and 'after' points
  16190. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16191. // add that fractional amount to t
  16192. var t = ( i + segmentFraction ) / ( il -1 );
  16193. return t;
  16194. };
  16195. // Returns a unit vector tangent at t
  16196. // In case any sub curve does not implement its tangent derivation,
  16197. // 2 points a small delta apart will be used to find its gradient
  16198. // which seems to give a reasonable approximation
  16199. THREE.Curve.prototype.getTangent = function( t ) {
  16200. var delta = 0.0001;
  16201. var t1 = t - delta;
  16202. var t2 = t + delta;
  16203. // Capping in case of danger
  16204. if ( t1 < 0 ) t1 = 0;
  16205. if ( t2 > 1 ) t2 = 1;
  16206. var pt1 = this.getPoint( t1 );
  16207. var pt2 = this.getPoint( t2 );
  16208. var vec = pt2.clone().sub(pt1);
  16209. return vec.normalize();
  16210. };
  16211. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16212. var t = this.getUtoTmapping( u );
  16213. return this.getTangent( t );
  16214. };
  16215. /**************************************************************
  16216. * Line
  16217. **************************************************************/
  16218. THREE.LineCurve = function ( v1, v2 ) {
  16219. this.v1 = v1;
  16220. this.v2 = v2;
  16221. };
  16222. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  16223. THREE.LineCurve.prototype.getPoint = function ( t ) {
  16224. var point = this.v2.clone().sub(this.v1);
  16225. point.multiplyScalar( t ).add( this.v1 );
  16226. return point;
  16227. };
  16228. // Line curve is linear, so we can overwrite default getPointAt
  16229. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  16230. return this.getPoint( u );
  16231. };
  16232. THREE.LineCurve.prototype.getTangent = function( t ) {
  16233. var tangent = this.v2.clone().sub(this.v1);
  16234. return tangent.normalize();
  16235. };
  16236. /**************************************************************
  16237. * Quadratic Bezier curve
  16238. **************************************************************/
  16239. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  16240. this.v0 = v0;
  16241. this.v1 = v1;
  16242. this.v2 = v2;
  16243. };
  16244. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  16245. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  16246. var tx, ty;
  16247. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  16248. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  16249. return new THREE.Vector2( tx, ty );
  16250. };
  16251. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  16252. var tx, ty;
  16253. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  16254. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  16255. // returns unit vector
  16256. var tangent = new THREE.Vector2( tx, ty );
  16257. tangent.normalize();
  16258. return tangent;
  16259. };
  16260. /**************************************************************
  16261. * Cubic Bezier curve
  16262. **************************************************************/
  16263. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  16264. this.v0 = v0;
  16265. this.v1 = v1;
  16266. this.v2 = v2;
  16267. this.v3 = v3;
  16268. };
  16269. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  16270. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  16271. var tx, ty;
  16272. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16273. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16274. return new THREE.Vector2( tx, ty );
  16275. };
  16276. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  16277. var tx, ty;
  16278. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16279. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16280. var tangent = new THREE.Vector2( tx, ty );
  16281. tangent.normalize();
  16282. return tangent;
  16283. };
  16284. /**************************************************************
  16285. * Spline curve
  16286. **************************************************************/
  16287. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  16288. this.points = (points == undefined) ? [] : points;
  16289. };
  16290. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  16291. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  16292. var v = new THREE.Vector2();
  16293. var c = [];
  16294. var points = this.points, point, intPoint, weight;
  16295. point = ( points.length - 1 ) * t;
  16296. intPoint = Math.floor( point );
  16297. weight = point - intPoint;
  16298. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16299. c[ 1 ] = intPoint;
  16300. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  16301. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  16302. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16303. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16304. return v;
  16305. };
  16306. /**************************************************************
  16307. * Ellipse curve
  16308. **************************************************************/
  16309. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  16310. aStartAngle, aEndAngle,
  16311. aClockwise ) {
  16312. this.aX = aX;
  16313. this.aY = aY;
  16314. this.xRadius = xRadius;
  16315. this.yRadius = yRadius;
  16316. this.aStartAngle = aStartAngle;
  16317. this.aEndAngle = aEndAngle;
  16318. this.aClockwise = aClockwise;
  16319. };
  16320. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  16321. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  16322. var deltaAngle = this.aEndAngle - this.aStartAngle;
  16323. if ( !this.aClockwise ) {
  16324. t = 1 - t;
  16325. }
  16326. var angle = this.aStartAngle + t * deltaAngle;
  16327. var tx = this.aX + this.xRadius * Math.cos( angle );
  16328. var ty = this.aY + this.yRadius * Math.sin( angle );
  16329. return new THREE.Vector2( tx, ty );
  16330. };
  16331. /**************************************************************
  16332. * Arc curve
  16333. **************************************************************/
  16334. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  16335. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  16336. };
  16337. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  16338. /**************************************************************
  16339. * Utils
  16340. **************************************************************/
  16341. THREE.Curve.Utils = {
  16342. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16343. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16344. },
  16345. // Puay Bing, thanks for helping with this derivative!
  16346. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16347. return -3 * p0 * (1 - t) * (1 - t) +
  16348. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  16349. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  16350. 3 * t * t * p3;
  16351. },
  16352. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16353. // To check if my formulas are correct
  16354. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16355. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16356. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  16357. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16358. return h00 + h10 + h01 + h11;
  16359. },
  16360. // Catmull-Rom
  16361. interpolate: function( p0, p1, p2, p3, t ) {
  16362. var v0 = ( p2 - p0 ) * 0.5;
  16363. var v1 = ( p3 - p1 ) * 0.5;
  16364. var t2 = t * t;
  16365. var t3 = t * t2;
  16366. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16367. }
  16368. };
  16369. // TODO: Transformation for Curves?
  16370. /**************************************************************
  16371. * 3D Curves
  16372. **************************************************************/
  16373. // A Factory method for creating new curve subclasses
  16374. THREE.Curve.create = function ( constructor, getPointFunc ) {
  16375. constructor.prototype = Object.create( THREE.Curve.prototype );
  16376. constructor.prototype.getPoint = getPointFunc;
  16377. return constructor;
  16378. };
  16379. /**************************************************************
  16380. * Line3D
  16381. **************************************************************/
  16382. THREE.LineCurve3 = THREE.Curve.create(
  16383. function ( v1, v2 ) {
  16384. this.v1 = v1;
  16385. this.v2 = v2;
  16386. },
  16387. function ( t ) {
  16388. var r = new THREE.Vector3();
  16389. r.subVectors( this.v2, this.v1 ); // diff
  16390. r.multiplyScalar( t );
  16391. r.add( this.v1 );
  16392. return r;
  16393. }
  16394. );
  16395. /**************************************************************
  16396. * Quadratic Bezier 3D curve
  16397. **************************************************************/
  16398. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  16399. function ( v0, v1, v2 ) {
  16400. this.v0 = v0;
  16401. this.v1 = v1;
  16402. this.v2 = v2;
  16403. },
  16404. function ( t ) {
  16405. var tx, ty, tz;
  16406. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  16407. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  16408. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  16409. return new THREE.Vector3( tx, ty, tz );
  16410. }
  16411. );
  16412. /**************************************************************
  16413. * Cubic Bezier 3D curve
  16414. **************************************************************/
  16415. THREE.CubicBezierCurve3 = THREE.Curve.create(
  16416. function ( v0, v1, v2, v3 ) {
  16417. this.v0 = v0;
  16418. this.v1 = v1;
  16419. this.v2 = v2;
  16420. this.v3 = v3;
  16421. },
  16422. function ( t ) {
  16423. var tx, ty, tz;
  16424. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16425. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16426. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  16427. return new THREE.Vector3( tx, ty, tz );
  16428. }
  16429. );
  16430. /**************************************************************
  16431. * Spline 3D curve
  16432. **************************************************************/
  16433. THREE.SplineCurve3 = THREE.Curve.create(
  16434. function ( points /* array of Vector3 */) {
  16435. this.points = (points == undefined) ? [] : points;
  16436. },
  16437. function ( t ) {
  16438. var v = new THREE.Vector3();
  16439. var c = [];
  16440. var points = this.points, point, intPoint, weight;
  16441. point = ( points.length - 1 ) * t;
  16442. intPoint = Math.floor( point );
  16443. weight = point - intPoint;
  16444. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16445. c[ 1 ] = intPoint;
  16446. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16447. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16448. var pt0 = points[ c[0] ],
  16449. pt1 = points[ c[1] ],
  16450. pt2 = points[ c[2] ],
  16451. pt3 = points[ c[3] ];
  16452. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  16453. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  16454. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  16455. return v;
  16456. }
  16457. );
  16458. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  16459. // var v = new THREE.Vector3();
  16460. // var c = [];
  16461. // var points = this.points, point, intPoint, weight;
  16462. // point = ( points.length - 1 ) * t;
  16463. // intPoint = Math.floor( point );
  16464. // weight = point - intPoint;
  16465. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16466. // c[ 1 ] = intPoint;
  16467. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16468. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16469. // var pt0 = points[ c[0] ],
  16470. // pt1 = points[ c[1] ],
  16471. // pt2 = points[ c[2] ],
  16472. // pt3 = points[ c[3] ];
  16473. // // t = weight;
  16474. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  16475. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  16476. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  16477. // return v;
  16478. // }
  16479. /**************************************************************
  16480. * Closed Spline 3D curve
  16481. **************************************************************/
  16482. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  16483. function ( points /* array of Vector3 */) {
  16484. this.points = (points == undefined) ? [] : points;
  16485. },
  16486. function ( t ) {
  16487. var v = new THREE.Vector3();
  16488. var c = [];
  16489. var points = this.points, point, intPoint, weight;
  16490. point = ( points.length - 0 ) * t;
  16491. // This needs to be from 0-length +1
  16492. intPoint = Math.floor( point );
  16493. weight = point - intPoint;
  16494. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  16495. c[ 0 ] = ( intPoint - 1 ) % points.length;
  16496. c[ 1 ] = ( intPoint ) % points.length;
  16497. c[ 2 ] = ( intPoint + 1 ) % points.length;
  16498. c[ 3 ] = ( intPoint + 2 ) % points.length;
  16499. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16500. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16501. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  16502. return v;
  16503. }
  16504. );
  16505. /**
  16506. * @author zz85 / http://www.lab4games.net/zz85/blog
  16507. *
  16508. **/
  16509. /**************************************************************
  16510. * Curved Path - a curve path is simply a array of connected
  16511. * curves, but retains the api of a curve
  16512. **************************************************************/
  16513. THREE.CurvePath = function () {
  16514. this.curves = [];
  16515. this.bends = [];
  16516. this.autoClose = false; // Automatically closes the path
  16517. };
  16518. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16519. THREE.CurvePath.prototype.add = function ( curve ) {
  16520. this.curves.push( curve );
  16521. };
  16522. THREE.CurvePath.prototype.checkConnection = function() {
  16523. // TODO
  16524. // If the ending of curve is not connected to the starting
  16525. // or the next curve, then, this is not a real path
  16526. };
  16527. THREE.CurvePath.prototype.closePath = function() {
  16528. // TODO Test
  16529. // and verify for vector3 (needs to implement equals)
  16530. // Add a line curve if start and end of lines are not connected
  16531. var startPoint = this.curves[0].getPoint(0);
  16532. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  16533. if (!startPoint.equals(endPoint)) {
  16534. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16535. }
  16536. };
  16537. // To get accurate point with reference to
  16538. // entire path distance at time t,
  16539. // following has to be done:
  16540. // 1. Length of each sub path have to be known
  16541. // 2. Locate and identify type of curve
  16542. // 3. Get t for the curve
  16543. // 4. Return curve.getPointAt(t')
  16544. THREE.CurvePath.prototype.getPoint = function( t ) {
  16545. var d = t * this.getLength();
  16546. var curveLengths = this.getCurveLengths();
  16547. var i = 0, diff, curve;
  16548. // To think about boundaries points.
  16549. while ( i < curveLengths.length ) {
  16550. if ( curveLengths[ i ] >= d ) {
  16551. diff = curveLengths[ i ] - d;
  16552. curve = this.curves[ i ];
  16553. var u = 1 - diff / curve.getLength();
  16554. return curve.getPointAt( u );
  16555. break;
  16556. }
  16557. i ++;
  16558. }
  16559. return null;
  16560. // loop where sum != 0, sum > d , sum+1 <d
  16561. };
  16562. /*
  16563. THREE.CurvePath.prototype.getTangent = function( t ) {
  16564. };*/
  16565. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16566. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16567. // getPoint() depends on getLength
  16568. THREE.CurvePath.prototype.getLength = function() {
  16569. var lens = this.getCurveLengths();
  16570. return lens[ lens.length - 1 ];
  16571. };
  16572. // Compute lengths and cache them
  16573. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16574. THREE.CurvePath.prototype.getCurveLengths = function() {
  16575. // We use cache values if curves and cache array are same length
  16576. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16577. return this.cacheLengths;
  16578. };
  16579. // Get length of subsurve
  16580. // Push sums into cached array
  16581. var lengths = [], sums = 0;
  16582. var i, il = this.curves.length;
  16583. for ( i = 0; i < il; i ++ ) {
  16584. sums += this.curves[ i ].getLength();
  16585. lengths.push( sums );
  16586. }
  16587. this.cacheLengths = lengths;
  16588. return lengths;
  16589. };
  16590. // Returns min and max coordinates, as well as centroid
  16591. THREE.CurvePath.prototype.getBoundingBox = function () {
  16592. var points = this.getPoints();
  16593. var maxX, maxY, maxZ;
  16594. var minX, minY, minZ;
  16595. maxX = maxY = Number.NEGATIVE_INFINITY;
  16596. minX = minY = Number.POSITIVE_INFINITY;
  16597. var p, i, il, sum;
  16598. var v3 = points[0] instanceof THREE.Vector3;
  16599. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16600. for ( i = 0, il = points.length; i < il; i ++ ) {
  16601. p = points[ i ];
  16602. if ( p.x > maxX ) maxX = p.x;
  16603. else if ( p.x < minX ) minX = p.x;
  16604. if ( p.y > maxY ) maxY = p.y;
  16605. else if ( p.y < minY ) minY = p.y;
  16606. if ( v3 ) {
  16607. if ( p.z > maxZ ) maxZ = p.z;
  16608. else if ( p.z < minZ ) minZ = p.z;
  16609. }
  16610. sum.add( p );
  16611. }
  16612. var ret = {
  16613. minX: minX,
  16614. minY: minY,
  16615. maxX: maxX,
  16616. maxY: maxY,
  16617. centroid: sum.divideScalar( il )
  16618. };
  16619. if ( v3 ) {
  16620. ret.maxZ = maxZ;
  16621. ret.minZ = minZ;
  16622. }
  16623. return ret;
  16624. };
  16625. /**************************************************************
  16626. * Create Geometries Helpers
  16627. **************************************************************/
  16628. /// Generate geometry from path points (for Line or ParticleSystem objects)
  16629. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16630. var pts = this.getPoints( divisions, true );
  16631. return this.createGeometry( pts );
  16632. };
  16633. // Generate geometry from equidistance sampling along the path
  16634. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16635. var pts = this.getSpacedPoints( divisions, true );
  16636. return this.createGeometry( pts );
  16637. };
  16638. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16639. var geometry = new THREE.Geometry();
  16640. for ( var i = 0; i < points.length; i ++ ) {
  16641. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16642. }
  16643. return geometry;
  16644. };
  16645. /**************************************************************
  16646. * Bend / Wrap Helper Methods
  16647. **************************************************************/
  16648. // Wrap path / Bend modifiers?
  16649. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16650. this.bends.push( bendpath );
  16651. };
  16652. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  16653. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  16654. var i, il;
  16655. if ( !bends ) {
  16656. bends = this.bends;
  16657. }
  16658. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16659. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16660. }
  16661. return oldPts;
  16662. };
  16663. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  16664. var oldPts = this.getSpacedPoints( segments );
  16665. var i, il;
  16666. if ( !bends ) {
  16667. bends = this.bends;
  16668. }
  16669. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16670. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16671. }
  16672. return oldPts;
  16673. };
  16674. // This returns getPoints() bend/wrapped around the contour of a path.
  16675. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  16676. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  16677. var bounds = this.getBoundingBox();
  16678. var i, il, p, oldX, oldY, xNorm;
  16679. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  16680. p = oldPts[ i ];
  16681. oldX = p.x;
  16682. oldY = p.y;
  16683. xNorm = oldX / bounds.maxX;
  16684. // If using actual distance, for length > path, requires line extrusions
  16685. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  16686. xNorm = path.getUtoTmapping( xNorm, oldX );
  16687. // check for out of bounds?
  16688. var pathPt = path.getPoint( xNorm );
  16689. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  16690. p.x = pathPt.x + normal.x;
  16691. p.y = pathPt.y + normal.y;
  16692. }
  16693. return oldPts;
  16694. };
  16695. /**
  16696. * @author alteredq / http://alteredqualia.com/
  16697. */
  16698. THREE.Gyroscope = function () {
  16699. THREE.Object3D.call( this );
  16700. };
  16701. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  16702. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  16703. this.matrixAutoUpdate && this.updateMatrix();
  16704. // update matrixWorld
  16705. if ( this.matrixWorldNeedsUpdate || force ) {
  16706. if ( this.parent ) {
  16707. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  16708. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  16709. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  16710. this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
  16711. } else {
  16712. this.matrixWorld.copy( this.matrix );
  16713. }
  16714. this.matrixWorldNeedsUpdate = false;
  16715. force = true;
  16716. }
  16717. // update children
  16718. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  16719. this.children[ i ].updateMatrixWorld( force );
  16720. }
  16721. };
  16722. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  16723. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  16724. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  16725. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  16726. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  16727. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  16728. /**
  16729. * @author zz85 / http://www.lab4games.net/zz85/blog
  16730. * Creates free form 2d path using series of points, lines or curves.
  16731. *
  16732. **/
  16733. THREE.Path = function ( points ) {
  16734. THREE.CurvePath.call(this);
  16735. this.actions = [];
  16736. if ( points ) {
  16737. this.fromPoints( points );
  16738. }
  16739. };
  16740. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16741. THREE.PathActions = {
  16742. MOVE_TO: 'moveTo',
  16743. LINE_TO: 'lineTo',
  16744. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  16745. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  16746. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  16747. ARC: 'arc', // Circle
  16748. ELLIPSE: 'ellipse'
  16749. };
  16750. // TODO Clean up PATH API
  16751. // Create path using straight lines to connect all points
  16752. // - vectors: array of Vector2
  16753. THREE.Path.prototype.fromPoints = function ( vectors ) {
  16754. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  16755. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  16756. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  16757. };
  16758. };
  16759. // startPath() endPath()?
  16760. THREE.Path.prototype.moveTo = function ( x, y ) {
  16761. var args = Array.prototype.slice.call( arguments );
  16762. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  16763. };
  16764. THREE.Path.prototype.lineTo = function ( x, y ) {
  16765. var args = Array.prototype.slice.call( arguments );
  16766. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16767. var x0 = lastargs[ lastargs.length - 2 ];
  16768. var y0 = lastargs[ lastargs.length - 1 ];
  16769. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  16770. this.curves.push( curve );
  16771. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  16772. };
  16773. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  16774. var args = Array.prototype.slice.call( arguments );
  16775. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16776. var x0 = lastargs[ lastargs.length - 2 ];
  16777. var y0 = lastargs[ lastargs.length - 1 ];
  16778. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  16779. new THREE.Vector2( aCPx, aCPy ),
  16780. new THREE.Vector2( aX, aY ) );
  16781. this.curves.push( curve );
  16782. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  16783. };
  16784. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  16785. aCP2x, aCP2y,
  16786. aX, aY ) {
  16787. var args = Array.prototype.slice.call( arguments );
  16788. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16789. var x0 = lastargs[ lastargs.length - 2 ];
  16790. var y0 = lastargs[ lastargs.length - 1 ];
  16791. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  16792. new THREE.Vector2( aCP1x, aCP1y ),
  16793. new THREE.Vector2( aCP2x, aCP2y ),
  16794. new THREE.Vector2( aX, aY ) );
  16795. this.curves.push( curve );
  16796. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  16797. };
  16798. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  16799. var args = Array.prototype.slice.call( arguments );
  16800. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16801. var x0 = lastargs[ lastargs.length - 2 ];
  16802. var y0 = lastargs[ lastargs.length - 1 ];
  16803. //---
  16804. var npts = [ new THREE.Vector2( x0, y0 ) ];
  16805. Array.prototype.push.apply( npts, pts );
  16806. var curve = new THREE.SplineCurve( npts );
  16807. this.curves.push( curve );
  16808. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  16809. };
  16810. // FUTURE: Change the API or follow canvas API?
  16811. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  16812. aStartAngle, aEndAngle, aClockwise ) {
  16813. var lastargs = this.actions[ this.actions.length - 1].args;
  16814. var x0 = lastargs[ lastargs.length - 2 ];
  16815. var y0 = lastargs[ lastargs.length - 1 ];
  16816. this.absarc(aX + x0, aY + y0, aRadius,
  16817. aStartAngle, aEndAngle, aClockwise );
  16818. };
  16819. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  16820. aStartAngle, aEndAngle, aClockwise ) {
  16821. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  16822. };
  16823. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  16824. aStartAngle, aEndAngle, aClockwise ) {
  16825. var lastargs = this.actions[ this.actions.length - 1].args;
  16826. var x0 = lastargs[ lastargs.length - 2 ];
  16827. var y0 = lastargs[ lastargs.length - 1 ];
  16828. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  16829. aStartAngle, aEndAngle, aClockwise );
  16830. };
  16831. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  16832. aStartAngle, aEndAngle, aClockwise ) {
  16833. var args = Array.prototype.slice.call( arguments );
  16834. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  16835. aStartAngle, aEndAngle, aClockwise );
  16836. this.curves.push( curve );
  16837. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  16838. args.push(lastPoint.x);
  16839. args.push(lastPoint.y);
  16840. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  16841. };
  16842. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  16843. if ( ! divisions ) divisions = 40;
  16844. var points = [];
  16845. for ( var i = 0; i < divisions; i ++ ) {
  16846. points.push( this.getPoint( i / divisions ) );
  16847. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  16848. }
  16849. // if ( closedPath ) {
  16850. //
  16851. // points.push( points[ 0 ] );
  16852. //
  16853. // }
  16854. return points;
  16855. };
  16856. /* Return an array of vectors based on contour of the path */
  16857. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  16858. if (this.useSpacedPoints) {
  16859. console.log('tata');
  16860. return this.getSpacedPoints( divisions, closedPath );
  16861. }
  16862. divisions = divisions || 12;
  16863. var points = [];
  16864. var i, il, item, action, args;
  16865. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  16866. laste, j,
  16867. t, tx, ty;
  16868. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16869. item = this.actions[ i ];
  16870. action = item.action;
  16871. args = item.args;
  16872. switch( action ) {
  16873. case THREE.PathActions.MOVE_TO:
  16874. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16875. break;
  16876. case THREE.PathActions.LINE_TO:
  16877. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16878. break;
  16879. case THREE.PathActions.QUADRATIC_CURVE_TO:
  16880. cpx = args[ 2 ];
  16881. cpy = args[ 3 ];
  16882. cpx1 = args[ 0 ];
  16883. cpy1 = args[ 1 ];
  16884. if ( points.length > 0 ) {
  16885. laste = points[ points.length - 1 ];
  16886. cpx0 = laste.x;
  16887. cpy0 = laste.y;
  16888. } else {
  16889. laste = this.actions[ i - 1 ].args;
  16890. cpx0 = laste[ laste.length - 2 ];
  16891. cpy0 = laste[ laste.length - 1 ];
  16892. }
  16893. for ( j = 1; j <= divisions; j ++ ) {
  16894. t = j / divisions;
  16895. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16896. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16897. points.push( new THREE.Vector2( tx, ty ) );
  16898. }
  16899. break;
  16900. case THREE.PathActions.BEZIER_CURVE_TO:
  16901. cpx = args[ 4 ];
  16902. cpy = args[ 5 ];
  16903. cpx1 = args[ 0 ];
  16904. cpy1 = args[ 1 ];
  16905. cpx2 = args[ 2 ];
  16906. cpy2 = args[ 3 ];
  16907. if ( points.length > 0 ) {
  16908. laste = points[ points.length - 1 ];
  16909. cpx0 = laste.x;
  16910. cpy0 = laste.y;
  16911. } else {
  16912. laste = this.actions[ i - 1 ].args;
  16913. cpx0 = laste[ laste.length - 2 ];
  16914. cpy0 = laste[ laste.length - 1 ];
  16915. }
  16916. for ( j = 1; j <= divisions; j ++ ) {
  16917. t = j / divisions;
  16918. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16919. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16920. points.push( new THREE.Vector2( tx, ty ) );
  16921. }
  16922. break;
  16923. case THREE.PathActions.CSPLINE_THRU:
  16924. laste = this.actions[ i - 1 ].args;
  16925. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  16926. var spts = [ last ];
  16927. var n = divisions * args[ 0 ].length;
  16928. spts = spts.concat( args[ 0 ] );
  16929. var spline = new THREE.SplineCurve( spts );
  16930. for ( j = 1; j <= n; j ++ ) {
  16931. points.push( spline.getPointAt( j / n ) ) ;
  16932. }
  16933. break;
  16934. case THREE.PathActions.ARC:
  16935. var aX = args[ 0 ], aY = args[ 1 ],
  16936. aRadius = args[ 2 ],
  16937. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  16938. aClockwise = !!args[ 5 ];
  16939. var deltaAngle = aEndAngle - aStartAngle;
  16940. var angle;
  16941. var tdivisions = divisions * 2;
  16942. for ( j = 1; j <= tdivisions; j ++ ) {
  16943. t = j / tdivisions;
  16944. if ( ! aClockwise ) {
  16945. t = 1 - t;
  16946. }
  16947. angle = aStartAngle + t * deltaAngle;
  16948. tx = aX + aRadius * Math.cos( angle );
  16949. ty = aY + aRadius * Math.sin( angle );
  16950. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16951. points.push( new THREE.Vector2( tx, ty ) );
  16952. }
  16953. //console.log(points);
  16954. break;
  16955. case THREE.PathActions.ELLIPSE:
  16956. var aX = args[ 0 ], aY = args[ 1 ],
  16957. xRadius = args[ 2 ],
  16958. yRadius = args[ 3 ],
  16959. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  16960. aClockwise = !!args[ 6 ];
  16961. var deltaAngle = aEndAngle - aStartAngle;
  16962. var angle;
  16963. var tdivisions = divisions * 2;
  16964. for ( j = 1; j <= tdivisions; j ++ ) {
  16965. t = j / tdivisions;
  16966. if ( ! aClockwise ) {
  16967. t = 1 - t;
  16968. }
  16969. angle = aStartAngle + t * deltaAngle;
  16970. tx = aX + xRadius * Math.cos( angle );
  16971. ty = aY + yRadius * Math.sin( angle );
  16972. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16973. points.push( new THREE.Vector2( tx, ty ) );
  16974. }
  16975. //console.log(points);
  16976. break;
  16977. } // end switch
  16978. }
  16979. // Normalize to remove the closing point by default.
  16980. var lastPoint = points[ points.length - 1];
  16981. var EPSILON = 0.0000000001;
  16982. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  16983. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  16984. points.splice( points.length - 1, 1);
  16985. if ( closedPath ) {
  16986. points.push( points[ 0 ] );
  16987. }
  16988. return points;
  16989. };
  16990. // Breaks path into shapes
  16991. THREE.Path.prototype.toShapes = function() {
  16992. var i, il, item, action, args;
  16993. var subPaths = [], lastPath = new THREE.Path();
  16994. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16995. item = this.actions[ i ];
  16996. args = item.args;
  16997. action = item.action;
  16998. if ( action == THREE.PathActions.MOVE_TO ) {
  16999. if ( lastPath.actions.length != 0 ) {
  17000. subPaths.push( lastPath );
  17001. lastPath = new THREE.Path();
  17002. }
  17003. }
  17004. lastPath[ action ].apply( lastPath, args );
  17005. }
  17006. if ( lastPath.actions.length != 0 ) {
  17007. subPaths.push( lastPath );
  17008. }
  17009. // console.log(subPaths);
  17010. if ( subPaths.length == 0 ) return [];
  17011. var tmpPath, tmpShape, shapes = [];
  17012. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17013. // console.log("Holes first", holesFirst);
  17014. if ( subPaths.length == 1) {
  17015. tmpPath = subPaths[0];
  17016. tmpShape = new THREE.Shape();
  17017. tmpShape.actions = tmpPath.actions;
  17018. tmpShape.curves = tmpPath.curves;
  17019. shapes.push( tmpShape );
  17020. return shapes;
  17021. };
  17022. if ( holesFirst ) {
  17023. tmpShape = new THREE.Shape();
  17024. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17025. tmpPath = subPaths[ i ];
  17026. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17027. tmpShape.actions = tmpPath.actions;
  17028. tmpShape.curves = tmpPath.curves;
  17029. shapes.push( tmpShape );
  17030. tmpShape = new THREE.Shape();
  17031. //console.log('cw', i);
  17032. } else {
  17033. tmpShape.holes.push( tmpPath );
  17034. //console.log('ccw', i);
  17035. }
  17036. }
  17037. } else {
  17038. // Shapes first
  17039. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17040. tmpPath = subPaths[ i ];
  17041. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17042. if ( tmpShape ) shapes.push( tmpShape );
  17043. tmpShape = new THREE.Shape();
  17044. tmpShape.actions = tmpPath.actions;
  17045. tmpShape.curves = tmpPath.curves;
  17046. } else {
  17047. tmpShape.holes.push( tmpPath );
  17048. }
  17049. }
  17050. shapes.push( tmpShape );
  17051. }
  17052. //console.log("shape", shapes);
  17053. return shapes;
  17054. };
  17055. /**
  17056. * @author zz85 / http://www.lab4games.net/zz85/blog
  17057. * Defines a 2d shape plane using paths.
  17058. **/
  17059. // STEP 1 Create a path.
  17060. // STEP 2 Turn path into shape.
  17061. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17062. // STEP 3a - Extract points from each shape, turn to vertices
  17063. // STEP 3b - Triangulate each shape, add faces.
  17064. THREE.Shape = function ( ) {
  17065. THREE.Path.apply( this, arguments );
  17066. this.holes = [];
  17067. };
  17068. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17069. // Convenience method to return ExtrudeGeometry
  17070. THREE.Shape.prototype.extrude = function ( options ) {
  17071. var extruded = new THREE.ExtrudeGeometry( this, options );
  17072. return extruded;
  17073. };
  17074. // Convenience method to return ShapeGeometry
  17075. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17076. var geometry = new THREE.ShapeGeometry( this, options );
  17077. return geometry;
  17078. };
  17079. // Get points of holes
  17080. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17081. var i, il = this.holes.length, holesPts = [];
  17082. for ( i = 0; i < il; i ++ ) {
  17083. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17084. }
  17085. return holesPts;
  17086. };
  17087. // Get points of holes (spaced by regular distance)
  17088. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17089. var i, il = this.holes.length, holesPts = [];
  17090. for ( i = 0; i < il; i ++ ) {
  17091. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17092. }
  17093. return holesPts;
  17094. };
  17095. // Get points of shape and holes (keypoints based on segments parameter)
  17096. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17097. return {
  17098. shape: this.getTransformedPoints( divisions ),
  17099. holes: this.getPointsHoles( divisions )
  17100. };
  17101. };
  17102. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17103. if (this.useSpacedPoints) {
  17104. return this.extractAllSpacedPoints(divisions);
  17105. }
  17106. return this.extractAllPoints(divisions);
  17107. };
  17108. //
  17109. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17110. //
  17111. // return {
  17112. //
  17113. // shape: this.transform( bend, divisions ),
  17114. // holes: this.getPointsHoles( divisions, bend )
  17115. //
  17116. // };
  17117. //
  17118. // };
  17119. // Get points of shape and holes (spaced by regular distance)
  17120. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17121. return {
  17122. shape: this.getTransformedSpacedPoints( divisions ),
  17123. holes: this.getSpacedPointsHoles( divisions )
  17124. };
  17125. };
  17126. /**************************************************************
  17127. * Utils
  17128. **************************************************************/
  17129. THREE.Shape.Utils = {
  17130. /*
  17131. contour - array of vector2 for contour
  17132. holes - array of array of vector2
  17133. */
  17134. removeHoles: function ( contour, holes ) {
  17135. var shape = contour.concat(); // work on this shape
  17136. var allpoints = shape.concat();
  17137. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  17138. var prevShapeVert, nextShapeVert,
  17139. prevHoleVert, nextHoleVert,
  17140. holeIndex, shapeIndex,
  17141. shapeId, shapeGroup,
  17142. h, h2,
  17143. hole, shortest, d,
  17144. p, pts1, pts2,
  17145. tmpShape1, tmpShape2,
  17146. tmpHole1, tmpHole2,
  17147. verts = [];
  17148. for ( h = 0; h < holes.length; h ++ ) {
  17149. hole = holes[ h ];
  17150. /*
  17151. shapeholes[ h ].concat(); // preserves original
  17152. holes.push( hole );
  17153. */
  17154. Array.prototype.push.apply( allpoints, hole );
  17155. shortest = Number.POSITIVE_INFINITY;
  17156. // Find the shortest pair of pts between shape and hole
  17157. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  17158. // Using distanceToSquared() intead of distanceTo() should speed a little
  17159. // since running square roots operations are reduced.
  17160. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  17161. pts1 = hole[ h2 ];
  17162. var dist = [];
  17163. for ( p = 0; p < shape.length; p++ ) {
  17164. pts2 = shape[ p ];
  17165. d = pts1.distanceToSquared( pts2 );
  17166. dist.push( d );
  17167. if ( d < shortest ) {
  17168. shortest = d;
  17169. holeIndex = h2;
  17170. shapeIndex = p;
  17171. }
  17172. }
  17173. }
  17174. //console.log("shortest", shortest, dist);
  17175. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17176. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17177. var areaapts = [
  17178. hole[ holeIndex ],
  17179. shape[ shapeIndex ],
  17180. shape[ prevShapeVert ]
  17181. ];
  17182. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  17183. var areabpts = [
  17184. hole[ holeIndex ],
  17185. hole[ prevHoleVert ],
  17186. shape[ shapeIndex ]
  17187. ];
  17188. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  17189. var shapeOffset = 1;
  17190. var holeOffset = -1;
  17191. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  17192. shapeIndex += shapeOffset;
  17193. holeIndex += holeOffset;
  17194. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17195. shapeIndex %= shape.length;
  17196. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17197. holeIndex %= hole.length;
  17198. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17199. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17200. areaapts = [
  17201. hole[ holeIndex ],
  17202. shape[ shapeIndex ],
  17203. shape[ prevShapeVert ]
  17204. ];
  17205. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  17206. areabpts = [
  17207. hole[ holeIndex ],
  17208. hole[ prevHoleVert ],
  17209. shape[ shapeIndex ]
  17210. ];
  17211. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  17212. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  17213. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  17214. // In case areas are not correct.
  17215. //console.log("USE THIS");
  17216. shapeIndex = oldShapeIndex;
  17217. holeIndex = oldHoleIndex ;
  17218. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17219. shapeIndex %= shape.length;
  17220. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17221. holeIndex %= hole.length;
  17222. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17223. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17224. } else {
  17225. //console.log("USE THAT ")
  17226. }
  17227. tmpShape1 = shape.slice( 0, shapeIndex );
  17228. tmpShape2 = shape.slice( shapeIndex );
  17229. tmpHole1 = hole.slice( holeIndex );
  17230. tmpHole2 = hole.slice( 0, holeIndex );
  17231. // Should check orders here again?
  17232. var trianglea = [
  17233. hole[ holeIndex ],
  17234. shape[ shapeIndex ],
  17235. shape[ prevShapeVert ]
  17236. ];
  17237. var triangleb = [
  17238. hole[ holeIndex ] ,
  17239. hole[ prevHoleVert ],
  17240. shape[ shapeIndex ]
  17241. ];
  17242. verts.push( trianglea );
  17243. verts.push( triangleb );
  17244. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17245. }
  17246. return {
  17247. shape:shape, /* shape with no holes */
  17248. isolatedPts: verts, /* isolated faces */
  17249. allpoints: allpoints
  17250. }
  17251. },
  17252. triangulateShape: function ( contour, holes ) {
  17253. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  17254. var shape = shapeWithoutHoles.shape,
  17255. allpoints = shapeWithoutHoles.allpoints,
  17256. isolatedPts = shapeWithoutHoles.isolatedPts;
  17257. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  17258. // 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.
  17259. //console.log( "triangles",triangles, triangles.length );
  17260. //console.log( "allpoints",allpoints, allpoints.length );
  17261. var i, il, f, face,
  17262. key, index,
  17263. allPointsMap = {},
  17264. isolatedPointsMap = {};
  17265. // prepare all points map
  17266. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17267. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17268. if ( allPointsMap[ key ] !== undefined ) {
  17269. console.log( "Duplicate point", key );
  17270. }
  17271. allPointsMap[ key ] = i;
  17272. }
  17273. // check all face vertices against all points map
  17274. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17275. face = triangles[ i ];
  17276. for ( f = 0; f < 3; f ++ ) {
  17277. key = face[ f ].x + ":" + face[ f ].y;
  17278. index = allPointsMap[ key ];
  17279. if ( index !== undefined ) {
  17280. face[ f ] = index;
  17281. }
  17282. }
  17283. }
  17284. // check isolated points vertices against all points map
  17285. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  17286. face = isolatedPts[ i ];
  17287. for ( f = 0; f < 3; f ++ ) {
  17288. key = face[ f ].x + ":" + face[ f ].y;
  17289. index = allPointsMap[ key ];
  17290. if ( index !== undefined ) {
  17291. face[ f ] = index;
  17292. }
  17293. }
  17294. }
  17295. return triangles.concat( isolatedPts );
  17296. }, // end triangulate shapes
  17297. /*
  17298. triangulate2 : function( pts, holes ) {
  17299. // For use with Poly2Tri.js
  17300. var allpts = pts.concat();
  17301. var shape = [];
  17302. for (var p in pts) {
  17303. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  17304. }
  17305. var swctx = new js.poly2tri.SweepContext(shape);
  17306. for (var h in holes) {
  17307. var aHole = holes[h];
  17308. var newHole = []
  17309. for (i in aHole) {
  17310. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  17311. allpts.push(aHole[i]);
  17312. }
  17313. swctx.AddHole(newHole);
  17314. }
  17315. var find;
  17316. var findIndexForPt = function (pt) {
  17317. find = new THREE.Vector2(pt.x, pt.y);
  17318. var p;
  17319. for (p=0, pl = allpts.length; p<pl; p++) {
  17320. if (allpts[p].equals(find)) return p;
  17321. }
  17322. return -1;
  17323. };
  17324. // triangulate
  17325. js.poly2tri.sweep.Triangulate(swctx);
  17326. var triangles = swctx.GetTriangles();
  17327. var tr ;
  17328. var facesPts = [];
  17329. for (var t in triangles) {
  17330. tr = triangles[t];
  17331. facesPts.push([
  17332. findIndexForPt(tr.GetPoint(0)),
  17333. findIndexForPt(tr.GetPoint(1)),
  17334. findIndexForPt(tr.GetPoint(2))
  17335. ]);
  17336. }
  17337. // console.log(facesPts);
  17338. // console.log("triangles", triangles.length, triangles);
  17339. // Returns array of faces with 3 element each
  17340. return facesPts;
  17341. },
  17342. */
  17343. isClockWise: function ( pts ) {
  17344. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17345. },
  17346. // Bezier Curves formulas obtained from
  17347. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17348. // Quad Bezier Functions
  17349. b2p0: function ( t, p ) {
  17350. var k = 1 - t;
  17351. return k * k * p;
  17352. },
  17353. b2p1: function ( t, p ) {
  17354. return 2 * ( 1 - t ) * t * p;
  17355. },
  17356. b2p2: function ( t, p ) {
  17357. return t * t * p;
  17358. },
  17359. b2: function ( t, p0, p1, p2 ) {
  17360. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17361. },
  17362. // Cubic Bezier Functions
  17363. b3p0: function ( t, p ) {
  17364. var k = 1 - t;
  17365. return k * k * k * p;
  17366. },
  17367. b3p1: function ( t, p ) {
  17368. var k = 1 - t;
  17369. return 3 * k * k * t * p;
  17370. },
  17371. b3p2: function ( t, p ) {
  17372. var k = 1 - t;
  17373. return 3 * k * t * t * p;
  17374. },
  17375. b3p3: function ( t, p ) {
  17376. return t * t * t * p;
  17377. },
  17378. b3: function ( t, p0, p1, p2, p3 ) {
  17379. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17380. }
  17381. };
  17382. /**
  17383. * @author mikael emtinger / http://gomo.se/
  17384. */
  17385. THREE.AnimationHandler = (function() {
  17386. var playing = [];
  17387. var library = {};
  17388. var that = {};
  17389. //--- update ---
  17390. that.update = function( deltaTimeMS ) {
  17391. for( var i = 0; i < playing.length; i ++ )
  17392. playing[ i ].update( deltaTimeMS );
  17393. };
  17394. //--- add ---
  17395. that.addToUpdate = function( animation ) {
  17396. if ( playing.indexOf( animation ) === -1 )
  17397. playing.push( animation );
  17398. };
  17399. //--- remove ---
  17400. that.removeFromUpdate = function( animation ) {
  17401. var index = playing.indexOf( animation );
  17402. if( index !== -1 )
  17403. playing.splice( index, 1 );
  17404. };
  17405. //--- add ---
  17406. that.add = function( data ) {
  17407. if ( library[ data.name ] !== undefined )
  17408. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  17409. library[ data.name ] = data;
  17410. initData( data );
  17411. };
  17412. //--- get ---
  17413. that.get = function( name ) {
  17414. if ( typeof name === "string" ) {
  17415. if ( library[ name ] ) {
  17416. return library[ name ];
  17417. } else {
  17418. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  17419. return null;
  17420. }
  17421. } else {
  17422. // todo: add simple tween library
  17423. }
  17424. };
  17425. //--- parse ---
  17426. that.parse = function( root ) {
  17427. // setup hierarchy
  17428. var hierarchy = [];
  17429. if ( root instanceof THREE.SkinnedMesh ) {
  17430. for( var b = 0; b < root.bones.length; b++ ) {
  17431. hierarchy.push( root.bones[ b ] );
  17432. }
  17433. } else {
  17434. parseRecurseHierarchy( root, hierarchy );
  17435. }
  17436. return hierarchy;
  17437. };
  17438. var parseRecurseHierarchy = function( root, hierarchy ) {
  17439. hierarchy.push( root );
  17440. for( var c = 0; c < root.children.length; c++ )
  17441. parseRecurseHierarchy( root.children[ c ], hierarchy );
  17442. }
  17443. //--- init data ---
  17444. var initData = function( data ) {
  17445. if( data.initialized === true )
  17446. return;
  17447. // loop through all keys
  17448. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  17449. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17450. // remove minus times
  17451. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  17452. data.hierarchy[ h ].keys[ k ].time = 0;
  17453. // create quaternions
  17454. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  17455. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  17456. var quat = data.hierarchy[ h ].keys[ k ].rot;
  17457. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  17458. }
  17459. }
  17460. // prepare morph target keys
  17461. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  17462. // get all used
  17463. var usedMorphTargets = {};
  17464. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17465. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17466. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  17467. usedMorphTargets[ morphTargetName ] = -1;
  17468. }
  17469. }
  17470. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  17471. // set all used on all frames
  17472. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17473. var influences = {};
  17474. for ( var morphTargetName in usedMorphTargets ) {
  17475. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17476. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  17477. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  17478. break;
  17479. }
  17480. }
  17481. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  17482. influences[ morphTargetName ] = 0;
  17483. }
  17484. }
  17485. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  17486. }
  17487. }
  17488. // remove all keys that are on the same time
  17489. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17490. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  17491. data.hierarchy[ h ].keys.splice( k, 1 );
  17492. k --;
  17493. }
  17494. }
  17495. // set index
  17496. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17497. data.hierarchy[ h ].keys[ k ].index = k;
  17498. }
  17499. }
  17500. // JIT
  17501. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  17502. data.JIT = {};
  17503. data.JIT.hierarchy = [];
  17504. for( var h = 0; h < data.hierarchy.length; h ++ )
  17505. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  17506. // done
  17507. data.initialized = true;
  17508. };
  17509. // interpolation types
  17510. that.LINEAR = 0;
  17511. that.CATMULLROM = 1;
  17512. that.CATMULLROM_FORWARD = 2;
  17513. return that;
  17514. }());
  17515. /**
  17516. * @author mikael emtinger / http://gomo.se/
  17517. * @author mrdoob / http://mrdoob.com/
  17518. * @author alteredq / http://alteredqualia.com/
  17519. */
  17520. THREE.Animation = function ( root, name, interpolationType ) {
  17521. this.root = root;
  17522. this.data = THREE.AnimationHandler.get( name );
  17523. this.hierarchy = THREE.AnimationHandler.parse( root );
  17524. this.currentTime = 0;
  17525. this.timeScale = 1;
  17526. this.isPlaying = false;
  17527. this.isPaused = true;
  17528. this.loop = true;
  17529. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  17530. this.points = [];
  17531. this.target = new THREE.Vector3();
  17532. };
  17533. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  17534. if ( this.isPlaying === false ) {
  17535. this.isPlaying = true;
  17536. this.loop = loop !== undefined ? loop : true;
  17537. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17538. // reset key cache
  17539. var h, hl = this.hierarchy.length,
  17540. object;
  17541. for ( h = 0; h < hl; h ++ ) {
  17542. object = this.hierarchy[ h ];
  17543. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17544. object.useQuaternion = true;
  17545. }
  17546. object.matrixAutoUpdate = true;
  17547. if ( object.animationCache === undefined ) {
  17548. object.animationCache = {};
  17549. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  17550. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  17551. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17552. }
  17553. var prevKey = object.animationCache.prevKey;
  17554. var nextKey = object.animationCache.nextKey;
  17555. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  17556. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  17557. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  17558. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  17559. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  17560. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  17561. }
  17562. this.update( 0 );
  17563. }
  17564. this.isPaused = false;
  17565. THREE.AnimationHandler.addToUpdate( this );
  17566. };
  17567. THREE.Animation.prototype.pause = function() {
  17568. if ( this.isPaused === true ) {
  17569. THREE.AnimationHandler.addToUpdate( this );
  17570. } else {
  17571. THREE.AnimationHandler.removeFromUpdate( this );
  17572. }
  17573. this.isPaused = !this.isPaused;
  17574. };
  17575. THREE.Animation.prototype.stop = function() {
  17576. this.isPlaying = false;
  17577. this.isPaused = false;
  17578. THREE.AnimationHandler.removeFromUpdate( this );
  17579. };
  17580. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  17581. // early out
  17582. if ( this.isPlaying === false ) return;
  17583. // vars
  17584. var types = [ "pos", "rot", "scl" ];
  17585. var type;
  17586. var scale;
  17587. var vector;
  17588. var prevXYZ, nextXYZ;
  17589. var prevKey, nextKey;
  17590. var object;
  17591. var animationCache;
  17592. var frame;
  17593. var JIThierarchy = this.data.JIT.hierarchy;
  17594. var currentTime, unloopedCurrentTime;
  17595. var currentPoint, forwardPoint, angle;
  17596. this.currentTime += deltaTimeMS * this.timeScale;
  17597. unloopedCurrentTime = this.currentTime;
  17598. currentTime = this.currentTime = this.currentTime % this.data.length;
  17599. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17600. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17601. object = this.hierarchy[ h ];
  17602. animationCache = object.animationCache;
  17603. // loop through pos/rot/scl
  17604. for ( var t = 0; t < 3; t ++ ) {
  17605. // get keys
  17606. type = types[ t ];
  17607. prevKey = animationCache.prevKey[ type ];
  17608. nextKey = animationCache.nextKey[ type ];
  17609. // switch keys?
  17610. if ( nextKey.time <= unloopedCurrentTime ) {
  17611. // did we loop?
  17612. if ( currentTime < unloopedCurrentTime ) {
  17613. if ( this.loop ) {
  17614. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  17615. nextKey = this.getNextKeyWith( type, h, 1 );
  17616. while( nextKey.time < currentTime ) {
  17617. prevKey = nextKey;
  17618. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17619. }
  17620. } else {
  17621. this.stop();
  17622. return;
  17623. }
  17624. } else {
  17625. do {
  17626. prevKey = nextKey;
  17627. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17628. } while( nextKey.time < currentTime )
  17629. }
  17630. animationCache.prevKey[ type ] = prevKey;
  17631. animationCache.nextKey[ type ] = nextKey;
  17632. }
  17633. object.matrixAutoUpdate = true;
  17634. object.matrixWorldNeedsUpdate = true;
  17635. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  17636. prevXYZ = prevKey[ type ];
  17637. nextXYZ = nextKey[ type ];
  17638. // check scale error
  17639. if ( scale < 0 || scale > 1 ) {
  17640. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  17641. scale = scale < 0 ? 0 : 1;
  17642. }
  17643. // interpolate
  17644. if ( type === "pos" ) {
  17645. vector = object.position;
  17646. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  17647. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17648. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17649. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17650. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17651. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17652. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  17653. this.points[ 1 ] = prevXYZ;
  17654. this.points[ 2 ] = nextXYZ;
  17655. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  17656. scale = scale * 0.33 + 0.33;
  17657. currentPoint = this.interpolateCatmullRom( this.points, scale );
  17658. vector.x = currentPoint[ 0 ];
  17659. vector.y = currentPoint[ 1 ];
  17660. vector.z = currentPoint[ 2 ];
  17661. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17662. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  17663. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  17664. this.target.sub( vector );
  17665. this.target.y = 0;
  17666. this.target.normalize();
  17667. angle = Math.atan2( this.target.x, this.target.z );
  17668. object.rotation.set( 0, angle, 0 );
  17669. }
  17670. }
  17671. } else if ( type === "rot" ) {
  17672. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  17673. } else if ( type === "scl" ) {
  17674. vector = object.scale;
  17675. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17676. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17677. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17678. }
  17679. }
  17680. }
  17681. };
  17682. // Catmull-Rom spline
  17683. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  17684. var c = [], v3 = [],
  17685. point, intPoint, weight, w2, w3,
  17686. pa, pb, pc, pd;
  17687. point = ( points.length - 1 ) * scale;
  17688. intPoint = Math.floor( point );
  17689. weight = point - intPoint;
  17690. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  17691. c[ 1 ] = intPoint;
  17692. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  17693. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  17694. pa = points[ c[ 0 ] ];
  17695. pb = points[ c[ 1 ] ];
  17696. pc = points[ c[ 2 ] ];
  17697. pd = points[ c[ 3 ] ];
  17698. w2 = weight * weight;
  17699. w3 = weight * w2;
  17700. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  17701. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  17702. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  17703. return v3;
  17704. };
  17705. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  17706. var v0 = ( p2 - p0 ) * 0.5,
  17707. v1 = ( p3 - p1 ) * 0.5;
  17708. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17709. };
  17710. // Get next key with
  17711. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  17712. var keys = this.data.hierarchy[ h ].keys;
  17713. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17714. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17715. key = key < keys.length - 1 ? key : keys.length - 1;
  17716. } else {
  17717. key = key % keys.length;
  17718. }
  17719. for ( ; key < keys.length; key++ ) {
  17720. if ( keys[ key ][ type ] !== undefined ) {
  17721. return keys[ key ];
  17722. }
  17723. }
  17724. return this.data.hierarchy[ h ].keys[ 0 ];
  17725. };
  17726. // Get previous key with
  17727. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  17728. var keys = this.data.hierarchy[ h ].keys;
  17729. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17730. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17731. key = key > 0 ? key : 0;
  17732. } else {
  17733. key = key >= 0 ? key : key + keys.length;
  17734. }
  17735. for ( ; key >= 0; key -- ) {
  17736. if ( keys[ key ][ type ] !== undefined ) {
  17737. return keys[ key ];
  17738. }
  17739. }
  17740. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  17741. };
  17742. /**
  17743. * @author mikael emtinger / http://gomo.se/
  17744. * @author mrdoob / http://mrdoob.com/
  17745. * @author alteredq / http://alteredqualia.com/
  17746. * @author khang duong
  17747. * @author erik kitson
  17748. */
  17749. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  17750. this.root = root;
  17751. this.data = THREE.AnimationHandler.get( data );
  17752. this.hierarchy = THREE.AnimationHandler.parse( root );
  17753. this.currentTime = 0;
  17754. this.timeScale = 0.001;
  17755. this.isPlaying = false;
  17756. this.isPaused = true;
  17757. this.loop = true;
  17758. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  17759. // initialize to first keyframes
  17760. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17761. var keys = this.data.hierarchy[h].keys,
  17762. sids = this.data.hierarchy[h].sids,
  17763. obj = this.hierarchy[h];
  17764. if ( keys.length && sids ) {
  17765. for ( var s = 0; s < sids.length; s++ ) {
  17766. var sid = sids[ s ],
  17767. next = this.getNextKeyWith( sid, h, 0 );
  17768. if ( next ) {
  17769. next.apply( sid );
  17770. }
  17771. }
  17772. obj.matrixAutoUpdate = false;
  17773. this.data.hierarchy[h].node.updateMatrix();
  17774. obj.matrixWorldNeedsUpdate = true;
  17775. }
  17776. }
  17777. };
  17778. // Play
  17779. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  17780. if( !this.isPlaying ) {
  17781. this.isPlaying = true;
  17782. this.loop = loop !== undefined ? loop : true;
  17783. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17784. this.startTimeMs = startTimeMS;
  17785. this.startTime = 10000000;
  17786. this.endTime = -this.startTime;
  17787. // reset key cache
  17788. var h, hl = this.hierarchy.length,
  17789. object,
  17790. node;
  17791. for ( h = 0; h < hl; h++ ) {
  17792. object = this.hierarchy[ h ];
  17793. node = this.data.hierarchy[ h ];
  17794. object.useQuaternion = true;
  17795. if ( node.animationCache === undefined ) {
  17796. node.animationCache = {};
  17797. node.animationCache.prevKey = null;
  17798. node.animationCache.nextKey = null;
  17799. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17800. }
  17801. var keys = this.data.hierarchy[h].keys;
  17802. if (keys.length) {
  17803. node.animationCache.prevKey = keys[ 0 ];
  17804. node.animationCache.nextKey = keys[ 1 ];
  17805. this.startTime = Math.min( keys[0].time, this.startTime );
  17806. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  17807. }
  17808. }
  17809. this.update( 0 );
  17810. }
  17811. this.isPaused = false;
  17812. THREE.AnimationHandler.addToUpdate( this );
  17813. };
  17814. // Pause
  17815. THREE.KeyFrameAnimation.prototype.pause = function() {
  17816. if( this.isPaused ) {
  17817. THREE.AnimationHandler.addToUpdate( this );
  17818. } else {
  17819. THREE.AnimationHandler.removeFromUpdate( this );
  17820. }
  17821. this.isPaused = !this.isPaused;
  17822. };
  17823. // Stop
  17824. THREE.KeyFrameAnimation.prototype.stop = function() {
  17825. this.isPlaying = false;
  17826. this.isPaused = false;
  17827. THREE.AnimationHandler.removeFromUpdate( this );
  17828. // reset JIT matrix and remove cache
  17829. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  17830. var obj = this.hierarchy[ h ];
  17831. var node = this.data.hierarchy[ h ];
  17832. if ( node.animationCache !== undefined ) {
  17833. var original = node.animationCache.originalMatrix;
  17834. if( obj instanceof THREE.Bone ) {
  17835. original.copy( obj.skinMatrix );
  17836. obj.skinMatrix = original;
  17837. } else {
  17838. original.copy( obj.matrix );
  17839. obj.matrix = original;
  17840. }
  17841. delete node.animationCache;
  17842. }
  17843. }
  17844. };
  17845. // Update
  17846. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  17847. // early out
  17848. if( !this.isPlaying ) return;
  17849. // vars
  17850. var prevKey, nextKey;
  17851. var object;
  17852. var node;
  17853. var frame;
  17854. var JIThierarchy = this.data.JIT.hierarchy;
  17855. var currentTime, unloopedCurrentTime;
  17856. var looped;
  17857. // update
  17858. this.currentTime += deltaTimeMS * this.timeScale;
  17859. unloopedCurrentTime = this.currentTime;
  17860. currentTime = this.currentTime = this.currentTime % this.data.length;
  17861. // if looped around, the current time should be based on the startTime
  17862. if ( currentTime < this.startTimeMs ) {
  17863. currentTime = this.currentTime = this.startTimeMs + currentTime;
  17864. }
  17865. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17866. looped = currentTime < unloopedCurrentTime;
  17867. if ( looped && !this.loop ) {
  17868. // Set the animation to the last keyframes and stop
  17869. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17870. var keys = this.data.hierarchy[h].keys,
  17871. sids = this.data.hierarchy[h].sids,
  17872. end = keys.length-1,
  17873. obj = this.hierarchy[h];
  17874. if ( keys.length ) {
  17875. for ( var s = 0; s < sids.length; s++ ) {
  17876. var sid = sids[ s ],
  17877. prev = this.getPrevKeyWith( sid, h, end );
  17878. if ( prev ) {
  17879. prev.apply( sid );
  17880. }
  17881. }
  17882. this.data.hierarchy[h].node.updateMatrix();
  17883. obj.matrixWorldNeedsUpdate = true;
  17884. }
  17885. }
  17886. this.stop();
  17887. return;
  17888. }
  17889. // check pre-infinity
  17890. if ( currentTime < this.startTime ) {
  17891. return;
  17892. }
  17893. // update
  17894. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17895. object = this.hierarchy[ h ];
  17896. node = this.data.hierarchy[ h ];
  17897. var keys = node.keys,
  17898. animationCache = node.animationCache;
  17899. // use JIT?
  17900. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  17901. if( object instanceof THREE.Bone ) {
  17902. object.skinMatrix = JIThierarchy[ h ][ frame ];
  17903. object.matrixWorldNeedsUpdate = false;
  17904. } else {
  17905. object.matrix = JIThierarchy[ h ][ frame ];
  17906. object.matrixWorldNeedsUpdate = true;
  17907. }
  17908. // use interpolation
  17909. } else if ( keys.length ) {
  17910. // make sure so original matrix and not JIT matrix is set
  17911. if ( this.JITCompile && animationCache ) {
  17912. if( object instanceof THREE.Bone ) {
  17913. object.skinMatrix = animationCache.originalMatrix;
  17914. } else {
  17915. object.matrix = animationCache.originalMatrix;
  17916. }
  17917. }
  17918. prevKey = animationCache.prevKey;
  17919. nextKey = animationCache.nextKey;
  17920. if ( prevKey && nextKey ) {
  17921. // switch keys?
  17922. if ( nextKey.time <= unloopedCurrentTime ) {
  17923. // did we loop?
  17924. if ( looped && this.loop ) {
  17925. prevKey = keys[ 0 ];
  17926. nextKey = keys[ 1 ];
  17927. while ( nextKey.time < currentTime ) {
  17928. prevKey = nextKey;
  17929. nextKey = keys[ prevKey.index + 1 ];
  17930. }
  17931. } else if ( !looped ) {
  17932. var lastIndex = keys.length - 1;
  17933. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  17934. prevKey = nextKey;
  17935. nextKey = keys[ prevKey.index + 1 ];
  17936. }
  17937. }
  17938. animationCache.prevKey = prevKey;
  17939. animationCache.nextKey = nextKey;
  17940. }
  17941. if(nextKey.time >= currentTime)
  17942. prevKey.interpolate( nextKey, currentTime );
  17943. else
  17944. prevKey.interpolate( nextKey, nextKey.time);
  17945. }
  17946. this.data.hierarchy[h].node.updateMatrix();
  17947. object.matrixWorldNeedsUpdate = true;
  17948. }
  17949. }
  17950. // update JIT?
  17951. if ( this.JITCompile ) {
  17952. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  17953. this.hierarchy[ 0 ].updateMatrixWorld( true );
  17954. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  17955. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  17956. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  17957. } else {
  17958. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  17959. }
  17960. }
  17961. }
  17962. }
  17963. };
  17964. // Get next key with
  17965. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  17966. var keys = this.data.hierarchy[ h ].keys;
  17967. key = key % keys.length;
  17968. for ( ; key < keys.length; key++ ) {
  17969. if ( keys[ key ].hasTarget( sid ) ) {
  17970. return keys[ key ];
  17971. }
  17972. }
  17973. return keys[ 0 ];
  17974. };
  17975. // Get previous key with
  17976. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  17977. var keys = this.data.hierarchy[ h ].keys;
  17978. key = key >= 0 ? key : key + keys.length;
  17979. for ( ; key >= 0; key-- ) {
  17980. if ( keys[ key ].hasTarget( sid ) ) {
  17981. return keys[ key ];
  17982. }
  17983. }
  17984. return keys[ keys.length - 1 ];
  17985. };
  17986. /**
  17987. * Camera for rendering cube maps
  17988. * - renders scene into axis-aligned cube
  17989. *
  17990. * @author alteredq / http://alteredqualia.com/
  17991. */
  17992. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  17993. THREE.Object3D.call( this );
  17994. var fov = 90, aspect = 1;
  17995. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17996. cameraPX.up.set( 0, -1, 0 );
  17997. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  17998. this.add( cameraPX );
  17999. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18000. cameraNX.up.set( 0, -1, 0 );
  18001. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  18002. this.add( cameraNX );
  18003. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18004. cameraPY.up.set( 0, 0, 1 );
  18005. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  18006. this.add( cameraPY );
  18007. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18008. cameraNY.up.set( 0, 0, -1 );
  18009. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  18010. this.add( cameraNY );
  18011. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18012. cameraPZ.up.set( 0, -1, 0 );
  18013. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  18014. this.add( cameraPZ );
  18015. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18016. cameraNZ.up.set( 0, -1, 0 );
  18017. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  18018. this.add( cameraNZ );
  18019. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  18020. this.updateCubeMap = function ( renderer, scene ) {
  18021. var renderTarget = this.renderTarget;
  18022. var generateMipmaps = renderTarget.generateMipmaps;
  18023. renderTarget.generateMipmaps = false;
  18024. renderTarget.activeCubeFace = 0;
  18025. renderer.render( scene, cameraPX, renderTarget );
  18026. renderTarget.activeCubeFace = 1;
  18027. renderer.render( scene, cameraNX, renderTarget );
  18028. renderTarget.activeCubeFace = 2;
  18029. renderer.render( scene, cameraPY, renderTarget );
  18030. renderTarget.activeCubeFace = 3;
  18031. renderer.render( scene, cameraNY, renderTarget );
  18032. renderTarget.activeCubeFace = 4;
  18033. renderer.render( scene, cameraPZ, renderTarget );
  18034. renderTarget.generateMipmaps = generateMipmaps;
  18035. renderTarget.activeCubeFace = 5;
  18036. renderer.render( scene, cameraNZ, renderTarget );
  18037. };
  18038. };
  18039. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  18040. /*
  18041. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  18042. *
  18043. * A general perpose camera, for setting FOV, Lens Focal Length,
  18044. * and switching between perspective and orthographic views easily.
  18045. * Use this only if you do not wish to manage
  18046. * both a Orthographic and Perspective Camera
  18047. *
  18048. */
  18049. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  18050. THREE.Camera.call( this );
  18051. this.fov = fov;
  18052. this.left = -width / 2;
  18053. this.right = width / 2
  18054. this.top = height / 2;
  18055. this.bottom = -height / 2;
  18056. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  18057. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  18058. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  18059. this.zoom = 1;
  18060. this.toPerspective();
  18061. var aspect = width/height;
  18062. };
  18063. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  18064. THREE.CombinedCamera.prototype.toPerspective = function () {
  18065. // Switches to the Perspective Camera
  18066. this.near = this.cameraP.near;
  18067. this.far = this.cameraP.far;
  18068. this.cameraP.fov = this.fov / this.zoom ;
  18069. this.cameraP.updateProjectionMatrix();
  18070. this.projectionMatrix = this.cameraP.projectionMatrix;
  18071. this.inPerspectiveMode = true;
  18072. this.inOrthographicMode = false;
  18073. };
  18074. THREE.CombinedCamera.prototype.toOrthographic = function () {
  18075. // Switches to the Orthographic camera estimating viewport from Perspective
  18076. var fov = this.fov;
  18077. var aspect = this.cameraP.aspect;
  18078. var near = this.cameraP.near;
  18079. var far = this.cameraP.far;
  18080. // The size that we set is the mid plane of the viewing frustum
  18081. var hyperfocus = ( near + far ) / 2;
  18082. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  18083. var planeHeight = 2 * halfHeight;
  18084. var planeWidth = planeHeight * aspect;
  18085. var halfWidth = planeWidth / 2;
  18086. halfHeight /= this.zoom;
  18087. halfWidth /= this.zoom;
  18088. this.cameraO.left = -halfWidth;
  18089. this.cameraO.right = halfWidth;
  18090. this.cameraO.top = halfHeight;
  18091. this.cameraO.bottom = -halfHeight;
  18092. // this.cameraO.left = -farHalfWidth;
  18093. // this.cameraO.right = farHalfWidth;
  18094. // this.cameraO.top = farHalfHeight;
  18095. // this.cameraO.bottom = -farHalfHeight;
  18096. // this.cameraO.left = this.left / this.zoom;
  18097. // this.cameraO.right = this.right / this.zoom;
  18098. // this.cameraO.top = this.top / this.zoom;
  18099. // this.cameraO.bottom = this.bottom / this.zoom;
  18100. this.cameraO.updateProjectionMatrix();
  18101. this.near = this.cameraO.near;
  18102. this.far = this.cameraO.far;
  18103. this.projectionMatrix = this.cameraO.projectionMatrix;
  18104. this.inPerspectiveMode = false;
  18105. this.inOrthographicMode = true;
  18106. };
  18107. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  18108. this.cameraP.aspect = width / height;
  18109. this.left = -width / 2;
  18110. this.right = width / 2
  18111. this.top = height / 2;
  18112. this.bottom = -height / 2;
  18113. };
  18114. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  18115. this.fov = fov;
  18116. if ( this.inPerspectiveMode ) {
  18117. this.toPerspective();
  18118. } else {
  18119. this.toOrthographic();
  18120. }
  18121. };
  18122. // For mantaining similar API with PerspectiveCamera
  18123. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  18124. if ( this.inPerspectiveMode ) {
  18125. this.toPerspective();
  18126. } else {
  18127. this.toPerspective();
  18128. this.toOrthographic();
  18129. }
  18130. };
  18131. /*
  18132. * Uses Focal Length (in mm) to estimate and set FOV
  18133. * 35mm (fullframe) camera is used if frame size is not specified;
  18134. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  18135. */
  18136. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  18137. if ( frameHeight === undefined ) frameHeight = 24;
  18138. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  18139. this.setFov( fov );
  18140. return fov;
  18141. };
  18142. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  18143. this.zoom = zoom;
  18144. if ( this.inPerspectiveMode ) {
  18145. this.toPerspective();
  18146. } else {
  18147. this.toOrthographic();
  18148. }
  18149. };
  18150. THREE.CombinedCamera.prototype.toFrontView = function() {
  18151. this.rotation.x = 0;
  18152. this.rotation.y = 0;
  18153. this.rotation.z = 0;
  18154. // should we be modifing the matrix instead?
  18155. this.rotationAutoUpdate = false;
  18156. };
  18157. THREE.CombinedCamera.prototype.toBackView = function() {
  18158. this.rotation.x = 0;
  18159. this.rotation.y = Math.PI;
  18160. this.rotation.z = 0;
  18161. this.rotationAutoUpdate = false;
  18162. };
  18163. THREE.CombinedCamera.prototype.toLeftView = function() {
  18164. this.rotation.x = 0;
  18165. this.rotation.y = - Math.PI / 2;
  18166. this.rotation.z = 0;
  18167. this.rotationAutoUpdate = false;
  18168. };
  18169. THREE.CombinedCamera.prototype.toRightView = function() {
  18170. this.rotation.x = 0;
  18171. this.rotation.y = Math.PI / 2;
  18172. this.rotation.z = 0;
  18173. this.rotationAutoUpdate = false;
  18174. };
  18175. THREE.CombinedCamera.prototype.toTopView = function() {
  18176. this.rotation.x = - Math.PI / 2;
  18177. this.rotation.y = 0;
  18178. this.rotation.z = 0;
  18179. this.rotationAutoUpdate = false;
  18180. };
  18181. THREE.CombinedCamera.prototype.toBottomView = function() {
  18182. this.rotation.x = Math.PI / 2;
  18183. this.rotation.y = 0;
  18184. this.rotation.z = 0;
  18185. this.rotationAutoUpdate = false;
  18186. };
  18187. /**
  18188. * @author alteredq / http://alteredqualia.com/
  18189. *
  18190. * - 3d asterisk shape (for line pieces THREE.Line)
  18191. */
  18192. THREE.AsteriskGeometry = function ( innerRadius, outerRadius ) {
  18193. THREE.Geometry.call( this );
  18194. var sd = innerRadius;
  18195. var ed = outerRadius;
  18196. var sd2 = 0.707 * sd;
  18197. var ed2 = 0.707 * ed;
  18198. var rays = [ [ sd, 0, 0 ], [ ed, 0, 0 ], [ -sd, 0, 0 ], [ -ed, 0, 0 ],
  18199. [ 0, sd, 0 ], [ 0, ed, 0 ], [ 0, -sd, 0 ], [ 0, -ed, 0 ],
  18200. [ 0, 0, sd ], [ 0, 0, ed ], [ 0, 0, -sd ], [ 0, 0, -ed ],
  18201. [ sd2, sd2, 0 ], [ ed2, ed2, 0 ], [ -sd2, -sd2, 0 ], [ -ed2, -ed2, 0 ],
  18202. [ sd2, -sd2, 0 ], [ ed2, -ed2, 0 ], [ -sd2, sd2, 0 ], [ -ed2, ed2, 0 ],
  18203. [ sd2, 0, sd2 ], [ ed2, 0, ed2 ], [ -sd2, 0, -sd2 ], [ -ed2, 0, -ed2 ],
  18204. [ sd2, 0, -sd2 ], [ ed2, 0, -ed2 ], [ -sd2, 0, sd2 ], [ -ed2, 0, ed2 ],
  18205. [ 0, sd2, sd2 ], [ 0, ed2, ed2 ], [ 0, -sd2, -sd2 ], [ 0, -ed2, -ed2 ],
  18206. [ 0, sd2, -sd2 ], [ 0, ed2, -ed2 ], [ 0, -sd2, sd2 ], [ 0, -ed2, ed2 ]
  18207. ];
  18208. for ( var i = 0, il = rays.length; i < il; i ++ ) {
  18209. var x = rays[ i ][ 0 ];
  18210. var y = rays[ i ][ 1 ];
  18211. var z = rays[ i ][ 2 ];
  18212. this.vertices.push( new THREE.Vector3( x, y, z ) );
  18213. }
  18214. };
  18215. THREE.AsteriskGeometry.prototype = Object.create( THREE.Geometry.prototype );/**
  18216. * @author hughes
  18217. */
  18218. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18219. THREE.Geometry.call( this );
  18220. radius = radius || 50;
  18221. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18222. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18223. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18224. var i, uvs = [],
  18225. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18226. this.vertices.push(center);
  18227. uvs.push( centerUV );
  18228. for ( i = 0; i <= segments; i ++ ) {
  18229. var vertex = new THREE.Vector3();
  18230. vertex.x = radius * Math.cos( thetaStart + i / segments * thetaLength );
  18231. vertex.y = radius * Math.sin( thetaStart + i / segments * thetaLength );
  18232. this.vertices.push( vertex );
  18233. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  18234. }
  18235. var n = new THREE.Vector3( 0, 0, -1 );
  18236. for ( i = 1; i <= segments; i ++ ) {
  18237. var v1 = i;
  18238. var v2 = i + 1 ;
  18239. var v3 = 0;
  18240. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  18241. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  18242. }
  18243. this.computeCentroids();
  18244. this.computeFaceNormals();
  18245. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18246. };
  18247. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18248. /**
  18249. * @author mrdoob / http://mrdoob.com/
  18250. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18251. */
  18252. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18253. THREE.Geometry.call( this );
  18254. var scope = this;
  18255. this.width = width;
  18256. this.height = height;
  18257. this.depth = depth;
  18258. this.widthSegments = widthSegments || 1;
  18259. this.heightSegments = heightSegments || 1;
  18260. this.depthSegments = depthSegments || 1;
  18261. var width_half = this.width / 2;
  18262. var height_half = this.height / 2;
  18263. var depth_half = this.depth / 2;
  18264. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  18265. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  18266. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  18267. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  18268. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  18269. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  18270. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18271. var w, ix, iy,
  18272. gridX = scope.widthSegments,
  18273. gridY = scope.heightSegments,
  18274. width_half = width / 2,
  18275. height_half = height / 2,
  18276. offset = scope.vertices.length;
  18277. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18278. w = 'z';
  18279. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18280. w = 'y';
  18281. gridY = scope.depthSegments;
  18282. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18283. w = 'x';
  18284. gridX = scope.depthSegments;
  18285. }
  18286. var gridX1 = gridX + 1,
  18287. gridY1 = gridY + 1,
  18288. segment_width = width / gridX,
  18289. segment_height = height / gridY,
  18290. normal = new THREE.Vector3();
  18291. normal[ w ] = depth > 0 ? 1 : - 1;
  18292. for ( iy = 0; iy < gridY1; iy ++ ) {
  18293. for ( ix = 0; ix < gridX1; ix ++ ) {
  18294. var vector = new THREE.Vector3();
  18295. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18296. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18297. vector[ w ] = depth;
  18298. scope.vertices.push( vector );
  18299. }
  18300. }
  18301. for ( iy = 0; iy < gridY; iy++ ) {
  18302. for ( ix = 0; ix < gridX; ix++ ) {
  18303. var a = ix + gridX1 * iy;
  18304. var b = ix + gridX1 * ( iy + 1 );
  18305. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18306. var d = ( ix + 1 ) + gridX1 * iy;
  18307. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  18308. face.normal.copy( normal );
  18309. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  18310. face.materialIndex = materialIndex;
  18311. scope.faces.push( face );
  18312. scope.faceVertexUvs[ 0 ].push( [
  18313. new THREE.Vector2( ix / gridX, 1 - iy / gridY ),
  18314. new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  18315. new THREE.Vector2( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  18316. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY )
  18317. ] );
  18318. }
  18319. }
  18320. }
  18321. this.computeCentroids();
  18322. this.mergeVertices();
  18323. };
  18324. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18325. /**
  18326. * @author mrdoob / http://mrdoob.com/
  18327. */
  18328. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radiusSegments, heightSegments, openEnded ) {
  18329. THREE.Geometry.call( this );
  18330. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18331. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18332. height = height !== undefined ? height : 100;
  18333. var heightHalf = height / 2;
  18334. var segmentsX = radiusSegments || 8;
  18335. var segmentsY = heightSegments || 1;
  18336. var x, y, vertices = [], uvs = [];
  18337. for ( y = 0; y <= segmentsY; y ++ ) {
  18338. var verticesRow = [];
  18339. var uvsRow = [];
  18340. var v = y / segmentsY;
  18341. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18342. for ( x = 0; x <= segmentsX; x ++ ) {
  18343. var u = x / segmentsX;
  18344. var vertex = new THREE.Vector3();
  18345. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  18346. vertex.y = - v * height + heightHalf;
  18347. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  18348. this.vertices.push( vertex );
  18349. verticesRow.push( this.vertices.length - 1 );
  18350. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  18351. }
  18352. vertices.push( verticesRow );
  18353. uvs.push( uvsRow );
  18354. }
  18355. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18356. var na, nb;
  18357. for ( x = 0; x < segmentsX; x ++ ) {
  18358. if ( radiusTop !== 0 ) {
  18359. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18360. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18361. } else {
  18362. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18363. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18364. }
  18365. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18366. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18367. for ( y = 0; y < segmentsY; y ++ ) {
  18368. var v1 = vertices[ y ][ x ];
  18369. var v2 = vertices[ y + 1 ][ x ];
  18370. var v3 = vertices[ y + 1 ][ x + 1 ];
  18371. var v4 = vertices[ y ][ x + 1 ];
  18372. var n1 = na.clone();
  18373. var n2 = na.clone();
  18374. var n3 = nb.clone();
  18375. var n4 = nb.clone();
  18376. var uv1 = uvs[ y ][ x ].clone();
  18377. var uv2 = uvs[ y + 1 ][ x ].clone();
  18378. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18379. var uv4 = uvs[ y ][ x + 1 ].clone();
  18380. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  18381. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  18382. }
  18383. }
  18384. // top cap
  18385. if ( !openEnded && radiusTop > 0 ) {
  18386. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18387. for ( x = 0; x < segmentsX; x ++ ) {
  18388. var v1 = vertices[ 0 ][ x ];
  18389. var v2 = vertices[ 0 ][ x + 1 ];
  18390. var v3 = this.vertices.length - 1;
  18391. var n1 = new THREE.Vector3( 0, 1, 0 );
  18392. var n2 = new THREE.Vector3( 0, 1, 0 );
  18393. var n3 = new THREE.Vector3( 0, 1, 0 );
  18394. var uv1 = uvs[ 0 ][ x ].clone();
  18395. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18396. var uv3 = new THREE.Vector2( uv2.u, 0 );
  18397. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18398. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18399. }
  18400. }
  18401. // bottom cap
  18402. if ( !openEnded && radiusBottom > 0 ) {
  18403. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18404. for ( x = 0; x < segmentsX; x ++ ) {
  18405. var v1 = vertices[ y ][ x + 1 ];
  18406. var v2 = vertices[ y ][ x ];
  18407. var v3 = this.vertices.length - 1;
  18408. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18409. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18410. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18411. var uv1 = uvs[ y ][ x + 1 ].clone();
  18412. var uv2 = uvs[ y ][ x ].clone();
  18413. var uv3 = new THREE.Vector2( uv2.u, 1 );
  18414. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18415. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18416. }
  18417. }
  18418. this.computeCentroids();
  18419. this.computeFaceNormals();
  18420. }
  18421. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18422. /**
  18423. * @author zz85 / http://www.lab4games.net/zz85/blog
  18424. *
  18425. * Creates extruded geometry from a path shape.
  18426. *
  18427. * parameters = {
  18428. *
  18429. * size: <float>, // size of the text
  18430. * height: <float>, // thickness to extrude text
  18431. * curveSegments: <int>, // number of points on the curves
  18432. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18433. * amount: <int>, // Amount
  18434. *
  18435. * bevelEnabled: <bool>, // turn on bevel
  18436. * bevelThickness: <float>, // how deep into text bevel goes
  18437. * bevelSize: <float>, // how far from text outline is bevel
  18438. * bevelSegments: <int>, // number of bevel layers
  18439. *
  18440. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18441. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18442. *
  18443. * material: <int> // material index for front and back faces
  18444. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18445. * uvGenerator: <Object> // object that provides UV generator functions
  18446. *
  18447. * }
  18448. **/
  18449. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18450. if ( typeof( shapes ) === "undefined" ) {
  18451. shapes = [];
  18452. return;
  18453. }
  18454. THREE.Geometry.call( this );
  18455. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18456. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18457. this.addShapeList( shapes, options );
  18458. this.computeCentroids();
  18459. this.computeFaceNormals();
  18460. // can't really use automatic vertex normals
  18461. // as then front and back sides get smoothed too
  18462. // should do separate smoothing just for sides
  18463. //this.computeVertexNormals();
  18464. //console.log( "took", ( Date.now() - startTime ) );
  18465. };
  18466. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18467. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18468. var sl = shapes.length;
  18469. for ( var s = 0; s < sl; s ++ ) {
  18470. var shape = shapes[ s ];
  18471. this.addShape( shape, options );
  18472. }
  18473. };
  18474. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18475. var amount = options.amount !== undefined ? options.amount : 100;
  18476. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18477. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18478. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18479. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18480. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18481. var steps = options.steps !== undefined ? options.steps : 1;
  18482. var extrudePath = options.extrudePath;
  18483. var extrudePts, extrudeByPath = false;
  18484. var material = options.material;
  18485. var extrudeMaterial = options.extrudeMaterial;
  18486. // Use default WorldUVGenerator if no UV generators are specified.
  18487. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18488. var shapebb = this.shapebb;
  18489. //shapebb = shape.getBoundingBox();
  18490. var splineTube, binormal, normal, position2;
  18491. if ( extrudePath ) {
  18492. extrudePts = extrudePath.getSpacedPoints( steps );
  18493. extrudeByPath = true;
  18494. bevelEnabled = false; // bevels not supported for path extrusion
  18495. // SETUP TNB variables
  18496. // Reuse TNB from TubeGeomtry for now.
  18497. // TODO1 - have a .isClosed in spline?
  18498. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18499. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18500. binormal = new THREE.Vector3();
  18501. normal = new THREE.Vector3();
  18502. position2 = new THREE.Vector3();
  18503. }
  18504. // Safeguards if bevels are not enabled
  18505. if ( ! bevelEnabled ) {
  18506. bevelSegments = 0;
  18507. bevelThickness = 0;
  18508. bevelSize = 0;
  18509. }
  18510. // Variables initalization
  18511. var ahole, h, hl; // looping of holes
  18512. var scope = this;
  18513. var bevelPoints = [];
  18514. var shapesOffset = this.vertices.length;
  18515. var shapePoints = shape.extractPoints( curveSegments );
  18516. var vertices = shapePoints.shape;
  18517. var holes = shapePoints.holes;
  18518. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  18519. if ( reverse ) {
  18520. vertices = vertices.reverse();
  18521. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18522. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18523. ahole = holes[ h ];
  18524. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18525. holes[ h ] = ahole.reverse();
  18526. }
  18527. }
  18528. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18529. }
  18530. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18531. /* Vertices */
  18532. var contour = vertices; // vertices has all points but contour has only points of circumference
  18533. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18534. ahole = holes[ h ];
  18535. vertices = vertices.concat( ahole );
  18536. }
  18537. function scalePt2 ( pt, vec, size ) {
  18538. if ( !vec ) console.log( "die" );
  18539. return vec.clone().multiplyScalar( size ).add( pt );
  18540. }
  18541. var b, bs, t, z,
  18542. vert, vlen = vertices.length,
  18543. face, flen = faces.length,
  18544. cont, clen = contour.length;
  18545. // Find directions for point movement
  18546. var RAD_TO_DEGREES = 180 / Math.PI;
  18547. function getBevelVec( pt_i, pt_j, pt_k ) {
  18548. // Algorithm 2
  18549. return getBevelVec2( pt_i, pt_j, pt_k );
  18550. }
  18551. function getBevelVec1( pt_i, pt_j, pt_k ) {
  18552. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  18553. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  18554. if ( anglea > angleb ) {
  18555. angleb += Math.PI * 2;
  18556. }
  18557. var anglec = ( anglea + angleb ) / 2;
  18558. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  18559. var x = - Math.cos( anglec );
  18560. var y = - Math.sin( anglec );
  18561. var vec = new THREE.Vector2( x, y ); //.normalize();
  18562. return vec;
  18563. }
  18564. function getBevelVec2( pt_i, pt_j, pt_k ) {
  18565. var a = THREE.ExtrudeGeometry.__v1,
  18566. b = THREE.ExtrudeGeometry.__v2,
  18567. v_hat = THREE.ExtrudeGeometry.__v3,
  18568. w_hat = THREE.ExtrudeGeometry.__v4,
  18569. p = THREE.ExtrudeGeometry.__v5,
  18570. q = THREE.ExtrudeGeometry.__v6,
  18571. v, w,
  18572. v_dot_w_hat, q_sub_p_dot_w_hat,
  18573. s, intersection;
  18574. // good reading for line-line intersection
  18575. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  18576. // define a as vector j->i
  18577. // define b as vectot k->i
  18578. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  18579. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  18580. // get unit vectors
  18581. v = a.normalize();
  18582. w = b.normalize();
  18583. // normals from pt i
  18584. v_hat.set( -v.y, v.x );
  18585. w_hat.set( w.y, -w.x );
  18586. // pts from i
  18587. p.copy( pt_i ).add( v_hat );
  18588. q.copy( pt_i ).add( w_hat );
  18589. if ( p.equals( q ) ) {
  18590. //console.log("Warning: lines are straight");
  18591. return w_hat.clone();
  18592. }
  18593. // Points from j, k. helps prevents points cross overover most of the time
  18594. p.copy( pt_j ).add( v_hat );
  18595. q.copy( pt_k ).add( w_hat );
  18596. v_dot_w_hat = v.dot( w_hat );
  18597. q_sub_p_dot_w_hat = q.sub( p ).dot( w_hat );
  18598. // We should not reach these conditions
  18599. if ( v_dot_w_hat === 0 ) {
  18600. console.log( "Either infinite or no solutions!" );
  18601. if ( q_sub_p_dot_w_hat === 0 ) {
  18602. console.log( "Its finite solutions." );
  18603. } else {
  18604. console.log( "Too bad, no solutions." );
  18605. }
  18606. }
  18607. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  18608. if ( s < 0 ) {
  18609. // in case of emergecy, revert to algorithm 1.
  18610. return getBevelVec1( pt_i, pt_j, pt_k );
  18611. }
  18612. intersection = v.multiplyScalar( s ).add( p );
  18613. return intersection.sub( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  18614. }
  18615. var contourMovements = [];
  18616. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18617. if ( j === il ) j = 0;
  18618. if ( k === il ) k = 0;
  18619. // (j)---(i)---(k)
  18620. // console.log('i,j,k', i, j , k)
  18621. var pt_i = contour[ i ];
  18622. var pt_j = contour[ j ];
  18623. var pt_k = contour[ k ];
  18624. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18625. }
  18626. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18627. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18628. ahole = holes[ h ];
  18629. oneHoleMovements = [];
  18630. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18631. if ( j === il ) j = 0;
  18632. if ( k === il ) k = 0;
  18633. // (j)---(i)---(k)
  18634. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18635. }
  18636. holesMovements.push( oneHoleMovements );
  18637. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18638. }
  18639. // Loop bevelSegments, 1 for the front, 1 for the back
  18640. for ( b = 0; b < bevelSegments; b ++ ) {
  18641. //for ( b = bevelSegments; b > 0; b -- ) {
  18642. t = b / bevelSegments;
  18643. z = bevelThickness * ( 1 - t );
  18644. //z = bevelThickness * t;
  18645. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  18646. //bs = bevelSize * t ; // linear
  18647. // contract shape
  18648. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18649. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18650. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  18651. v( vert.x, vert.y, - z );
  18652. }
  18653. // expand holes
  18654. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  18655. ahole = holes[ h ];
  18656. oneHoleMovements = holesMovements[ h ];
  18657. for ( i = 0, il = ahole.length; i < il; i++ ) {
  18658. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18659. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  18660. v( vert.x, vert.y, -z );
  18661. }
  18662. }
  18663. }
  18664. bs = bevelSize;
  18665. // Back facing vertices
  18666. for ( i = 0; i < vlen; i ++ ) {
  18667. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18668. if ( !extrudeByPath ) {
  18669. v( vert.x, vert.y, 0 );
  18670. } else {
  18671. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18672. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  18673. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  18674. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  18675. v( position2.x, position2.y, position2.z );
  18676. }
  18677. }
  18678. // Add stepped vertices...
  18679. // Including front facing vertices
  18680. var s;
  18681. for ( s = 1; s <= steps; s ++ ) {
  18682. for ( i = 0; i < vlen; i ++ ) {
  18683. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18684. if ( !extrudeByPath ) {
  18685. v( vert.x, vert.y, amount / steps * s );
  18686. } else {
  18687. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18688. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  18689. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  18690. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  18691. v( position2.x, position2.y, position2.z );
  18692. }
  18693. }
  18694. }
  18695. // Add bevel segments planes
  18696. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18697. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  18698. t = b / bevelSegments;
  18699. z = bevelThickness * ( 1 - t );
  18700. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  18701. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  18702. // contract shape
  18703. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18704. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18705. v( vert.x, vert.y, amount + z );
  18706. }
  18707. // expand holes
  18708. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18709. ahole = holes[ h ];
  18710. oneHoleMovements = holesMovements[ h ];
  18711. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18712. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18713. if ( !extrudeByPath ) {
  18714. v( vert.x, vert.y, amount + z );
  18715. } else {
  18716. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  18717. }
  18718. }
  18719. }
  18720. }
  18721. /* Faces */
  18722. // Top and bottom faces
  18723. buildLidFaces();
  18724. // Sides faces
  18725. buildSideFaces();
  18726. ///// Internal functions
  18727. function buildLidFaces() {
  18728. if ( bevelEnabled ) {
  18729. var layer = 0 ; // steps + 1
  18730. var offset = vlen * layer;
  18731. // Bottom faces
  18732. for ( i = 0; i < flen; i ++ ) {
  18733. face = faces[ i ];
  18734. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  18735. }
  18736. layer = steps + bevelSegments * 2;
  18737. offset = vlen * layer;
  18738. // Top faces
  18739. for ( i = 0; i < flen; i ++ ) {
  18740. face = faces[ i ];
  18741. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  18742. }
  18743. } else {
  18744. // Bottom faces
  18745. for ( i = 0; i < flen; i++ ) {
  18746. face = faces[ i ];
  18747. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  18748. }
  18749. // Top faces
  18750. for ( i = 0; i < flen; i ++ ) {
  18751. face = faces[ i ];
  18752. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  18753. }
  18754. }
  18755. }
  18756. // Create faces for the z-sides of the shape
  18757. function buildSideFaces() {
  18758. var layeroffset = 0;
  18759. sidewalls( contour, layeroffset );
  18760. layeroffset += contour.length;
  18761. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18762. ahole = holes[ h ];
  18763. sidewalls( ahole, layeroffset );
  18764. //, true
  18765. layeroffset += ahole.length;
  18766. }
  18767. }
  18768. function sidewalls( contour, layeroffset ) {
  18769. var j, k;
  18770. i = contour.length;
  18771. while ( --i >= 0 ) {
  18772. j = i;
  18773. k = i - 1;
  18774. if ( k < 0 ) k = contour.length - 1;
  18775. //console.log('b', i,j, i-1, k,vertices.length);
  18776. var s = 0, sl = steps + bevelSegments * 2;
  18777. for ( s = 0; s < sl; s ++ ) {
  18778. var slen1 = vlen * s;
  18779. var slen2 = vlen * ( s + 1 );
  18780. var a = layeroffset + j + slen1,
  18781. b = layeroffset + k + slen1,
  18782. c = layeroffset + k + slen2,
  18783. d = layeroffset + j + slen2;
  18784. f4( a, b, c, d, contour, s, sl, j, k );
  18785. }
  18786. }
  18787. }
  18788. function v( x, y, z ) {
  18789. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  18790. }
  18791. function f3( a, b, c, isBottom ) {
  18792. a += shapesOffset;
  18793. b += shapesOffset;
  18794. c += shapesOffset;
  18795. // normal, color, material
  18796. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18797. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  18798. scope.faceVertexUvs[ 0 ].push( uvs );
  18799. }
  18800. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  18801. a += shapesOffset;
  18802. b += shapesOffset;
  18803. c += shapesOffset;
  18804. d += shapesOffset;
  18805. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  18806. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  18807. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  18808. scope.faceVertexUvs[ 0 ].push( uvs );
  18809. }
  18810. };
  18811. THREE.ExtrudeGeometry.WorldUVGenerator = {
  18812. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18813. var ax = geometry.vertices[ indexA ].x,
  18814. ay = geometry.vertices[ indexA ].y,
  18815. bx = geometry.vertices[ indexB ].x,
  18816. by = geometry.vertices[ indexB ].y,
  18817. cx = geometry.vertices[ indexC ].x,
  18818. cy = geometry.vertices[ indexC ].y;
  18819. return [
  18820. new THREE.Vector2( ax, ay ),
  18821. new THREE.Vector2( bx, by ),
  18822. new THREE.Vector2( cx, cy )
  18823. ];
  18824. },
  18825. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18826. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  18827. },
  18828. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  18829. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  18830. contourIndex1, contourIndex2 ) {
  18831. var ax = geometry.vertices[ indexA ].x,
  18832. ay = geometry.vertices[ indexA ].y,
  18833. az = geometry.vertices[ indexA ].z,
  18834. bx = geometry.vertices[ indexB ].x,
  18835. by = geometry.vertices[ indexB ].y,
  18836. bz = geometry.vertices[ indexB ].z,
  18837. cx = geometry.vertices[ indexC ].x,
  18838. cy = geometry.vertices[ indexC ].y,
  18839. cz = geometry.vertices[ indexC ].z,
  18840. dx = geometry.vertices[ indexD ].x,
  18841. dy = geometry.vertices[ indexD ].y,
  18842. dz = geometry.vertices[ indexD ].z;
  18843. if ( Math.abs( ay - by ) < 0.01 ) {
  18844. return [
  18845. new THREE.Vector2( ax, 1 - az ),
  18846. new THREE.Vector2( bx, 1 - bz ),
  18847. new THREE.Vector2( cx, 1 - cz ),
  18848. new THREE.Vector2( dx, 1 - dz )
  18849. ];
  18850. } else {
  18851. return [
  18852. new THREE.Vector2( ay, 1 - az ),
  18853. new THREE.Vector2( by, 1 - bz ),
  18854. new THREE.Vector2( cy, 1 - cz ),
  18855. new THREE.Vector2( dy, 1 - dz )
  18856. ];
  18857. }
  18858. }
  18859. };
  18860. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  18861. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  18862. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  18863. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  18864. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  18865. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  18866. /**
  18867. * @author jonobr1 / http://jonobr1.com
  18868. *
  18869. * Creates a one-sided polygonal geometry from a path shape. Similar to
  18870. * ExtrudeGeometry.
  18871. *
  18872. * parameters = {
  18873. *
  18874. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  18875. *
  18876. * material: <int> // material index for front and back faces
  18877. * uvGenerator: <Object> // object that provides UV generator functions
  18878. *
  18879. * }
  18880. **/
  18881. THREE.ShapeGeometry = function ( shapes, options ) {
  18882. THREE.Geometry.call( this );
  18883. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  18884. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18885. this.addShapeList( shapes, options );
  18886. this.computeCentroids();
  18887. this.computeFaceNormals();
  18888. };
  18889. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18890. /**
  18891. * Add an array of shapes to THREE.ShapeGeometry.
  18892. */
  18893. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18894. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  18895. this.addShape( shapes[ i ], options );
  18896. }
  18897. return this;
  18898. };
  18899. /**
  18900. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  18901. */
  18902. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  18903. if ( options === undefined ) options = {};
  18904. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18905. var material = options.material;
  18906. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  18907. var shapebb = this.shapebb;
  18908. //
  18909. var i, l, hole, s;
  18910. var shapesOffset = this.vertices.length;
  18911. var shapePoints = shape.extractPoints( curveSegments );
  18912. var vertices = shapePoints.shape;
  18913. var holes = shapePoints.holes;
  18914. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  18915. if ( reverse ) {
  18916. vertices = vertices.reverse();
  18917. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  18918. for ( i = 0, l = holes.length; i < l; i++ ) {
  18919. hole = holes[ i ];
  18920. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  18921. holes[ i ] = hole.reverse();
  18922. }
  18923. }
  18924. reverse = false;
  18925. }
  18926. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  18927. // Vertices
  18928. var contour = vertices;
  18929. for ( i = 0, l = holes.length; i < l; i++ ) {
  18930. hole = holes[ i ];
  18931. vertices = vertices.concat( hole );
  18932. }
  18933. //
  18934. var vert, vlen = vertices.length;
  18935. var face, flen = faces.length;
  18936. var cont, clen = contour.length;
  18937. for ( i = 0; i < vlen; i++ ) {
  18938. vert = vertices[ i ];
  18939. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  18940. }
  18941. for ( i = 0; i < flen; i++ ) {
  18942. face = faces[ i ];
  18943. var a = face[ 0 ] + shapesOffset;
  18944. var b = face[ 1 ] + shapesOffset;
  18945. var c = face[ 2 ] + shapesOffset;
  18946. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18947. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  18948. }
  18949. };
  18950. /**
  18951. * @author astrodud / http://astrodud.isgreat.org/
  18952. * @author zz85 / https://github.com/zz85
  18953. * @author bhouston / http://exocortex.com
  18954. */
  18955. // points - to create a closed torus, one must use a set of points
  18956. // like so: [ a, b, c, d, a ], see first is the same as last.
  18957. // segments - the number of circumference segments to create
  18958. // phiStart - the starting radian
  18959. // phiLength - the radian (0 to 2*PI) range of the lathed section
  18960. // 2*pi is a closed lathe, less than 2PI is a portion.
  18961. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  18962. THREE.Geometry.call( this );
  18963. segments = segments || 12;
  18964. phiStart = phiStart || 0;
  18965. phiLength = phiLength || 2 * Math.PI;
  18966. var inversePointLength = 1.0 / ( points.length - 1 );
  18967. var inverseSegments = 1.0 / segments;
  18968. for ( var i = 0, il = segments; i <= il; i ++ ) {
  18969. var phi = phiStart + i * inverseSegments * phiLength;
  18970. var c = Math.cos( phi ),
  18971. s = Math.sin( phi );
  18972. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  18973. var pt = points[ j ];
  18974. var vertex = new THREE.Vector3();
  18975. vertex.x = c * pt.x - s * pt.y;
  18976. vertex.y = s * pt.x + c * pt.y;
  18977. vertex.z = pt.z;
  18978. this.vertices.push( vertex );
  18979. }
  18980. }
  18981. var np = points.length;
  18982. for ( var i = 0, il = segments; i < il; i ++ ) {
  18983. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  18984. var base = j + np * i;
  18985. var a = base;
  18986. var b = base + np;
  18987. var c = base + 1 + np;
  18988. var d = base + 1;
  18989. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18990. var u0 = i * inverseSegments;
  18991. var v0 = j * inversePointLength;
  18992. var u1 = u0 + inverseSegments;
  18993. var v1 = v0 + inversePointLength;
  18994. this.faceVertexUvs[ 0 ].push( [
  18995. new THREE.Vector2( u0, v0 ),
  18996. new THREE.Vector2( u1, v0 ),
  18997. new THREE.Vector2( u1, v1 ),
  18998. new THREE.Vector2( u0, v1 )
  18999. ] );
  19000. }
  19001. }
  19002. this.mergeVertices();
  19003. this.computeCentroids();
  19004. this.computeFaceNormals();
  19005. this.computeVertexNormals();
  19006. };
  19007. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19008. /**
  19009. * @author mrdoob / http://mrdoob.com/
  19010. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19011. */
  19012. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19013. THREE.Geometry.call( this );
  19014. this.width = width;
  19015. this.height = height;
  19016. this.widthSegments = widthSegments || 1;
  19017. this.heightSegments = heightSegments || 1;
  19018. var ix, iz;
  19019. var width_half = width / 2;
  19020. var height_half = height / 2;
  19021. var gridX = this.widthSegments;
  19022. var gridZ = this.heightSegments;
  19023. var gridX1 = gridX + 1;
  19024. var gridZ1 = gridZ + 1;
  19025. var segment_width = this.width / gridX;
  19026. var segment_height = this.height / gridZ;
  19027. var normal = new THREE.Vector3( 0, 0, 1 );
  19028. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19029. for ( ix = 0; ix < gridX1; ix ++ ) {
  19030. var x = ix * segment_width - width_half;
  19031. var y = iz * segment_height - height_half;
  19032. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19033. }
  19034. }
  19035. for ( iz = 0; iz < gridZ; iz ++ ) {
  19036. for ( ix = 0; ix < gridX; ix ++ ) {
  19037. var a = ix + gridX1 * iz;
  19038. var b = ix + gridX1 * ( iz + 1 );
  19039. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19040. var d = ( ix + 1 ) + gridX1 * iz;
  19041. var face = new THREE.Face4( a, b, c, d );
  19042. face.normal.copy( normal );
  19043. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  19044. this.faces.push( face );
  19045. this.faceVertexUvs[ 0 ].push( [
  19046. new THREE.Vector2( ix / gridX, 1 - iz / gridZ ),
  19047. new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  19048. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  19049. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  19050. ] );
  19051. }
  19052. }
  19053. this.computeCentroids();
  19054. };
  19055. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19056. /**
  19057. * @author mrdoob / http://mrdoob.com/
  19058. */
  19059. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19060. THREE.Geometry.call( this );
  19061. this.radius = radius || 50;
  19062. this.widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19063. this.heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19064. phiStart = phiStart !== undefined ? phiStart : 0;
  19065. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19066. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19067. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19068. var x, y, vertices = [], uvs = [];
  19069. for ( y = 0; y <= this.heightSegments; y ++ ) {
  19070. var verticesRow = [];
  19071. var uvsRow = [];
  19072. for ( x = 0; x <= this.widthSegments; x ++ ) {
  19073. var u = x / this.widthSegments;
  19074. var v = y / this.heightSegments;
  19075. var vertex = new THREE.Vector3();
  19076. vertex.x = - this.radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19077. vertex.y = this.radius * Math.cos( thetaStart + v * thetaLength );
  19078. vertex.z = this.radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19079. this.vertices.push( vertex );
  19080. verticesRow.push( this.vertices.length - 1 );
  19081. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19082. }
  19083. vertices.push( verticesRow );
  19084. uvs.push( uvsRow );
  19085. }
  19086. for ( y = 0; y < this.heightSegments; y ++ ) {
  19087. for ( x = 0; x < this.widthSegments; x ++ ) {
  19088. var v1 = vertices[ y ][ x + 1 ];
  19089. var v2 = vertices[ y ][ x ];
  19090. var v3 = vertices[ y + 1 ][ x ];
  19091. var v4 = vertices[ y + 1 ][ x + 1 ];
  19092. var n1 = this.vertices[ v1 ].clone().normalize();
  19093. var n2 = this.vertices[ v2 ].clone().normalize();
  19094. var n3 = this.vertices[ v3 ].clone().normalize();
  19095. var n4 = this.vertices[ v4 ].clone().normalize();
  19096. var uv1 = uvs[ y ][ x + 1 ].clone();
  19097. var uv2 = uvs[ y ][ x ].clone();
  19098. var uv3 = uvs[ y + 1 ][ x ].clone();
  19099. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19100. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  19101. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19102. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19103. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  19104. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19105. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19106. } else {
  19107. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  19108. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  19109. }
  19110. }
  19111. }
  19112. this.computeCentroids();
  19113. this.computeFaceNormals();
  19114. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19115. };
  19116. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19117. /**
  19118. * @author zz85 / http://www.lab4games.net/zz85/blog
  19119. * @author alteredq / http://alteredqualia.com/
  19120. *
  19121. * For creating 3D text geometry in three.js
  19122. *
  19123. * Text = 3D Text
  19124. *
  19125. * parameters = {
  19126. * size: <float>, // size of the text
  19127. * height: <float>, // thickness to extrude text
  19128. * curveSegments: <int>, // number of points on the curves
  19129. *
  19130. * font: <string>, // font name
  19131. * weight: <string>, // font weight (normal, bold)
  19132. * style: <string>, // font style (normal, italics)
  19133. *
  19134. * bevelEnabled: <bool>, // turn on bevel
  19135. * bevelThickness: <float>, // how deep into text bevel goes
  19136. * bevelSize: <float>, // how far from text outline is bevel
  19137. * }
  19138. *
  19139. */
  19140. /* Usage Examples
  19141. // TextGeometry wrapper
  19142. var text3d = new TextGeometry( text, options );
  19143. // Complete manner
  19144. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19145. var text3d = new ExtrudeGeometry( textShapes, options );
  19146. */
  19147. THREE.TextGeometry = function ( text, parameters ) {
  19148. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19149. // translate parameters to ExtrudeGeometry API
  19150. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19151. // defaults
  19152. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19153. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19154. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19155. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19156. };
  19157. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19158. /**
  19159. * @author oosmoxiecode
  19160. * @author mrdoob / http://mrdoob.com/
  19161. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19162. */
  19163. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19164. THREE.Geometry.call( this );
  19165. var scope = this;
  19166. this.radius = radius || 100;
  19167. this.tube = tube || 40;
  19168. this.radialSegments = radialSegments || 8;
  19169. this.tubularSegments = tubularSegments || 6;
  19170. this.arc = arc || Math.PI * 2;
  19171. var center = new THREE.Vector3(), uvs = [], normals = [];
  19172. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  19173. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  19174. var u = i / this.tubularSegments * this.arc;
  19175. var v = j / this.radialSegments * Math.PI * 2;
  19176. center.x = this.radius * Math.cos( u );
  19177. center.y = this.radius * Math.sin( u );
  19178. var vertex = new THREE.Vector3();
  19179. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  19180. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  19181. vertex.z = this.tube * Math.sin( v );
  19182. this.vertices.push( vertex );
  19183. uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
  19184. normals.push( vertex.clone().sub( center ).normalize() );
  19185. }
  19186. }
  19187. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  19188. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  19189. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  19190. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19191. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  19192. var d = ( this.tubularSegments + 1 ) * j + i;
  19193. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  19194. face.normal.add( normals[ a ] );
  19195. face.normal.add( normals[ b ] );
  19196. face.normal.add( normals[ c ] );
  19197. face.normal.add( normals[ d ] );
  19198. face.normal.normalize();
  19199. this.faces.push( face );
  19200. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19201. }
  19202. }
  19203. this.computeCentroids();
  19204. };
  19205. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19206. /**
  19207. * @author oosmoxiecode
  19208. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19209. */
  19210. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19211. THREE.Geometry.call( this );
  19212. var scope = this;
  19213. this.radius = radius || 100;
  19214. this.tube = tube || 40;
  19215. this.radialSegments = radialSegments || 64;
  19216. this.tubularSegments = tubularSegments || 8;
  19217. this.p = p || 2;
  19218. this.q = q || 3;
  19219. this.heightScale = heightScale || 1;
  19220. this.grid = new Array( this.radialSegments );
  19221. var tang = new THREE.Vector3();
  19222. var n = new THREE.Vector3();
  19223. var bitan = new THREE.Vector3();
  19224. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19225. this.grid[ i ] = new Array( this.tubularSegments );
  19226. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19227. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  19228. var v = j / this.tubularSegments * 2 * Math.PI;
  19229. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  19230. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  19231. var cx, cy;
  19232. tang.subVectors( p2, p1 );
  19233. n.addVectors( p2, p1 );
  19234. bitan.crossVectors( tang, n );
  19235. n.crossVectors( bitan, tang );
  19236. bitan.normalize();
  19237. n.normalize();
  19238. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19239. cy = this.tube * Math.sin( v );
  19240. p1.x += cx * n.x + cy * bitan.x;
  19241. p1.y += cx * n.y + cy * bitan.y;
  19242. p1.z += cx * n.z + cy * bitan.z;
  19243. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  19244. }
  19245. }
  19246. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19247. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19248. var ip = ( i + 1 ) % this.radialSegments;
  19249. var jp = ( j + 1 ) % this.tubularSegments;
  19250. var a = this.grid[ i ][ j ];
  19251. var b = this.grid[ ip ][ j ];
  19252. var c = this.grid[ ip ][ jp ];
  19253. var d = this.grid[ i ][ jp ];
  19254. var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
  19255. var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  19256. var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19257. var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19258. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19259. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  19260. }
  19261. }
  19262. this.computeCentroids();
  19263. this.computeFaceNormals();
  19264. this.computeVertexNormals();
  19265. function vert( x, y, z ) {
  19266. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19267. }
  19268. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  19269. var cu = Math.cos( u );
  19270. var cv = Math.cos( v );
  19271. var su = Math.sin( u );
  19272. var quOverP = in_q / in_p * u;
  19273. var cs = Math.cos( quOverP );
  19274. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19275. var ty = radius * ( 2 + cs ) * su * 0.5;
  19276. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19277. return new THREE.Vector3( tx, ty, tz );
  19278. }
  19279. };
  19280. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19281. /**
  19282. * @author WestLangley / https://github.com/WestLangley
  19283. * @author zz85 / https://github.com/zz85
  19284. * @author miningold / https://github.com/miningold
  19285. *
  19286. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19287. *
  19288. * Creates a tube which extrudes along a 3d spline
  19289. *
  19290. * Uses parallel transport frames as described in
  19291. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19292. */
  19293. THREE.TubeGeometry = function( path, segments, radius, radiusSegments, closed, debug ) {
  19294. THREE.Geometry.call( this );
  19295. this.path = path;
  19296. this.segments = segments || 64;
  19297. this.radius = radius || 1;
  19298. this.radiusSegments = radiusSegments || 8;
  19299. this.closed = closed || false;
  19300. if ( debug ) this.debug = new THREE.Object3D();
  19301. this.grid = [];
  19302. var scope = this,
  19303. tangent,
  19304. normal,
  19305. binormal,
  19306. numpoints = this.segments + 1,
  19307. x, y, z,
  19308. tx, ty, tz,
  19309. u, v,
  19310. cx, cy,
  19311. pos, pos2 = new THREE.Vector3(),
  19312. i, j,
  19313. ip, jp,
  19314. a, b, c, d,
  19315. uva, uvb, uvc, uvd;
  19316. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  19317. tangents = frames.tangents,
  19318. normals = frames.normals,
  19319. binormals = frames.binormals;
  19320. // proxy internals
  19321. this.tangents = tangents;
  19322. this.normals = normals;
  19323. this.binormals = binormals;
  19324. function vert( x, y, z ) {
  19325. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19326. }
  19327. // consruct the grid
  19328. for ( i = 0; i < numpoints; i++ ) {
  19329. this.grid[ i ] = [];
  19330. u = i / ( numpoints - 1 );
  19331. pos = path.getPointAt( u );
  19332. tangent = tangents[ i ];
  19333. normal = normals[ i ];
  19334. binormal = binormals[ i ];
  19335. if ( this.debug ) {
  19336. this.debug.add( new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff ) );
  19337. this.debug.add( new THREE.ArrowHelper(normal, pos, radius, 0xff0000 ) );
  19338. this.debug.add( new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00 ) );
  19339. }
  19340. for ( j = 0; j < this.radiusSegments; j++ ) {
  19341. v = j / this.radiusSegments * 2 * Math.PI;
  19342. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19343. cy = this.radius * Math.sin( v );
  19344. pos2.copy( pos );
  19345. pos2.x += cx * normal.x + cy * binormal.x;
  19346. pos2.y += cx * normal.y + cy * binormal.y;
  19347. pos2.z += cx * normal.z + cy * binormal.z;
  19348. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  19349. }
  19350. }
  19351. // construct the mesh
  19352. for ( i = 0; i < this.segments; i++ ) {
  19353. for ( j = 0; j < this.radiusSegments; j++ ) {
  19354. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  19355. jp = (j + 1) % this.radiusSegments;
  19356. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  19357. b = this.grid[ ip ][ j ];
  19358. c = this.grid[ ip ][ jp ];
  19359. d = this.grid[ i ][ jp ];
  19360. uva = new THREE.Vector2( i / this.segments, j / this.radiusSegments );
  19361. uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radiusSegments );
  19362. uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radiusSegments );
  19363. uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radiusSegments );
  19364. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19365. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  19366. }
  19367. }
  19368. this.computeCentroids();
  19369. this.computeFaceNormals();
  19370. this.computeVertexNormals();
  19371. };
  19372. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19373. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19374. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  19375. var tangent = new THREE.Vector3(),
  19376. normal = new THREE.Vector3(),
  19377. binormal = new THREE.Vector3(),
  19378. tangents = [],
  19379. normals = [],
  19380. binormals = [],
  19381. vec = new THREE.Vector3(),
  19382. mat = new THREE.Matrix4(),
  19383. numpoints = segments + 1,
  19384. theta,
  19385. epsilon = 0.0001,
  19386. smallest,
  19387. tx, ty, tz,
  19388. i, u, v;
  19389. // expose internals
  19390. this.tangents = tangents;
  19391. this.normals = normals;
  19392. this.binormals = binormals;
  19393. // compute the tangent vectors for each segment on the path
  19394. for ( i = 0; i < numpoints; i++ ) {
  19395. u = i / ( numpoints - 1 );
  19396. tangents[ i ] = path.getTangentAt( u );
  19397. tangents[ i ].normalize();
  19398. }
  19399. initialNormal3();
  19400. function initialNormal1(lastBinormal) {
  19401. // fixed start binormal. Has dangers of 0 vectors
  19402. normals[ 0 ] = new THREE.Vector3();
  19403. binormals[ 0 ] = new THREE.Vector3();
  19404. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19405. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  19406. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19407. }
  19408. function initialNormal2() {
  19409. // This uses the Frenet-Serret formula for deriving binormal
  19410. var t2 = path.getTangentAt( epsilon );
  19411. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  19412. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  19413. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  19414. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  19415. }
  19416. function initialNormal3() {
  19417. // select an initial normal vector perpenicular to the first tangent vector,
  19418. // and in the direction of the smallest tangent xyz component
  19419. normals[ 0 ] = new THREE.Vector3();
  19420. binormals[ 0 ] = new THREE.Vector3();
  19421. smallest = Number.MAX_VALUE;
  19422. tx = Math.abs( tangents[ 0 ].x );
  19423. ty = Math.abs( tangents[ 0 ].y );
  19424. tz = Math.abs( tangents[ 0 ].z );
  19425. if ( tx <= smallest ) {
  19426. smallest = tx;
  19427. normal.set( 1, 0, 0 );
  19428. }
  19429. if ( ty <= smallest ) {
  19430. smallest = ty;
  19431. normal.set( 0, 1, 0 );
  19432. }
  19433. if ( tz <= smallest ) {
  19434. normal.set( 0, 0, 1 );
  19435. }
  19436. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  19437. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  19438. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  19439. }
  19440. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19441. for ( i = 1; i < numpoints; i++ ) {
  19442. normals[ i ] = normals[ i-1 ].clone();
  19443. binormals[ i ] = binormals[ i-1 ].clone();
  19444. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  19445. if ( vec.length() > epsilon ) {
  19446. vec.normalize();
  19447. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  19448. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  19449. }
  19450. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19451. }
  19452. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19453. if ( closed ) {
  19454. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  19455. theta /= ( numpoints - 1 );
  19456. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  19457. theta = -theta;
  19458. }
  19459. for ( i = 1; i < numpoints; i++ ) {
  19460. // twist a little...
  19461. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  19462. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  19463. }
  19464. }
  19465. };
  19466. /**
  19467. * @author clockworkgeek / https://github.com/clockworkgeek
  19468. * @author timothypratley / https://github.com/timothypratley
  19469. */
  19470. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  19471. THREE.Geometry.call( this );
  19472. radius = radius || 1;
  19473. detail = detail || 0;
  19474. var that = this;
  19475. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  19476. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  19477. }
  19478. var midpoints = [], p = this.vertices;
  19479. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19480. make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );
  19481. }
  19482. this.mergeVertices();
  19483. // Apply radius
  19484. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19485. this.vertices[ i ].multiplyScalar( radius );
  19486. }
  19487. // Project vector onto sphere's surface
  19488. function prepare( vector ) {
  19489. var vertex = vector.normalize().clone();
  19490. vertex.index = that.vertices.push( vertex ) - 1;
  19491. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19492. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19493. var v = inclination( vector ) / Math.PI + 0.5;
  19494. vertex.uv = new THREE.Vector2( u, 1 - v );
  19495. return vertex;
  19496. }
  19497. // Approximate a curved face with recursively sub-divided triangles.
  19498. function make( v1, v2, v3, detail ) {
  19499. if ( detail < 1 ) {
  19500. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19501. face.centroid.add( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  19502. face.normal = face.centroid.clone().normalize();
  19503. that.faces.push( face );
  19504. var azi = azimuth( face.centroid );
  19505. that.faceVertexUvs[ 0 ].push( [
  19506. correctUV( v1.uv, v1, azi ),
  19507. correctUV( v2.uv, v2, azi ),
  19508. correctUV( v3.uv, v3, azi )
  19509. ] );
  19510. } else {
  19511. detail -= 1;
  19512. // split triangle into 4 smaller triangles
  19513. make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
  19514. make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
  19515. make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
  19516. make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant
  19517. }
  19518. }
  19519. function midpoint( v1, v2 ) {
  19520. if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
  19521. if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];
  19522. var mid = midpoints[ v1.index ][ v2.index ];
  19523. if ( mid === undefined ) {
  19524. // generate mean point and project to surface with prepare()
  19525. midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
  19526. new THREE.Vector3().addVectors( v1, v2 ).divideScalar( 2 )
  19527. );
  19528. }
  19529. return mid;
  19530. }
  19531. // Angle around the Y axis, counter-clockwise when looking from above.
  19532. function azimuth( vector ) {
  19533. return Math.atan2( vector.z, -vector.x );
  19534. }
  19535. // Angle above the XZ plane.
  19536. function inclination( vector ) {
  19537. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19538. }
  19539. // Texture fixing helper. Spheres have some odd behaviours.
  19540. function correctUV( uv, vector, azimuth ) {
  19541. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  19542. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  19543. return uv;
  19544. }
  19545. this.computeCentroids();
  19546. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19547. };
  19548. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19549. /**
  19550. * @author timothypratley / https://github.com/timothypratley
  19551. */
  19552. THREE.IcosahedronGeometry = function ( radius, detail ) {
  19553. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19554. var vertices = [
  19555. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  19556. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  19557. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  19558. ];
  19559. var faces = [
  19560. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  19561. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  19562. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  19563. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  19564. ];
  19565. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19566. };
  19567. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19568. /**
  19569. * @author timothypratley / https://github.com/timothypratley
  19570. */
  19571. THREE.OctahedronGeometry = function ( radius, detail ) {
  19572. var vertices = [
  19573. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  19574. ];
  19575. var faces = [
  19576. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  19577. ];
  19578. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19579. };
  19580. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19581. /**
  19582. * @author timothypratley / https://github.com/timothypratley
  19583. */
  19584. THREE.TetrahedronGeometry = function ( radius, detail ) {
  19585. var vertices = [
  19586. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  19587. ];
  19588. var faces = [
  19589. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  19590. ];
  19591. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19592. };
  19593. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19594. /**
  19595. * @author zz85 / https://github.com/zz85
  19596. * Parametric Surfaces Geometry
  19597. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  19598. *
  19599. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  19600. *
  19601. */
  19602. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  19603. THREE.Geometry.call( this );
  19604. var verts = this.vertices;
  19605. var faces = this.faces;
  19606. var uvs = this.faceVertexUvs[ 0 ];
  19607. useTris = (useTris === undefined) ? false : useTris;
  19608. var i, il, j, p;
  19609. var u, v;
  19610. var stackCount = stacks + 1;
  19611. var sliceCount = slices + 1;
  19612. for ( i = 0; i <= stacks; i ++ ) {
  19613. v = i / stacks;
  19614. for ( j = 0; j <= slices; j ++ ) {
  19615. u = j / slices;
  19616. p = func( u, v );
  19617. verts.push( p );
  19618. }
  19619. }
  19620. var a, b, c, d;
  19621. var uva, uvb, uvc, uvd;
  19622. for ( i = 0; i < stacks; i ++ ) {
  19623. for ( j = 0; j < slices; j ++ ) {
  19624. a = i * sliceCount + j;
  19625. b = i * sliceCount + j + 1;
  19626. c = (i + 1) * sliceCount + j;
  19627. d = (i + 1) * sliceCount + j + 1;
  19628. uva = new THREE.Vector2( j / slices, i / stacks );
  19629. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  19630. uvc = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  19631. uvd = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  19632. if ( useTris ) {
  19633. faces.push( new THREE.Face3( a, b, c ) );
  19634. faces.push( new THREE.Face3( b, d, c ) );
  19635. uvs.push( [ uva, uvb, uvc ] );
  19636. uvs.push( [ uvb, uvd, uvc ] );
  19637. } else {
  19638. faces.push( new THREE.Face4( a, b, d, c ) );
  19639. uvs.push( [ uva, uvb, uvd, uvc ] );
  19640. }
  19641. }
  19642. }
  19643. // console.log(this);
  19644. // magic bullet
  19645. // var diff = this.mergeVertices();
  19646. // console.log('removed ', diff, ' vertices by merging');
  19647. this.computeCentroids();
  19648. this.computeFaceNormals();
  19649. this.computeVertexNormals();
  19650. };
  19651. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19652. /**
  19653. * @author qiao / https://github.com/qiao
  19654. * @fileoverview This is a convex hull generator using the incremental method.
  19655. * The complexity is O(n^2) where n is the number of vertices.
  19656. * O(nlogn) algorithms do exist, but they are much more complicated.
  19657. *
  19658. * Benchmark:
  19659. *
  19660. * Platform: CPU: P7350 @2.00GHz Engine: V8
  19661. *
  19662. * Num Vertices Time(ms)
  19663. *
  19664. * 10 1
  19665. * 20 3
  19666. * 30 19
  19667. * 40 48
  19668. * 50 107
  19669. */
  19670. THREE.ConvexGeometry = function( vertices ) {
  19671. THREE.Geometry.call( this );
  19672. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  19673. for ( var i = 3; i < vertices.length; i++ ) {
  19674. addPoint( i );
  19675. }
  19676. function addPoint( vertexId ) {
  19677. var vertex = vertices[ vertexId ].clone();
  19678. var mag = vertex.length();
  19679. vertex.x += mag * randomOffset();
  19680. vertex.y += mag * randomOffset();
  19681. vertex.z += mag * randomOffset();
  19682. var hole = [];
  19683. for ( var f = 0; f < faces.length; ) {
  19684. var face = faces[ f ];
  19685. // for each face, if the vertex can see it,
  19686. // then we try to add the face's edges into the hole.
  19687. if ( visible( face, vertex ) ) {
  19688. for ( var e = 0; e < 3; e++ ) {
  19689. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  19690. var boundary = true;
  19691. // remove duplicated edges.
  19692. for ( var h = 0; h < hole.length; h++ ) {
  19693. if ( equalEdge( hole[ h ], edge ) ) {
  19694. hole[ h ] = hole[ hole.length - 1 ];
  19695. hole.pop();
  19696. boundary = false;
  19697. break;
  19698. }
  19699. }
  19700. if ( boundary ) {
  19701. hole.push( edge );
  19702. }
  19703. }
  19704. // remove faces[ f ]
  19705. faces[ f ] = faces[ faces.length - 1 ];
  19706. faces.pop();
  19707. } else { // not visible
  19708. f++;
  19709. }
  19710. }
  19711. // construct the new faces formed by the edges of the hole and the vertex
  19712. for ( var h = 0; h < hole.length; h++ ) {
  19713. faces.push( [
  19714. hole[ h ][ 0 ],
  19715. hole[ h ][ 1 ],
  19716. vertexId
  19717. ] );
  19718. }
  19719. }
  19720. /**
  19721. * Whether the face is visible from the vertex
  19722. */
  19723. function visible( face, vertex ) {
  19724. var va = vertices[ face[ 0 ] ];
  19725. var vb = vertices[ face[ 1 ] ];
  19726. var vc = vertices[ face[ 2 ] ];
  19727. var n = normal( va, vb, vc );
  19728. // distance from face to origin
  19729. var dist = n.dot( va );
  19730. return n.dot( vertex ) >= dist;
  19731. }
  19732. /**
  19733. * Face normal
  19734. */
  19735. function normal( va, vb, vc ) {
  19736. var cb = new THREE.Vector3();
  19737. var ab = new THREE.Vector3();
  19738. cb.subVectors( vc, vb );
  19739. ab.subVectors( va, vb );
  19740. cb.cross( ab );
  19741. cb.normalize();
  19742. return cb;
  19743. }
  19744. /**
  19745. * Detect whether two edges are equal.
  19746. * Note that when constructing the convex hull, two same edges can only
  19747. * be of the negative direction.
  19748. */
  19749. function equalEdge( ea, eb ) {
  19750. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  19751. }
  19752. /**
  19753. * Create a random offset between -1e-6 and 1e-6.
  19754. */
  19755. function randomOffset() {
  19756. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  19757. }
  19758. /**
  19759. * XXX: Not sure if this is the correct approach. Need someone to review.
  19760. */
  19761. function vertexUv( vertex ) {
  19762. var mag = vertex.length();
  19763. return new THREE.Vector2( vertex.x / mag, vertex.y / mag );
  19764. }
  19765. // Push vertices into `this.vertices`, skipping those inside the hull
  19766. var id = 0;
  19767. var newId = new Array( vertices.length ); // map from old vertex id to new id
  19768. for ( var i = 0; i < faces.length; i++ ) {
  19769. var face = faces[ i ];
  19770. for ( var j = 0; j < 3; j++ ) {
  19771. if ( newId[ face[ j ] ] === undefined ) {
  19772. newId[ face[ j ] ] = id++;
  19773. this.vertices.push( vertices[ face[ j ] ] );
  19774. }
  19775. face[ j ] = newId[ face[ j ] ];
  19776. }
  19777. }
  19778. // Convert faces into instances of THREE.Face3
  19779. for ( var i = 0; i < faces.length; i++ ) {
  19780. this.faces.push( new THREE.Face3(
  19781. faces[ i ][ 0 ],
  19782. faces[ i ][ 1 ],
  19783. faces[ i ][ 2 ]
  19784. ) );
  19785. }
  19786. // Compute UVs
  19787. for ( var i = 0; i < this.faces.length; i++ ) {
  19788. var face = this.faces[ i ];
  19789. this.faceVertexUvs[ 0 ].push( [
  19790. vertexUv( this.vertices[ face.a ] ),
  19791. vertexUv( this.vertices[ face.b ] ),
  19792. vertexUv( this.vertices[ face.c ])
  19793. ] );
  19794. }
  19795. this.computeCentroids();
  19796. this.computeFaceNormals();
  19797. this.computeVertexNormals();
  19798. };
  19799. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19800. /**
  19801. * @author sroucheray / http://sroucheray.org/
  19802. * @author mrdoob / http://mrdoob.com/
  19803. */
  19804. THREE.AxisHelper = function ( size ) {
  19805. var geometry = new THREE.Geometry();
  19806. geometry.vertices.push(
  19807. new THREE.Vector3(), new THREE.Vector3( size || 1, 0, 0 ),
  19808. new THREE.Vector3(), new THREE.Vector3( 0, size || 1, 0 ),
  19809. new THREE.Vector3(), new THREE.Vector3( 0, 0, size || 1 )
  19810. );
  19811. geometry.colors.push(
  19812. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  19813. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  19814. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  19815. );
  19816. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  19817. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  19818. };
  19819. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  19820. /**
  19821. * @author WestLangley / http://github.com/WestLangley
  19822. * @author zz85 / https://github.com/zz85
  19823. * @author bhouston / https://exocortex.com
  19824. *
  19825. * Creates an arrow for visualizing directions
  19826. *
  19827. * Parameters:
  19828. * dir - Vector3
  19829. * origin - Vector3
  19830. * length - Number
  19831. * hex - color in hex value
  19832. */
  19833. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  19834. THREE.Object3D.call( this );
  19835. if ( length === undefined ) length = 20;
  19836. if ( hex === undefined ) hex = 0xffff00;
  19837. var lineGeometry = new THREE.Geometry();
  19838. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  19839. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  19840. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  19841. this.add( this.line );
  19842. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  19843. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  19844. this.cone.position.set( 0, 1, 0 );
  19845. this.add( this.cone );
  19846. if ( origin instanceof THREE.Vector3 ) this.position = origin;
  19847. this.setDirection( dir );
  19848. this.setLength( length );
  19849. };
  19850. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  19851. THREE.ArrowHelper.prototype.setDirection = function ( dir ) {
  19852. var d = THREE.ArrowHelper.__v1.copy( dir ).normalize();
  19853. if ( d.y > 0.999 ) {
  19854. this.rotation.set( 0, 0, 0 );
  19855. } else if ( d.y < - 0.999 ) {
  19856. this.rotation.set( Math.PI, 0, 0 );
  19857. } else {
  19858. var axis = THREE.ArrowHelper.__v2.set( d.z, 0, - d.x ).normalize();
  19859. var radians = Math.acos( d.y );
  19860. var quaternion = THREE.ArrowHelper.__q1.setFromAxisAngle( axis, radians );
  19861. this.rotation.setEulerFromQuaternion( quaternion, this.eulerOrder );
  19862. }
  19863. };
  19864. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  19865. this.scale.set( length, length, length );
  19866. };
  19867. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  19868. this.line.material.color.setHex( hex );
  19869. this.cone.material.color.setHex( hex );
  19870. };
  19871. THREE.ArrowHelper.__v1 = new THREE.Vector3();
  19872. THREE.ArrowHelper.__v2 = new THREE.Vector3();
  19873. THREE.ArrowHelper.__q1 = new THREE.Quaternion();
  19874. /**
  19875. * @author alteredq / http://alteredqualia.com/
  19876. *
  19877. * - shows frustum, line of sight and up of the camera
  19878. * - suitable for fast updates
  19879. * - based on frustum visualization in lightgl.js shadowmap example
  19880. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  19881. */
  19882. THREE.CameraHelper = function ( camera ) {
  19883. THREE.Line.call( this );
  19884. var scope = this;
  19885. this.geometry = new THREE.Geometry();
  19886. this.material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  19887. this.type = THREE.LinePieces;
  19888. this.matrixWorld = camera.matrixWorld;
  19889. this.matrixAutoUpdate = false;
  19890. this.pointMap = {};
  19891. // colors
  19892. var hexFrustum = 0xffaa00;
  19893. var hexCone = 0xff0000;
  19894. var hexUp = 0x00aaff;
  19895. var hexTarget = 0xffffff;
  19896. var hexCross = 0x333333;
  19897. // near
  19898. addLine( "n1", "n2", hexFrustum );
  19899. addLine( "n2", "n4", hexFrustum );
  19900. addLine( "n4", "n3", hexFrustum );
  19901. addLine( "n3", "n1", hexFrustum );
  19902. // far
  19903. addLine( "f1", "f2", hexFrustum );
  19904. addLine( "f2", "f4", hexFrustum );
  19905. addLine( "f4", "f3", hexFrustum );
  19906. addLine( "f3", "f1", hexFrustum );
  19907. // sides
  19908. addLine( "n1", "f1", hexFrustum );
  19909. addLine( "n2", "f2", hexFrustum );
  19910. addLine( "n3", "f3", hexFrustum );
  19911. addLine( "n4", "f4", hexFrustum );
  19912. // cone
  19913. addLine( "p", "n1", hexCone );
  19914. addLine( "p", "n2", hexCone );
  19915. addLine( "p", "n3", hexCone );
  19916. addLine( "p", "n4", hexCone );
  19917. // up
  19918. addLine( "u1", "u2", hexUp );
  19919. addLine( "u2", "u3", hexUp );
  19920. addLine( "u3", "u1", hexUp );
  19921. // target
  19922. addLine( "c", "t", hexTarget );
  19923. addLine( "p", "c", hexCross );
  19924. // cross
  19925. addLine( "cn1", "cn2", hexCross );
  19926. addLine( "cn3", "cn4", hexCross );
  19927. addLine( "cf1", "cf2", hexCross );
  19928. addLine( "cf3", "cf4", hexCross );
  19929. this.camera = camera;
  19930. function addLine( a, b, hex ) {
  19931. addPoint( a, hex );
  19932. addPoint( b, hex );
  19933. }
  19934. function addPoint( id, hex ) {
  19935. scope.geometry.vertices.push( new THREE.Vector3() );
  19936. scope.geometry.colors.push( new THREE.Color( hex ) );
  19937. if ( scope.pointMap[ id ] === undefined ) scope.pointMap[ id ] = [];
  19938. scope.pointMap[ id ].push( scope.geometry.vertices.length - 1 );
  19939. }
  19940. this.update( camera );
  19941. };
  19942. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  19943. THREE.CameraHelper.prototype.update = function () {
  19944. var scope = this;
  19945. var w = 1, h = 1;
  19946. // we need just camera projection matrix
  19947. // world matrix must be identity
  19948. THREE.CameraHelper.__c.projectionMatrix.copy( this.camera.projectionMatrix );
  19949. // center / target
  19950. setPoint( "c", 0, 0, -1 );
  19951. setPoint( "t", 0, 0, 1 );
  19952. // near
  19953. setPoint( "n1", -w, -h, -1 );
  19954. setPoint( "n2", w, -h, -1 );
  19955. setPoint( "n3", -w, h, -1 );
  19956. setPoint( "n4", w, h, -1 );
  19957. // far
  19958. setPoint( "f1", -w, -h, 1 );
  19959. setPoint( "f2", w, -h, 1 );
  19960. setPoint( "f3", -w, h, 1 );
  19961. setPoint( "f4", w, h, 1 );
  19962. // up
  19963. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  19964. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  19965. setPoint( "u3", 0, h * 2, -1 );
  19966. // cross
  19967. setPoint( "cf1", -w, 0, 1 );
  19968. setPoint( "cf2", w, 0, 1 );
  19969. setPoint( "cf3", 0, -h, 1 );
  19970. setPoint( "cf4", 0, h, 1 );
  19971. setPoint( "cn1", -w, 0, -1 );
  19972. setPoint( "cn2", w, 0, -1 );
  19973. setPoint( "cn3", 0, -h, -1 );
  19974. setPoint( "cn4", 0, h, -1 );
  19975. function setPoint( point, x, y, z ) {
  19976. THREE.CameraHelper.__v.set( x, y, z );
  19977. THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
  19978. var points = scope.pointMap[ point ];
  19979. if ( points !== undefined ) {
  19980. for ( var i = 0, il = points.length; i < il; i ++ ) {
  19981. scope.geometry.vertices[ points[ i ] ].copy( THREE.CameraHelper.__v );
  19982. }
  19983. }
  19984. }
  19985. this.geometry.verticesNeedUpdate = true;
  19986. };
  19987. THREE.CameraHelper.__projector = new THREE.Projector();
  19988. THREE.CameraHelper.__v = new THREE.Vector3();
  19989. THREE.CameraHelper.__c = new THREE.Camera();
  19990. /**
  19991. * @author alteredq / http://alteredqualia.com/
  19992. *
  19993. * - shows directional light color, intensity, position, orientation and target
  19994. */
  19995. THREE.DirectionalLightHelper = function ( light, sphereSize ) {
  19996. THREE.Object3D.call( this );
  19997. this.light = light;
  19998. // position
  19999. this.position = light.position;
  20000. // direction
  20001. this.direction = new THREE.Vector3();
  20002. this.direction.subVectors( light.target.position, light.position );
  20003. // color
  20004. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20005. this.color = light.color.clone();
  20006. this.color.multiplyScalar( intensity );
  20007. var hexColor = this.color.getHex();
  20008. // light helper
  20009. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20010. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20011. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20012. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20013. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20014. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20015. this.add( this.lightSphere );
  20016. this.add( this.lightRays );
  20017. this.lightSphere.properties.isGizmo = true;
  20018. this.lightSphere.properties.gizmoSubject = light;
  20019. this.lightSphere.properties.gizmoRoot = this;
  20020. // light target helper
  20021. this.targetSphere = null;
  20022. if ( light.target.properties.targetInverse !== undefined ) {
  20023. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  20024. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  20025. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  20026. this.targetSphere.position = light.target.position;
  20027. this.targetSphere.properties.isGizmo = true;
  20028. this.targetSphere.properties.gizmoSubject = light.target;
  20029. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  20030. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20031. var lineGeometry = new THREE.Geometry();
  20032. lineGeometry.vertices.push( this.position.clone() );
  20033. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  20034. lineGeometry.computeLineDistances();
  20035. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  20036. this.targetLine.properties.isGizmo = true;
  20037. }
  20038. //
  20039. this.properties.isGizmo = true;
  20040. }
  20041. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20042. THREE.DirectionalLightHelper.prototype.update = function () {
  20043. // update arrow orientation
  20044. // pointing from light to target
  20045. this.direction.subVectors( this.light.target.position, this.light.position );
  20046. // update arrow, spheres, rays and line colors to light color * light intensity
  20047. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20048. this.color.copy( this.light.color );
  20049. this.color.multiplyScalar( intensity );
  20050. this.lightSphere.material.color.copy( this.color );
  20051. this.lightRays.material.color.copy( this.color );
  20052. // Only update targetSphere and targetLine if available
  20053. if ( this.targetSphere !== null ) {
  20054. this.targetSphere.material.color.copy( this.color );
  20055. this.targetLine.material.color.copy( this.color );
  20056. // update target line vertices
  20057. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  20058. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  20059. this.targetLine.geometry.computeLineDistances();
  20060. this.targetLine.geometry.verticesNeedUpdate = true;
  20061. }
  20062. }
  20063. /**
  20064. * @author alteredq / http://alteredqualia.com/
  20065. *
  20066. * - shows hemisphere light intensity, sky and ground colors and directions
  20067. */
  20068. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  20069. THREE.Object3D.call( this );
  20070. this.light = light;
  20071. // position
  20072. this.position = light.position;
  20073. //
  20074. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20075. // sky color
  20076. this.color = light.color.clone();
  20077. this.color.multiplyScalar( intensity );
  20078. var hexColor = this.color.getHex();
  20079. // ground color
  20080. this.groundColor = light.groundColor.clone();
  20081. this.groundColor.multiplyScalar( intensity );
  20082. var hexColorGround = this.groundColor.getHex();
  20083. // double colored light bulb
  20084. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, 0, Math.PI * 0.5 );
  20085. var bulbGroundGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, Math.PI * 0.5, Math.PI );
  20086. var bulbSkyMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20087. var bulbGroundMaterial = new THREE.MeshBasicMaterial( { color: hexColorGround, fog: false } );
  20088. for ( var i = 0, il = bulbGeometry.faces.length; i < il; i ++ ) {
  20089. bulbGeometry.faces[ i ].materialIndex = 0;
  20090. }
  20091. for ( var i = 0, il = bulbGroundGeometry.faces.length; i < il; i ++ ) {
  20092. bulbGroundGeometry.faces[ i ].materialIndex = 1;
  20093. }
  20094. THREE.GeometryUtils.merge( bulbGeometry, bulbGroundGeometry );
  20095. this.lightSphere = new THREE.Mesh( bulbGeometry, new THREE.MeshFaceMaterial( [ bulbSkyMaterial, bulbGroundMaterial ] ) );
  20096. // arrows for sky and ground light directions
  20097. this.lightArrow = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * 1.1, 0 ), arrowLength, hexColor );
  20098. this.lightArrow.rotation.x = Math.PI;
  20099. this.lightArrowGround = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * -1.1, 0 ), arrowLength, hexColorGround );
  20100. var joint = new THREE.Object3D();
  20101. joint.rotation.x = -Math.PI * 0.5;
  20102. joint.add( this.lightSphere );
  20103. joint.add( this.lightArrow );
  20104. joint.add( this.lightArrowGround );
  20105. this.add( joint );
  20106. //
  20107. this.lightSphere.properties.isGizmo = true;
  20108. this.lightSphere.properties.gizmoSubject = light;
  20109. this.lightSphere.properties.gizmoRoot = this;
  20110. //
  20111. this.properties.isGizmo = true;
  20112. //
  20113. this.target = new THREE.Vector3();
  20114. this.lookAt( this.target );
  20115. }
  20116. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20117. THREE.HemisphereLightHelper.prototype.update = function () {
  20118. // update sphere sky and ground colors to light color * light intensity
  20119. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20120. this.color.copy( this.light.color );
  20121. this.color.multiplyScalar( intensity );
  20122. this.groundColor.copy( this.light.groundColor );
  20123. this.groundColor.multiplyScalar( intensity );
  20124. this.lightSphere.material.materials[ 0 ].color.copy( this.color );
  20125. this.lightSphere.material.materials[ 1 ].color.copy( this.groundColor );
  20126. this.lightArrow.setColor( this.color.getHex() );
  20127. this.lightArrowGround.setColor( this.groundColor.getHex() );
  20128. this.lookAt( this.target );
  20129. }
  20130. /**
  20131. * @author alteredq / http://alteredqualia.com/
  20132. *
  20133. * - shows point light color, intensity, position and distance
  20134. */
  20135. THREE.PointLightHelper = function ( light, sphereSize ) {
  20136. THREE.Object3D.call( this );
  20137. this.light = light;
  20138. // position
  20139. this.position = light.position;
  20140. // color
  20141. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20142. this.color = light.color.clone();
  20143. this.color.multiplyScalar( intensity );
  20144. var hexColor = this.color.getHex();
  20145. // light helper
  20146. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20147. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20148. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20149. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20150. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20151. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20152. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20153. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20154. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20155. var d = light.distance;
  20156. if ( d === 0.0 ) {
  20157. this.lightDistance.visible = false;
  20158. } else {
  20159. this.lightDistance.scale.set( d, d, d );
  20160. }
  20161. this.add( this.lightSphere );
  20162. this.add( this.lightRays );
  20163. this.add( this.lightDistance );
  20164. //
  20165. this.lightSphere.properties.isGizmo = true;
  20166. this.lightSphere.properties.gizmoSubject = light;
  20167. this.lightSphere.properties.gizmoRoot = this;
  20168. //
  20169. this.properties.isGizmo = true;
  20170. }
  20171. THREE.PointLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20172. THREE.PointLightHelper.prototype.update = function () {
  20173. // update sphere and rays colors to light color * light intensity
  20174. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20175. this.color.copy( this.light.color );
  20176. this.color.multiplyScalar( intensity );
  20177. this.lightSphere.material.color.copy( this.color );
  20178. this.lightRays.material.color.copy( this.color );
  20179. this.lightDistance.material.color.copy( this.color );
  20180. //
  20181. var d = this.light.distance;
  20182. if ( d === 0.0 ) {
  20183. this.lightDistance.visible = false;
  20184. } else {
  20185. this.lightDistance.visible = true;
  20186. this.lightDistance.scale.set( d, d, d );
  20187. }
  20188. }
  20189. /**
  20190. * @author alteredq / http://alteredqualia.com/
  20191. *
  20192. * - shows spot light color, intensity, position, orientation, light cone and target
  20193. */
  20194. THREE.SpotLightHelper = function ( light, sphereSize ) {
  20195. THREE.Object3D.call( this );
  20196. this.light = light;
  20197. // position
  20198. this.position = light.position;
  20199. // direction
  20200. this.direction = new THREE.Vector3();
  20201. this.direction.subVectors( light.target.position, light.position );
  20202. // color
  20203. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20204. this.color = light.color.clone();
  20205. this.color.multiplyScalar( intensity );
  20206. var hexColor = this.color.getHex();
  20207. // light helper
  20208. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20209. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20210. var coneGeometry = new THREE.CylinderGeometry( 0.0001, 1, 1, 8, 1, true );
  20211. var coneMatrix = new THREE.Matrix4();
  20212. coneMatrix.rotateX( -Math.PI/2 );
  20213. coneMatrix.translate( new THREE.Vector3( 0, -0.5, 0 ) );
  20214. coneGeometry.applyMatrix( coneMatrix );
  20215. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20216. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20217. var coneMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.3, transparent: true } );
  20218. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20219. this.lightCone = new THREE.Mesh( coneGeometry, coneMaterial );
  20220. var coneLength = light.distance ? light.distance : 10000;
  20221. var coneWidth = coneLength * Math.tan( light.angle * 0.5 ) * 2;
  20222. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  20223. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20224. this.gyroscope = new THREE.Gyroscope();
  20225. this.gyroscope.add( this.lightSphere );
  20226. this.gyroscope.add( this.lightRays );
  20227. this.add( this.gyroscope );
  20228. this.add( this.lightCone );
  20229. this.lookAt( light.target.position );
  20230. this.lightSphere.properties.isGizmo = true;
  20231. this.lightSphere.properties.gizmoSubject = light;
  20232. this.lightSphere.properties.gizmoRoot = this;
  20233. // light target helper
  20234. this.targetSphere = null;
  20235. if ( light.target.properties.targetInverse !== undefined ) {
  20236. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  20237. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  20238. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  20239. this.targetSphere.position = light.target.position;
  20240. this.targetSphere.properties.isGizmo = true;
  20241. this.targetSphere.properties.gizmoSubject = light.target;
  20242. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  20243. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20244. var lineGeometry = new THREE.Geometry();
  20245. lineGeometry.vertices.push( this.position.clone() );
  20246. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  20247. lineGeometry.computeLineDistances();
  20248. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  20249. this.targetLine.properties.isGizmo = true;
  20250. }
  20251. //
  20252. this.properties.isGizmo = true;
  20253. }
  20254. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20255. THREE.SpotLightHelper.prototype.update = function () {
  20256. // update arrow orientation
  20257. // pointing from light to target
  20258. this.direction.subVectors( this.light.target.position, this.light.position );
  20259. // update light cone orientation and size
  20260. this.lookAt( this.light.target.position );
  20261. var coneLength = this.light.distance ? this.light.distance : 10000;
  20262. var coneWidth = coneLength * Math.tan( this.light.angle * 0.5 ) * 2;
  20263. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  20264. // update arrow, spheres, rays and line colors to light color * light intensity
  20265. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20266. this.color.copy( this.light.color );
  20267. this.color.multiplyScalar( intensity );
  20268. this.lightSphere.material.color.copy( this.color );
  20269. this.lightRays.material.color.copy( this.color );
  20270. this.lightCone.material.color.copy( this.color );
  20271. // Only update targetSphere and targetLine if available
  20272. if ( this.targetSphere !== null ) {
  20273. this.targetSphere.material.color.copy( this.color );
  20274. this.targetLine.material.color.copy( this.color );
  20275. // update target line vertices
  20276. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  20277. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  20278. this.targetLine.geometry.computeLineDistances();
  20279. this.targetLine.geometry.verticesNeedUpdate = true;
  20280. }
  20281. };
  20282. /**
  20283. * @author alteredq / http://alteredqualia.com/
  20284. */
  20285. THREE.ImmediateRenderObject = function ( ) {
  20286. THREE.Object3D.call( this );
  20287. this.render = function ( renderCallback ) { };
  20288. };
  20289. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20290. /**
  20291. * @author mikael emtinger / http://gomo.se/
  20292. * @author alteredq / http://alteredqualia.com/
  20293. */
  20294. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20295. THREE.Object3D.call( this );
  20296. this.lensFlares = [];
  20297. this.positionScreen = new THREE.Vector3();
  20298. this.customUpdateCallback = undefined;
  20299. if( texture !== undefined ) {
  20300. this.add( texture, size, distance, blending, color );
  20301. }
  20302. };
  20303. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20304. /*
  20305. * Add: adds another flare
  20306. */
  20307. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20308. if( size === undefined ) size = -1;
  20309. if( distance === undefined ) distance = 0;
  20310. if( opacity === undefined ) opacity = 1;
  20311. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20312. if( blending === undefined ) blending = THREE.NormalBlending;
  20313. distance = Math.min( distance, Math.max( 0, distance ) );
  20314. this.lensFlares.push( { texture: texture, // THREE.Texture
  20315. size: size, // size in pixels (-1 = use texture.width)
  20316. distance: distance, // distance (0-1) from light source (0=at light source)
  20317. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20318. scale: 1, // scale
  20319. rotation: 1, // rotation
  20320. opacity: opacity, // opacity
  20321. color: color, // color
  20322. blending: blending } ); // blending
  20323. };
  20324. /*
  20325. * Update lens flares update positions on all flares based on the screen position
  20326. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20327. */
  20328. THREE.LensFlare.prototype.updateLensFlares = function () {
  20329. var f, fl = this.lensFlares.length;
  20330. var flare;
  20331. var vecX = -this.positionScreen.x * 2;
  20332. var vecY = -this.positionScreen.y * 2;
  20333. for( f = 0; f < fl; f ++ ) {
  20334. flare = this.lensFlares[ f ];
  20335. flare.x = this.positionScreen.x + vecX * flare.distance;
  20336. flare.y = this.positionScreen.y + vecY * flare.distance;
  20337. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20338. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20339. }
  20340. };
  20341. /**
  20342. * @author alteredq / http://alteredqualia.com/
  20343. */
  20344. THREE.MorphBlendMesh = function( geometry, material ) {
  20345. THREE.Mesh.call( this, geometry, material );
  20346. this.animationsMap = {};
  20347. this.animationsList = [];
  20348. // prepare default animation
  20349. // (all frames played together in 1 second)
  20350. var numFrames = this.geometry.morphTargets.length;
  20351. var name = "__default";
  20352. var startFrame = 0;
  20353. var endFrame = numFrames - 1;
  20354. var fps = numFrames / 1;
  20355. this.createAnimation( name, startFrame, endFrame, fps );
  20356. this.setAnimationWeight( name, 1 );
  20357. };
  20358. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20359. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20360. var animation = {
  20361. startFrame: start,
  20362. endFrame: end,
  20363. length: end - start + 1,
  20364. fps: fps,
  20365. duration: ( end - start ) / fps,
  20366. lastFrame: 0,
  20367. currentFrame: 0,
  20368. active: false,
  20369. time: 0,
  20370. direction: 1,
  20371. weight: 1,
  20372. directionBackwards: false,
  20373. mirroredLoop: false
  20374. };
  20375. this.animationsMap[ name ] = animation;
  20376. this.animationsList.push( animation );
  20377. };
  20378. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20379. var pattern = /([a-z]+)(\d+)/;
  20380. var firstAnimation, frameRanges = {};
  20381. var geometry = this.geometry;
  20382. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20383. var morph = geometry.morphTargets[ i ];
  20384. var chunks = morph.name.match( pattern );
  20385. if ( chunks && chunks.length > 1 ) {
  20386. var name = chunks[ 1 ];
  20387. var num = chunks[ 2 ];
  20388. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20389. var range = frameRanges[ name ];
  20390. if ( i < range.start ) range.start = i;
  20391. if ( i > range.end ) range.end = i;
  20392. if ( ! firstAnimation ) firstAnimation = name;
  20393. }
  20394. }
  20395. for ( var name in frameRanges ) {
  20396. var range = frameRanges[ name ];
  20397. this.createAnimation( name, range.start, range.end, fps );
  20398. }
  20399. this.firstAnimation = firstAnimation;
  20400. };
  20401. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20402. var animation = this.animationsMap[ name ];
  20403. if ( animation ) {
  20404. animation.direction = 1;
  20405. animation.directionBackwards = false;
  20406. }
  20407. };
  20408. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20409. var animation = this.animationsMap[ name ];
  20410. if ( animation ) {
  20411. animation.direction = -1;
  20412. animation.directionBackwards = true;
  20413. }
  20414. };
  20415. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20416. var animation = this.animationsMap[ name ];
  20417. if ( animation ) {
  20418. animation.fps = fps;
  20419. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20420. }
  20421. };
  20422. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20423. var animation = this.animationsMap[ name ];
  20424. if ( animation ) {
  20425. animation.duration = duration;
  20426. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20427. }
  20428. };
  20429. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20430. var animation = this.animationsMap[ name ];
  20431. if ( animation ) {
  20432. animation.weight = weight;
  20433. }
  20434. };
  20435. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20436. var animation = this.animationsMap[ name ];
  20437. if ( animation ) {
  20438. animation.time = time;
  20439. }
  20440. };
  20441. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20442. var time = 0;
  20443. var animation = this.animationsMap[ name ];
  20444. if ( animation ) {
  20445. time = animation.time;
  20446. }
  20447. return time;
  20448. };
  20449. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20450. var duration = -1;
  20451. var animation = this.animationsMap[ name ];
  20452. if ( animation ) {
  20453. duration = animation.duration;
  20454. }
  20455. return duration;
  20456. };
  20457. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20458. var animation = this.animationsMap[ name ];
  20459. if ( animation ) {
  20460. animation.time = 0;
  20461. animation.active = true;
  20462. } else {
  20463. console.warn( "animation[" + name + "] undefined" );
  20464. }
  20465. };
  20466. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20467. var animation = this.animationsMap[ name ];
  20468. if ( animation ) {
  20469. animation.active = false;
  20470. }
  20471. };
  20472. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20473. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20474. var animation = this.animationsList[ i ];
  20475. if ( ! animation.active ) continue;
  20476. var frameTime = animation.duration / animation.length;
  20477. animation.time += animation.direction * delta;
  20478. if ( animation.mirroredLoop ) {
  20479. if ( animation.time > animation.duration || animation.time < 0 ) {
  20480. animation.direction *= -1;
  20481. if ( animation.time > animation.duration ) {
  20482. animation.time = animation.duration;
  20483. animation.directionBackwards = true;
  20484. }
  20485. if ( animation.time < 0 ) {
  20486. animation.time = 0;
  20487. animation.directionBackwards = false;
  20488. }
  20489. }
  20490. } else {
  20491. animation.time = animation.time % animation.duration;
  20492. if ( animation.time < 0 ) animation.time += animation.duration;
  20493. }
  20494. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20495. var weight = animation.weight;
  20496. if ( keyframe !== animation.currentFrame ) {
  20497. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20498. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20499. this.morphTargetInfluences[ keyframe ] = 0;
  20500. animation.lastFrame = animation.currentFrame;
  20501. animation.currentFrame = keyframe;
  20502. }
  20503. var mix = ( animation.time % frameTime ) / frameTime;
  20504. if ( animation.directionBackwards ) mix = 1 - mix;
  20505. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  20506. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  20507. }
  20508. };
  20509. /**
  20510. * @author mikael emtinger / http://gomo.se/
  20511. * @author alteredq / http://alteredqualia.com/
  20512. */
  20513. THREE.LensFlarePlugin = function ( ) {
  20514. var _gl, _renderer, _precision, _lensFlare = {};
  20515. this.init = function ( renderer ) {
  20516. _gl = renderer.context;
  20517. _renderer = renderer;
  20518. _precision = renderer.getPrecision();
  20519. _lensFlare.vertices = new Float32Array( 8 + 8 );
  20520. _lensFlare.faces = new Uint16Array( 6 );
  20521. var i = 0;
  20522. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  20523. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  20524. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  20525. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  20526. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20527. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20528. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  20529. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  20530. i = 0;
  20531. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  20532. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  20533. // buffers
  20534. _lensFlare.vertexBuffer = _gl.createBuffer();
  20535. _lensFlare.elementBuffer = _gl.createBuffer();
  20536. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20537. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  20538. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20539. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  20540. // textures
  20541. _lensFlare.tempTexture = _gl.createTexture();
  20542. _lensFlare.occlusionTexture = _gl.createTexture();
  20543. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20544. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  20545. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20546. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20547. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20548. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20549. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20550. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  20551. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20552. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20553. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20554. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20555. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  20556. _lensFlare.hasVertexTexture = false;
  20557. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  20558. } else {
  20559. _lensFlare.hasVertexTexture = true;
  20560. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  20561. }
  20562. _lensFlare.attributes = {};
  20563. _lensFlare.uniforms = {};
  20564. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  20565. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  20566. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  20567. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  20568. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  20569. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  20570. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  20571. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  20572. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  20573. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  20574. };
  20575. /*
  20576. * Render lens flares
  20577. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  20578. * reads these back and calculates occlusion.
  20579. * Then _lensFlare.update_lensFlares() is called to re-position and
  20580. * update transparency of flares. Then they are rendered.
  20581. *
  20582. */
  20583. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20584. var flares = scene.__webglFlares,
  20585. nFlares = flares.length;
  20586. if ( ! nFlares ) return;
  20587. var tempPosition = new THREE.Vector3();
  20588. var invAspect = viewportHeight / viewportWidth,
  20589. halfViewportWidth = viewportWidth * 0.5,
  20590. halfViewportHeight = viewportHeight * 0.5;
  20591. var size = 16 / viewportHeight,
  20592. scale = new THREE.Vector2( size * invAspect, size );
  20593. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  20594. screenPositionPixels = new THREE.Vector2( 1, 1 );
  20595. var uniforms = _lensFlare.uniforms,
  20596. attributes = _lensFlare.attributes;
  20597. // set _lensFlare program and reset blending
  20598. _gl.useProgram( _lensFlare.program );
  20599. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  20600. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  20601. // loop through all lens flares to update their occlusion and positions
  20602. // setup gl and common used attribs/unforms
  20603. _gl.uniform1i( uniforms.occlusionMap, 0 );
  20604. _gl.uniform1i( uniforms.map, 1 );
  20605. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20606. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  20607. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  20608. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20609. _gl.disable( _gl.CULL_FACE );
  20610. _gl.depthMask( false );
  20611. var i, j, jl, flare, sprite;
  20612. for ( i = 0; i < nFlares; i ++ ) {
  20613. size = 16 / viewportHeight;
  20614. scale.set( size * invAspect, size );
  20615. // calc object screen position
  20616. flare = flares[ i ];
  20617. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  20618. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  20619. tempPosition.applyMatrix4( camera.projectionMatrix );
  20620. // setup arrays for gl programs
  20621. screenPosition.copy( tempPosition )
  20622. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  20623. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  20624. // screen cull
  20625. if ( _lensFlare.hasVertexTexture || (
  20626. screenPositionPixels.x > 0 &&
  20627. screenPositionPixels.x < viewportWidth &&
  20628. screenPositionPixels.y > 0 &&
  20629. screenPositionPixels.y < viewportHeight ) ) {
  20630. // save current RGB to temp texture
  20631. _gl.activeTexture( _gl.TEXTURE1 );
  20632. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20633. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20634. // render pink quad
  20635. _gl.uniform1i( uniforms.renderType, 0 );
  20636. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20637. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20638. _gl.disable( _gl.BLEND );
  20639. _gl.enable( _gl.DEPTH_TEST );
  20640. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20641. // copy result to occlusionMap
  20642. _gl.activeTexture( _gl.TEXTURE0 );
  20643. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20644. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20645. // restore graphics
  20646. _gl.uniform1i( uniforms.renderType, 1 );
  20647. _gl.disable( _gl.DEPTH_TEST );
  20648. _gl.activeTexture( _gl.TEXTURE1 );
  20649. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20650. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20651. // update object positions
  20652. flare.positionScreen.copy( screenPosition )
  20653. if ( flare.customUpdateCallback ) {
  20654. flare.customUpdateCallback( flare );
  20655. } else {
  20656. flare.updateLensFlares();
  20657. }
  20658. // render flares
  20659. _gl.uniform1i( uniforms.renderType, 2 );
  20660. _gl.enable( _gl.BLEND );
  20661. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  20662. sprite = flare.lensFlares[ j ];
  20663. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  20664. screenPosition.x = sprite.x;
  20665. screenPosition.y = sprite.y;
  20666. screenPosition.z = sprite.z;
  20667. size = sprite.size * sprite.scale / viewportHeight;
  20668. scale.x = size * invAspect;
  20669. scale.y = size;
  20670. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20671. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20672. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  20673. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  20674. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  20675. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  20676. _renderer.setTexture( sprite.texture, 1 );
  20677. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20678. }
  20679. }
  20680. }
  20681. }
  20682. // restore gl
  20683. _gl.enable( _gl.CULL_FACE );
  20684. _gl.enable( _gl.DEPTH_TEST );
  20685. _gl.depthMask( true );
  20686. };
  20687. function createProgram ( shader, precision ) {
  20688. var program = _gl.createProgram();
  20689. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  20690. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  20691. var prefix = "precision " + precision + " float;\n";
  20692. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  20693. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  20694. _gl.compileShader( fragmentShader );
  20695. _gl.compileShader( vertexShader );
  20696. _gl.attachShader( program, fragmentShader );
  20697. _gl.attachShader( program, vertexShader );
  20698. _gl.linkProgram( program );
  20699. return program;
  20700. };
  20701. };
  20702. /**
  20703. * @author alteredq / http://alteredqualia.com/
  20704. */
  20705. THREE.ShadowMapPlugin = function ( ) {
  20706. var _gl,
  20707. _renderer,
  20708. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  20709. _frustum = new THREE.Frustum(),
  20710. _projScreenMatrix = new THREE.Matrix4(),
  20711. _min = new THREE.Vector3(),
  20712. _max = new THREE.Vector3();
  20713. this.init = function ( renderer ) {
  20714. _gl = renderer.context;
  20715. _renderer = renderer;
  20716. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  20717. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  20718. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  20719. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  20720. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  20721. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  20722. _depthMaterial._shadowPass = true;
  20723. _depthMaterialMorph._shadowPass = true;
  20724. _depthMaterialSkin._shadowPass = true;
  20725. _depthMaterialMorphSkin._shadowPass = true;
  20726. };
  20727. this.render = function ( scene, camera ) {
  20728. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  20729. this.update( scene, camera );
  20730. };
  20731. this.update = function ( scene, camera ) {
  20732. var i, il, j, jl, n,
  20733. shadowMap, shadowMatrix, shadowCamera,
  20734. program, buffer, material,
  20735. webglObject, object, light,
  20736. renderList,
  20737. lights = [],
  20738. k = 0,
  20739. fog = null;
  20740. // set GL state for depth map
  20741. _gl.clearColor( 1, 1, 1, 1 );
  20742. _gl.disable( _gl.BLEND );
  20743. _gl.enable( _gl.CULL_FACE );
  20744. _gl.frontFace( _gl.CCW );
  20745. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  20746. _gl.cullFace( _gl.FRONT );
  20747. } else {
  20748. _gl.cullFace( _gl.BACK );
  20749. }
  20750. _renderer.setDepthTest( true );
  20751. // preprocess lights
  20752. // - skip lights that are not casting shadows
  20753. // - create virtual lights for cascaded shadow maps
  20754. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  20755. light = scene.__lights[ i ];
  20756. if ( ! light.castShadow ) continue;
  20757. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  20758. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  20759. var virtualLight;
  20760. if ( ! light.shadowCascadeArray[ n ] ) {
  20761. virtualLight = createVirtualLight( light, n );
  20762. virtualLight.originalCamera = camera;
  20763. var gyro = new THREE.Gyroscope();
  20764. gyro.position = light.shadowCascadeOffset;
  20765. gyro.add( virtualLight );
  20766. gyro.add( virtualLight.target );
  20767. camera.add( gyro );
  20768. light.shadowCascadeArray[ n ] = virtualLight;
  20769. console.log( "Created virtualLight", virtualLight );
  20770. } else {
  20771. virtualLight = light.shadowCascadeArray[ n ];
  20772. }
  20773. updateVirtualLight( light, n );
  20774. lights[ k ] = virtualLight;
  20775. k ++;
  20776. }
  20777. } else {
  20778. lights[ k ] = light;
  20779. k ++;
  20780. }
  20781. }
  20782. // render depth map
  20783. for ( i = 0, il = lights.length; i < il; i ++ ) {
  20784. light = lights[ i ];
  20785. if ( ! light.shadowMap ) {
  20786. var shadowFilter = THREE.LinearFilter;
  20787. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  20788. shadowFilter = THREE.NearestFilter;
  20789. }
  20790. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  20791. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  20792. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  20793. light.shadowMatrix = new THREE.Matrix4();
  20794. }
  20795. if ( ! light.shadowCamera ) {
  20796. if ( light instanceof THREE.SpotLight ) {
  20797. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  20798. } else if ( light instanceof THREE.DirectionalLight ) {
  20799. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  20800. } else {
  20801. console.error( "Unsupported light type for shadow" );
  20802. continue;
  20803. }
  20804. scene.add( light.shadowCamera );
  20805. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  20806. }
  20807. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  20808. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  20809. light.shadowCamera.add( light.cameraHelper );
  20810. }
  20811. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  20812. updateShadowCamera( camera, light );
  20813. }
  20814. shadowMap = light.shadowMap;
  20815. shadowMatrix = light.shadowMatrix;
  20816. shadowCamera = light.shadowCamera;
  20817. shadowCamera.position.copy( light.matrixWorld.getPosition() );
  20818. shadowCamera.lookAt( light.target.matrixWorld.getPosition() );
  20819. shadowCamera.updateMatrixWorld();
  20820. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  20821. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  20822. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  20823. // compute shadow matrix
  20824. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  20825. 0.0, 0.5, 0.0, 0.5,
  20826. 0.0, 0.0, 0.5, 0.5,
  20827. 0.0, 0.0, 0.0, 1.0 );
  20828. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  20829. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  20830. // update camera matrices and frustum
  20831. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  20832. _frustum.setFromMatrix( _projScreenMatrix );
  20833. // render shadow map
  20834. _renderer.setRenderTarget( shadowMap );
  20835. _renderer.clear();
  20836. // set object matrices & frustum culling
  20837. renderList = scene.__webglObjects;
  20838. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20839. webglObject = renderList[ j ];
  20840. object = webglObject.object;
  20841. webglObject.render = false;
  20842. if ( object.visible && object.castShadow ) {
  20843. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  20844. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  20845. webglObject.render = true;
  20846. }
  20847. }
  20848. }
  20849. // render regular objects
  20850. var objectMaterial, useMorphing, useSkinning;
  20851. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20852. webglObject = renderList[ j ];
  20853. if ( webglObject.render ) {
  20854. object = webglObject.object;
  20855. buffer = webglObject.buffer;
  20856. // culling is overriden globally for all objects
  20857. // while rendering depth map
  20858. // need to deal with MeshFaceMaterial somehow
  20859. // in that case just use the first of material.materials for now
  20860. // (proper solution would require to break objects by materials
  20861. // similarly to regular rendering and then set corresponding
  20862. // depth materials per each chunk instead of just once per object)
  20863. objectMaterial = getObjectMaterial( object );
  20864. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  20865. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  20866. if ( object.customDepthMaterial ) {
  20867. material = object.customDepthMaterial;
  20868. } else if ( useSkinning ) {
  20869. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  20870. } else if ( useMorphing ) {
  20871. material = _depthMaterialMorph;
  20872. } else {
  20873. material = _depthMaterial;
  20874. }
  20875. if ( buffer instanceof THREE.BufferGeometry ) {
  20876. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  20877. } else {
  20878. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  20879. }
  20880. }
  20881. }
  20882. // set matrices and render immediate objects
  20883. renderList = scene.__webglObjectsImmediate;
  20884. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20885. webglObject = renderList[ j ];
  20886. object = webglObject.object;
  20887. if ( object.visible && object.castShadow ) {
  20888. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  20889. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  20890. }
  20891. }
  20892. }
  20893. // restore GL state
  20894. var clearColor = _renderer.getClearColor(),
  20895. clearAlpha = _renderer.getClearAlpha();
  20896. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  20897. _gl.enable( _gl.BLEND );
  20898. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  20899. _gl.cullFace( _gl.BACK );
  20900. }
  20901. };
  20902. function createVirtualLight( light, cascade ) {
  20903. var virtualLight = new THREE.DirectionalLight();
  20904. virtualLight.isVirtual = true;
  20905. virtualLight.onlyShadow = true;
  20906. virtualLight.castShadow = true;
  20907. virtualLight.shadowCameraNear = light.shadowCameraNear;
  20908. virtualLight.shadowCameraFar = light.shadowCameraFar;
  20909. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  20910. virtualLight.shadowCameraRight = light.shadowCameraRight;
  20911. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  20912. virtualLight.shadowCameraTop = light.shadowCameraTop;
  20913. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  20914. virtualLight.shadowDarkness = light.shadowDarkness;
  20915. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  20916. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  20917. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  20918. virtualLight.pointsWorld = [];
  20919. virtualLight.pointsFrustum = [];
  20920. var pointsWorld = virtualLight.pointsWorld,
  20921. pointsFrustum = virtualLight.pointsFrustum;
  20922. for ( var i = 0; i < 8; i ++ ) {
  20923. pointsWorld[ i ] = new THREE.Vector3();
  20924. pointsFrustum[ i ] = new THREE.Vector3();
  20925. }
  20926. var nearZ = light.shadowCascadeNearZ[ cascade ];
  20927. var farZ = light.shadowCascadeFarZ[ cascade ];
  20928. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  20929. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  20930. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  20931. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  20932. pointsFrustum[ 4 ].set( -1, -1, farZ );
  20933. pointsFrustum[ 5 ].set( 1, -1, farZ );
  20934. pointsFrustum[ 6 ].set( -1, 1, farZ );
  20935. pointsFrustum[ 7 ].set( 1, 1, farZ );
  20936. return virtualLight;
  20937. }
  20938. // Synchronize virtual light with the original light
  20939. function updateVirtualLight( light, cascade ) {
  20940. var virtualLight = light.shadowCascadeArray[ cascade ];
  20941. virtualLight.position.copy( light.position );
  20942. virtualLight.target.position.copy( light.target.position );
  20943. virtualLight.lookAt( virtualLight.target );
  20944. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  20945. virtualLight.shadowDarkness = light.shadowDarkness;
  20946. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  20947. var nearZ = light.shadowCascadeNearZ[ cascade ];
  20948. var farZ = light.shadowCascadeFarZ[ cascade ];
  20949. var pointsFrustum = virtualLight.pointsFrustum;
  20950. pointsFrustum[ 0 ].z = nearZ;
  20951. pointsFrustum[ 1 ].z = nearZ;
  20952. pointsFrustum[ 2 ].z = nearZ;
  20953. pointsFrustum[ 3 ].z = nearZ;
  20954. pointsFrustum[ 4 ].z = farZ;
  20955. pointsFrustum[ 5 ].z = farZ;
  20956. pointsFrustum[ 6 ].z = farZ;
  20957. pointsFrustum[ 7 ].z = farZ;
  20958. }
  20959. // Fit shadow camera's ortho frustum to camera frustum
  20960. function updateShadowCamera( camera, light ) {
  20961. var shadowCamera = light.shadowCamera,
  20962. pointsFrustum = light.pointsFrustum,
  20963. pointsWorld = light.pointsWorld;
  20964. _min.set( Infinity, Infinity, Infinity );
  20965. _max.set( -Infinity, -Infinity, -Infinity );
  20966. for ( var i = 0; i < 8; i ++ ) {
  20967. var p = pointsWorld[ i ];
  20968. p.copy( pointsFrustum[ i ] );
  20969. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  20970. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  20971. if ( p.x < _min.x ) _min.x = p.x;
  20972. if ( p.x > _max.x ) _max.x = p.x;
  20973. if ( p.y < _min.y ) _min.y = p.y;
  20974. if ( p.y > _max.y ) _max.y = p.y;
  20975. if ( p.z < _min.z ) _min.z = p.z;
  20976. if ( p.z > _max.z ) _max.z = p.z;
  20977. }
  20978. shadowCamera.left = _min.x;
  20979. shadowCamera.right = _max.x;
  20980. shadowCamera.top = _max.y;
  20981. shadowCamera.bottom = _min.y;
  20982. // can't really fit near/far
  20983. //shadowCamera.near = _min.z;
  20984. //shadowCamera.far = _max.z;
  20985. shadowCamera.updateProjectionMatrix();
  20986. }
  20987. // For the moment just ignore objects that have multiple materials with different animation methods
  20988. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  20989. function getObjectMaterial( object ) {
  20990. return object.material instanceof THREE.MeshFaceMaterial
  20991. ? object.material.materials[ 0 ]
  20992. : object.material;
  20993. };
  20994. };
  20995. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  20996. /**
  20997. * @author mikael emtinger / http://gomo.se/
  20998. * @author alteredq / http://alteredqualia.com/
  20999. */
  21000. THREE.SpritePlugin = function ( ) {
  21001. var _gl, _renderer, _precision, _sprite = {};
  21002. this.init = function ( renderer ) {
  21003. _gl = renderer.context;
  21004. _renderer = renderer;
  21005. _precision = renderer.getPrecision();
  21006. _sprite.vertices = new Float32Array( 8 + 8 );
  21007. _sprite.faces = new Uint16Array( 6 );
  21008. var i = 0;
  21009. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  21010. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  21011. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  21012. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  21013. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  21014. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  21015. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  21016. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  21017. i = 0;
  21018. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  21019. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  21020. _sprite.vertexBuffer = _gl.createBuffer();
  21021. _sprite.elementBuffer = _gl.createBuffer();
  21022. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21023. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  21024. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21025. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  21026. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ], _precision );
  21027. _sprite.attributes = {};
  21028. _sprite.uniforms = {};
  21029. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  21030. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  21031. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  21032. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  21033. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  21034. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  21035. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  21036. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  21037. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  21038. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  21039. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  21040. _sprite.uniforms.sizeAttenuation = _gl.getUniformLocation( _sprite.program, "sizeAttenuation" );
  21041. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  21042. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  21043. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  21044. _sprite.uniforms.fogType = _gl.getUniformLocation( _sprite.program, "fogType" );
  21045. _sprite.uniforms.fogDensity = _gl.getUniformLocation( _sprite.program, "fogDensity" );
  21046. _sprite.uniforms.fogNear = _gl.getUniformLocation( _sprite.program, "fogNear" );
  21047. _sprite.uniforms.fogFar = _gl.getUniformLocation( _sprite.program, "fogFar" );
  21048. _sprite.uniforms.fogColor = _gl.getUniformLocation( _sprite.program, "fogColor" );
  21049. _sprite.uniforms.alphaTest = _gl.getUniformLocation( _sprite.program, "alphaTest" );
  21050. };
  21051. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21052. var sprites = scene.__webglSprites,
  21053. nSprites = sprites.length;
  21054. if ( ! nSprites ) return;
  21055. var attributes = _sprite.attributes,
  21056. uniforms = _sprite.uniforms;
  21057. var invAspect = viewportHeight / viewportWidth;
  21058. var halfViewportWidth = viewportWidth * 0.5,
  21059. halfViewportHeight = viewportHeight * 0.5;
  21060. // setup gl
  21061. _gl.useProgram( _sprite.program );
  21062. _gl.enableVertexAttribArray( attributes.position );
  21063. _gl.enableVertexAttribArray( attributes.uv );
  21064. _gl.disable( _gl.CULL_FACE );
  21065. _gl.enable( _gl.BLEND );
  21066. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21067. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21068. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21069. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21070. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  21071. _gl.activeTexture( _gl.TEXTURE0 );
  21072. _gl.uniform1i( uniforms.map, 0 );
  21073. var oldFogType = 0;
  21074. var sceneFogType = 0;
  21075. var fog = scene.fog;
  21076. if ( fog ) {
  21077. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  21078. if ( fog instanceof THREE.Fog ) {
  21079. _gl.uniform1f( uniforms.fogNear, fog.near );
  21080. _gl.uniform1f( uniforms.fogFar, fog.far );
  21081. _gl.uniform1i( uniforms.fogType, 1 );
  21082. oldFogType = 1;
  21083. sceneFogType = 1;
  21084. } else if ( fog instanceof THREE.FogExp2 ) {
  21085. _gl.uniform1f( uniforms.fogDensity, fog.density );
  21086. _gl.uniform1i( uniforms.fogType, 2 );
  21087. oldFogType = 2;
  21088. sceneFogType = 2;
  21089. }
  21090. } else {
  21091. _gl.uniform1i( uniforms.fogType, 0 );
  21092. oldFogType = 0;
  21093. sceneFogType = 0;
  21094. }
  21095. // update positions and sort
  21096. var i, sprite, material, screenPosition, size, fogType, scale = [];
  21097. for( i = 0; i < nSprites; i ++ ) {
  21098. sprite = sprites[ i ];
  21099. material = sprite.material;
  21100. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21101. if ( ! material.useScreenCoordinates ) {
  21102. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  21103. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  21104. } else {
  21105. sprite.z = - sprite.position.z;
  21106. }
  21107. }
  21108. sprites.sort( painterSortStable );
  21109. // render all sprites
  21110. for( i = 0; i < nSprites; i ++ ) {
  21111. sprite = sprites[ i ];
  21112. material = sprite.material;
  21113. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21114. if ( material.map && material.map.image && material.map.image.width ) {
  21115. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  21116. if ( material.useScreenCoordinates === true ) {
  21117. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  21118. _gl.uniform3f(
  21119. uniforms.screenPosition,
  21120. ( ( sprite.position.x * _renderer.devicePixelRatio ) - halfViewportWidth ) / halfViewportWidth,
  21121. ( halfViewportHeight - ( sprite.position.y * _renderer.devicePixelRatio ) ) / halfViewportHeight,
  21122. Math.max( 0, Math.min( 1, sprite.position.z ) )
  21123. );
  21124. scale[ 0 ] = _renderer.devicePixelRatio;
  21125. scale[ 1 ] = _renderer.devicePixelRatio;
  21126. } else {
  21127. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  21128. _gl.uniform1i( uniforms.sizeAttenuation, material.sizeAttenuation ? 1 : 0 );
  21129. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  21130. scale[ 0 ] = 1;
  21131. scale[ 1 ] = 1;
  21132. }
  21133. if ( scene.fog && material.fog ) {
  21134. fogType = sceneFogType;
  21135. } else {
  21136. fogType = 0;
  21137. }
  21138. if ( oldFogType !== fogType ) {
  21139. _gl.uniform1i( uniforms.fogType, fogType );
  21140. oldFogType = fogType;
  21141. }
  21142. size = 1 / ( material.scaleByViewport ? viewportHeight : 1 );
  21143. scale[ 0 ] *= size * invAspect * sprite.scale.x
  21144. scale[ 1 ] *= size * sprite.scale.y;
  21145. _gl.uniform2f( uniforms.uvScale, material.uvScale.x, material.uvScale.y );
  21146. _gl.uniform2f( uniforms.uvOffset, material.uvOffset.x, material.uvOffset.y );
  21147. _gl.uniform2f( uniforms.alignment, material.alignment.x, material.alignment.y );
  21148. _gl.uniform1f( uniforms.opacity, material.opacity );
  21149. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  21150. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21151. _gl.uniform2fv( uniforms.scale, scale );
  21152. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  21153. _renderer.setDepthTest( material.depthTest );
  21154. _renderer.setDepthWrite( material.depthWrite );
  21155. _renderer.setTexture( material.map, 0 );
  21156. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21157. }
  21158. }
  21159. // restore gl
  21160. _gl.enable( _gl.CULL_FACE );
  21161. };
  21162. function createProgram ( shader, precision ) {
  21163. var program = _gl.createProgram();
  21164. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21165. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21166. var prefix = "precision " + precision + " float;\n";
  21167. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21168. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21169. _gl.compileShader( fragmentShader );
  21170. _gl.compileShader( vertexShader );
  21171. _gl.attachShader( program, fragmentShader );
  21172. _gl.attachShader( program, vertexShader );
  21173. _gl.linkProgram( program );
  21174. return program;
  21175. };
  21176. function painterSortStable ( a, b ) {
  21177. if ( a.z !== b.z ) {
  21178. return b.z - a.z;
  21179. } else {
  21180. return b.id - a.id;
  21181. }
  21182. };
  21183. };
  21184. /**
  21185. * @author alteredq / http://alteredqualia.com/
  21186. */
  21187. THREE.DepthPassPlugin = function ( ) {
  21188. this.enabled = false;
  21189. this.renderTarget = null;
  21190. var _gl,
  21191. _renderer,
  21192. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21193. _frustum = new THREE.Frustum(),
  21194. _projScreenMatrix = new THREE.Matrix4();
  21195. this.init = function ( renderer ) {
  21196. _gl = renderer.context;
  21197. _renderer = renderer;
  21198. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21199. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21200. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21201. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21202. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21203. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21204. _depthMaterial._shadowPass = true;
  21205. _depthMaterialMorph._shadowPass = true;
  21206. _depthMaterialSkin._shadowPass = true;
  21207. _depthMaterialMorphSkin._shadowPass = true;
  21208. };
  21209. this.render = function ( scene, camera ) {
  21210. if ( ! this.enabled ) return;
  21211. this.update( scene, camera );
  21212. };
  21213. this.update = function ( scene, camera ) {
  21214. var i, il, j, jl, n,
  21215. program, buffer, material,
  21216. webglObject, object, light,
  21217. renderList,
  21218. fog = null;
  21219. // set GL state for depth map
  21220. _gl.clearColor( 1, 1, 1, 1 );
  21221. _gl.disable( _gl.BLEND );
  21222. _renderer.setDepthTest( true );
  21223. // update scene
  21224. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21225. // update camera matrices and frustum
  21226. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21227. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  21228. _frustum.setFromMatrix( _projScreenMatrix );
  21229. // render depth map
  21230. _renderer.setRenderTarget( this.renderTarget );
  21231. _renderer.clear();
  21232. // set object matrices & frustum culling
  21233. renderList = scene.__webglObjects;
  21234. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21235. webglObject = renderList[ j ];
  21236. object = webglObject.object;
  21237. webglObject.render = false;
  21238. if ( object.visible ) {
  21239. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21240. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21241. webglObject.render = true;
  21242. }
  21243. }
  21244. }
  21245. // render regular objects
  21246. var objectMaterial, useMorphing, useSkinning;
  21247. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21248. webglObject = renderList[ j ];
  21249. if ( webglObject.render ) {
  21250. object = webglObject.object;
  21251. buffer = webglObject.buffer;
  21252. // todo: create proper depth material for particles
  21253. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  21254. objectMaterial = getObjectMaterial( object );
  21255. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  21256. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21257. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21258. if ( object.customDepthMaterial ) {
  21259. material = object.customDepthMaterial;
  21260. } else if ( useSkinning ) {
  21261. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21262. } else if ( useMorphing ) {
  21263. material = _depthMaterialMorph;
  21264. } else {
  21265. material = _depthMaterial;
  21266. }
  21267. if ( buffer instanceof THREE.BufferGeometry ) {
  21268. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21269. } else {
  21270. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21271. }
  21272. }
  21273. }
  21274. // set matrices and render immediate objects
  21275. renderList = scene.__webglObjectsImmediate;
  21276. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21277. webglObject = renderList[ j ];
  21278. object = webglObject.object;
  21279. if ( object.visible ) {
  21280. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  21281. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21282. }
  21283. }
  21284. // restore GL state
  21285. var clearColor = _renderer.getClearColor(),
  21286. clearAlpha = _renderer.getClearAlpha();
  21287. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21288. _gl.enable( _gl.BLEND );
  21289. };
  21290. // For the moment just ignore objects that have multiple materials with different animation methods
  21291. // Only the first material will be taken into account for deciding which depth material to use
  21292. function getObjectMaterial( object ) {
  21293. return object.material instanceof THREE.MeshFaceMaterial
  21294. ? object.material.materials[ 0 ]
  21295. : object.material;
  21296. };
  21297. };
  21298. /**
  21299. * @author mikael emtinger / http://gomo.se/
  21300. *
  21301. */
  21302. THREE.ShaderFlares = {
  21303. 'lensFlareVertexTexture': {
  21304. vertexShader: [
  21305. "uniform lowp int renderType;",
  21306. "uniform vec3 screenPosition;",
  21307. "uniform vec2 scale;",
  21308. "uniform float rotation;",
  21309. "uniform sampler2D occlusionMap;",
  21310. "attribute vec2 position;",
  21311. "attribute vec2 uv;",
  21312. "varying vec2 vUV;",
  21313. "varying float vVisibility;",
  21314. "void main() {",
  21315. "vUV = uv;",
  21316. "vec2 pos = position;",
  21317. "if( renderType == 2 ) {",
  21318. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  21319. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  21320. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  21321. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  21322. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  21323. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  21324. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  21325. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  21326. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21327. "vVisibility = ( visibility.r / 9.0 ) *",
  21328. "( 1.0 - visibility.g / 9.0 ) *",
  21329. "( visibility.b / 9.0 ) *",
  21330. "( 1.0 - visibility.a / 9.0 );",
  21331. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21332. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21333. "}",
  21334. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21335. "}"
  21336. ].join( "\n" ),
  21337. fragmentShader: [
  21338. "uniform lowp int renderType;",
  21339. "uniform sampler2D map;",
  21340. "uniform float opacity;",
  21341. "uniform vec3 color;",
  21342. "varying vec2 vUV;",
  21343. "varying float vVisibility;",
  21344. "void main() {",
  21345. // pink square
  21346. "if( renderType == 0 ) {",
  21347. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21348. // restore
  21349. "} else if( renderType == 1 ) {",
  21350. "gl_FragColor = texture2D( map, vUV );",
  21351. // flare
  21352. "} else {",
  21353. "vec4 texture = texture2D( map, vUV );",
  21354. "texture.a *= opacity * vVisibility;",
  21355. "gl_FragColor = texture;",
  21356. "gl_FragColor.rgb *= color;",
  21357. "}",
  21358. "}"
  21359. ].join( "\n" )
  21360. },
  21361. 'lensFlare': {
  21362. vertexShader: [
  21363. "uniform lowp int renderType;",
  21364. "uniform vec3 screenPosition;",
  21365. "uniform vec2 scale;",
  21366. "uniform float rotation;",
  21367. "attribute vec2 position;",
  21368. "attribute vec2 uv;",
  21369. "varying vec2 vUV;",
  21370. "void main() {",
  21371. "vUV = uv;",
  21372. "vec2 pos = position;",
  21373. "if( renderType == 2 ) {",
  21374. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21375. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21376. "}",
  21377. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21378. "}"
  21379. ].join( "\n" ),
  21380. fragmentShader: [
  21381. "precision mediump float;",
  21382. "uniform lowp int renderType;",
  21383. "uniform sampler2D map;",
  21384. "uniform sampler2D occlusionMap;",
  21385. "uniform float opacity;",
  21386. "uniform vec3 color;",
  21387. "varying vec2 vUV;",
  21388. "void main() {",
  21389. // pink square
  21390. "if( renderType == 0 ) {",
  21391. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  21392. // restore
  21393. "} else if( renderType == 1 ) {",
  21394. "gl_FragColor = texture2D( map, vUV );",
  21395. // flare
  21396. "} else {",
  21397. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  21398. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  21399. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  21400. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  21401. "visibility = ( 1.0 - visibility / 4.0 );",
  21402. "vec4 texture = texture2D( map, vUV );",
  21403. "texture.a *= opacity * visibility;",
  21404. "gl_FragColor = texture;",
  21405. "gl_FragColor.rgb *= color;",
  21406. "}",
  21407. "}"
  21408. ].join( "\n" )
  21409. }
  21410. };
  21411. /**
  21412. * @author mikael emtinger / http://gomo.se/
  21413. * @author alteredq / http://alteredqualia.com/
  21414. *
  21415. */
  21416. THREE.ShaderSprite = {
  21417. 'sprite': {
  21418. vertexShader: [
  21419. "uniform int useScreenCoordinates;",
  21420. "uniform int sizeAttenuation;",
  21421. "uniform vec3 screenPosition;",
  21422. "uniform mat4 modelViewMatrix;",
  21423. "uniform mat4 projectionMatrix;",
  21424. "uniform float rotation;",
  21425. "uniform vec2 scale;",
  21426. "uniform vec2 alignment;",
  21427. "uniform vec2 uvOffset;",
  21428. "uniform vec2 uvScale;",
  21429. "attribute vec2 position;",
  21430. "attribute vec2 uv;",
  21431. "varying vec2 vUV;",
  21432. "void main() {",
  21433. "vUV = uvOffset + uv * uvScale;",
  21434. "vec2 alignedPosition = position + alignment;",
  21435. "vec2 rotatedPosition;",
  21436. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  21437. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  21438. "vec4 finalPosition;",
  21439. "if( useScreenCoordinates != 0 ) {",
  21440. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  21441. "} else {",
  21442. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  21443. "finalPosition.xy += rotatedPosition * ( sizeAttenuation == 1 ? 1.0 : finalPosition.z );",
  21444. "}",
  21445. "gl_Position = finalPosition;",
  21446. "}"
  21447. ].join( "\n" ),
  21448. fragmentShader: [
  21449. "uniform vec3 color;",
  21450. "uniform sampler2D map;",
  21451. "uniform float opacity;",
  21452. "uniform int fogType;",
  21453. "uniform vec3 fogColor;",
  21454. "uniform float fogDensity;",
  21455. "uniform float fogNear;",
  21456. "uniform float fogFar;",
  21457. "uniform float alphaTest;",
  21458. "varying vec2 vUV;",
  21459. "void main() {",
  21460. "vec4 texture = texture2D( map, vUV );",
  21461. "if ( texture.a < alphaTest ) discard;",
  21462. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  21463. "if ( fogType > 0 ) {",
  21464. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  21465. "float fogFactor = 0.0;",
  21466. "if ( fogType == 1 ) {",
  21467. "fogFactor = smoothstep( fogNear, fogFar, depth );",
  21468. "} else {",
  21469. "const float LOG2 = 1.442695;",
  21470. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  21471. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  21472. "}",
  21473. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  21474. "}",
  21475. "}"
  21476. ].join( "\n" )
  21477. }
  21478. };