three.js 810 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. * @author bhouston / http://exocortex.com
  5. */
  6. var THREE = { REVISION: '66dev' };
  7. self.console = self.console || {
  8. info: function () {},
  9. log: function () {},
  10. debug: function () {},
  11. warn: function () {},
  12. error: function () {}
  13. };
  14. String.prototype.trim = String.prototype.trim || function () {
  15. return this.replace( /^\s+|\s+$/g, '' );
  16. };
  17. // based on https://github.com/documentcloud/underscore/blob/bf657be243a075b5e72acc8a83e6f12a564d8f55/underscore.js#L767
  18. THREE.extend = function ( obj, source ) {
  19. // ECMAScript5 compatibility based on: http://www.nczonline.net/blog/2012/12/11/are-your-mixins-ecmascript-5-compatible/
  20. if ( Object.keys ) {
  21. var keys = Object.keys( source );
  22. for (var i = 0, il = keys.length; i < il; i++) {
  23. var prop = keys[i];
  24. Object.defineProperty( obj, prop, Object.getOwnPropertyDescriptor( source, prop ) );
  25. }
  26. } else {
  27. var safeHasOwnProperty = {}.hasOwnProperty;
  28. for ( var prop in source ) {
  29. if ( safeHasOwnProperty.call( source, prop ) ) {
  30. obj[prop] = source[prop];
  31. }
  32. }
  33. }
  34. return obj;
  35. };
  36. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  37. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  38. // requestAnimationFrame polyfill by Erik Möller
  39. // fixes from Paul Irish and Tino Zijdel
  40. // using 'self' instead of 'window' for compatibility with both NodeJS and IE10.
  41. ( function () {
  42. var lastTime = 0;
  43. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  44. for ( var x = 0; x < vendors.length && !self.requestAnimationFrame; ++ x ) {
  45. self.requestAnimationFrame = self[ vendors[ x ] + 'RequestAnimationFrame' ];
  46. self.cancelAnimationFrame = self[ vendors[ x ] + 'CancelAnimationFrame' ] || self[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  47. }
  48. if ( self.requestAnimationFrame === undefined && self['setTimeout'] !== undefined ) {
  49. self.requestAnimationFrame = function ( callback ) {
  50. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  51. var id = self.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  52. lastTime = currTime + timeToCall;
  53. return id;
  54. };
  55. }
  56. if( self.cancelAnimationFrame === undefined && self['clearTimeout'] !== undefined ) {
  57. self.cancelAnimationFrame = function ( id ) { self.clearTimeout( id ) };
  58. }
  59. }() );
  60. // GL STATE CONSTANTS
  61. THREE.CullFaceNone = 0;
  62. THREE.CullFaceBack = 1;
  63. THREE.CullFaceFront = 2;
  64. THREE.CullFaceFrontBack = 3;
  65. THREE.FrontFaceDirectionCW = 0;
  66. THREE.FrontFaceDirectionCCW = 1;
  67. // SHADOWING TYPES
  68. THREE.BasicShadowMap = 0;
  69. THREE.PCFShadowMap = 1;
  70. THREE.PCFSoftShadowMap = 2;
  71. // MATERIAL CONSTANTS
  72. // side
  73. THREE.FrontSide = 0;
  74. THREE.BackSide = 1;
  75. THREE.DoubleSide = 2;
  76. // shading
  77. THREE.NoShading = 0;
  78. THREE.FlatShading = 1;
  79. THREE.SmoothShading = 2;
  80. // colors
  81. THREE.NoColors = 0;
  82. THREE.FaceColors = 1;
  83. THREE.VertexColors = 2;
  84. // blending modes
  85. THREE.NoBlending = 0;
  86. THREE.NormalBlending = 1;
  87. THREE.AdditiveBlending = 2;
  88. THREE.SubtractiveBlending = 3;
  89. THREE.MultiplyBlending = 4;
  90. THREE.CustomBlending = 5;
  91. // custom blending equations
  92. // (numbers start from 100 not to clash with other
  93. // mappings to OpenGL constants defined in Texture.js)
  94. THREE.AddEquation = 100;
  95. THREE.SubtractEquation = 101;
  96. THREE.ReverseSubtractEquation = 102;
  97. // custom blending destination factors
  98. THREE.ZeroFactor = 200;
  99. THREE.OneFactor = 201;
  100. THREE.SrcColorFactor = 202;
  101. THREE.OneMinusSrcColorFactor = 203;
  102. THREE.SrcAlphaFactor = 204;
  103. THREE.OneMinusSrcAlphaFactor = 205;
  104. THREE.DstAlphaFactor = 206;
  105. THREE.OneMinusDstAlphaFactor = 207;
  106. // custom blending source factors
  107. //THREE.ZeroFactor = 200;
  108. //THREE.OneFactor = 201;
  109. //THREE.SrcAlphaFactor = 204;
  110. //THREE.OneMinusSrcAlphaFactor = 205;
  111. //THREE.DstAlphaFactor = 206;
  112. //THREE.OneMinusDstAlphaFactor = 207;
  113. THREE.DstColorFactor = 208;
  114. THREE.OneMinusDstColorFactor = 209;
  115. THREE.SrcAlphaSaturateFactor = 210;
  116. // TEXTURE CONSTANTS
  117. THREE.MultiplyOperation = 0;
  118. THREE.MixOperation = 1;
  119. THREE.AddOperation = 2;
  120. // Mapping modes
  121. THREE.UVMapping = function () {};
  122. THREE.CubeReflectionMapping = function () {};
  123. THREE.CubeRefractionMapping = function () {};
  124. THREE.SphericalReflectionMapping = function () {};
  125. THREE.SphericalRefractionMapping = function () {};
  126. // Wrapping modes
  127. THREE.RepeatWrapping = 1000;
  128. THREE.ClampToEdgeWrapping = 1001;
  129. THREE.MirroredRepeatWrapping = 1002;
  130. // Filters
  131. THREE.NearestFilter = 1003;
  132. THREE.NearestMipMapNearestFilter = 1004;
  133. THREE.NearestMipMapLinearFilter = 1005;
  134. THREE.LinearFilter = 1006;
  135. THREE.LinearMipMapNearestFilter = 1007;
  136. THREE.LinearMipMapLinearFilter = 1008;
  137. // Data types
  138. THREE.UnsignedByteType = 1009;
  139. THREE.ByteType = 1010;
  140. THREE.ShortType = 1011;
  141. THREE.UnsignedShortType = 1012;
  142. THREE.IntType = 1013;
  143. THREE.UnsignedIntType = 1014;
  144. THREE.FloatType = 1015;
  145. // Pixel types
  146. //THREE.UnsignedByteType = 1009;
  147. THREE.UnsignedShort4444Type = 1016;
  148. THREE.UnsignedShort5551Type = 1017;
  149. THREE.UnsignedShort565Type = 1018;
  150. // Pixel formats
  151. THREE.AlphaFormat = 1019;
  152. THREE.RGBFormat = 1020;
  153. THREE.RGBAFormat = 1021;
  154. THREE.LuminanceFormat = 1022;
  155. THREE.LuminanceAlphaFormat = 1023;
  156. // Compressed texture formats
  157. THREE.RGB_S3TC_DXT1_Format = 2001;
  158. THREE.RGBA_S3TC_DXT1_Format = 2002;
  159. THREE.RGBA_S3TC_DXT3_Format = 2003;
  160. THREE.RGBA_S3TC_DXT5_Format = 2004;
  161. /*
  162. // Potential future PVRTC compressed texture formats
  163. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  164. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  165. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  166. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  167. */
  168. /**
  169. * @author mrdoob / http://mrdoob.com/
  170. */
  171. THREE.Color = function ( color ) {
  172. if ( arguments.length === 3 ) {
  173. return this.setRGB( arguments[ 0 ], arguments[ 1 ], arguments[ 2 ] );
  174. }
  175. return this.set( color )
  176. };
  177. THREE.Color.prototype = {
  178. constructor: THREE.Color,
  179. r: 1, g: 1, b: 1,
  180. set: function ( value ) {
  181. if ( value instanceof THREE.Color ) {
  182. this.copy( value );
  183. } else if ( typeof value === 'number' ) {
  184. this.setHex( value );
  185. } else if ( typeof value === 'string' ) {
  186. this.setStyle( value );
  187. }
  188. return this;
  189. },
  190. setHex: function ( hex ) {
  191. hex = Math.floor( hex );
  192. this.r = ( hex >> 16 & 255 ) / 255;
  193. this.g = ( hex >> 8 & 255 ) / 255;
  194. this.b = ( hex & 255 ) / 255;
  195. return this;
  196. },
  197. setRGB: function ( r, g, b ) {
  198. this.r = r;
  199. this.g = g;
  200. this.b = b;
  201. return this;
  202. },
  203. setHSL: function ( h, s, l ) {
  204. // h,s,l ranges are in 0.0 - 1.0
  205. if ( s === 0 ) {
  206. this.r = this.g = this.b = l;
  207. } else {
  208. var hue2rgb = function ( p, q, t ) {
  209. if ( t < 0 ) t += 1;
  210. if ( t > 1 ) t -= 1;
  211. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  212. if ( t < 1 / 2 ) return q;
  213. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  214. return p;
  215. };
  216. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  217. var q = ( 2 * l ) - p;
  218. this.r = hue2rgb( q, p, h + 1 / 3 );
  219. this.g = hue2rgb( q, p, h );
  220. this.b = hue2rgb( q, p, h - 1 / 3 );
  221. }
  222. return this;
  223. },
  224. setStyle: function ( style ) {
  225. // rgb(255,0,0)
  226. if ( /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.test( style ) ) {
  227. var color = /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.exec( style );
  228. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  229. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  230. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  231. return this;
  232. }
  233. // rgb(100%,0%,0%)
  234. if ( /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.test( style ) ) {
  235. var color = /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.exec( style );
  236. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  237. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  238. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  239. return this;
  240. }
  241. // #ff0000
  242. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  243. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  244. this.setHex( parseInt( color[ 1 ], 16 ) );
  245. return this;
  246. }
  247. // #f00
  248. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  249. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  250. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  251. return this;
  252. }
  253. // red
  254. if ( /^(\w+)$/i.test( style ) ) {
  255. this.setHex( THREE.ColorKeywords[ style ] );
  256. return this;
  257. }
  258. },
  259. copy: function ( color ) {
  260. this.r = color.r;
  261. this.g = color.g;
  262. this.b = color.b;
  263. return this;
  264. },
  265. copyGammaToLinear: function ( color ) {
  266. this.r = color.r * color.r;
  267. this.g = color.g * color.g;
  268. this.b = color.b * color.b;
  269. return this;
  270. },
  271. copyLinearToGamma: function ( color ) {
  272. this.r = Math.sqrt( color.r );
  273. this.g = Math.sqrt( color.g );
  274. this.b = Math.sqrt( color.b );
  275. return this;
  276. },
  277. convertGammaToLinear: function () {
  278. var r = this.r, g = this.g, b = this.b;
  279. this.r = r * r;
  280. this.g = g * g;
  281. this.b = b * b;
  282. return this;
  283. },
  284. convertLinearToGamma: function () {
  285. this.r = Math.sqrt( this.r );
  286. this.g = Math.sqrt( this.g );
  287. this.b = Math.sqrt( this.b );
  288. return this;
  289. },
  290. getHex: function () {
  291. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  292. },
  293. getHexString: function () {
  294. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  295. },
  296. getHSL: function ( optionalTarget ) {
  297. // h,s,l ranges are in 0.0 - 1.0
  298. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  299. var r = this.r, g = this.g, b = this.b;
  300. var max = Math.max( r, g, b );
  301. var min = Math.min( r, g, b );
  302. var hue, saturation;
  303. var lightness = ( min + max ) / 2.0;
  304. if ( min === max ) {
  305. hue = 0;
  306. saturation = 0;
  307. } else {
  308. var delta = max - min;
  309. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  310. switch ( max ) {
  311. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  312. case g: hue = ( b - r ) / delta + 2; break;
  313. case b: hue = ( r - g ) / delta + 4; break;
  314. }
  315. hue /= 6;
  316. }
  317. hsl.h = hue;
  318. hsl.s = saturation;
  319. hsl.l = lightness;
  320. return hsl;
  321. },
  322. getStyle: function () {
  323. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  324. },
  325. offsetHSL: function ( h, s, l ) {
  326. var hsl = this.getHSL();
  327. hsl.h += h; hsl.s += s; hsl.l += l;
  328. this.setHSL( hsl.h, hsl.s, hsl.l );
  329. return this;
  330. },
  331. add: function ( color ) {
  332. this.r += color.r;
  333. this.g += color.g;
  334. this.b += color.b;
  335. return this;
  336. },
  337. addColors: function ( color1, color2 ) {
  338. this.r = color1.r + color2.r;
  339. this.g = color1.g + color2.g;
  340. this.b = color1.b + color2.b;
  341. return this;
  342. },
  343. addScalar: function ( s ) {
  344. this.r += s;
  345. this.g += s;
  346. this.b += s;
  347. return this;
  348. },
  349. multiply: function ( color ) {
  350. this.r *= color.r;
  351. this.g *= color.g;
  352. this.b *= color.b;
  353. return this;
  354. },
  355. multiplyScalar: function ( s ) {
  356. this.r *= s;
  357. this.g *= s;
  358. this.b *= s;
  359. return this;
  360. },
  361. lerp: function ( color, alpha ) {
  362. this.r += ( color.r - this.r ) * alpha;
  363. this.g += ( color.g - this.g ) * alpha;
  364. this.b += ( color.b - this.b ) * alpha;
  365. return this;
  366. },
  367. equals: function ( c ) {
  368. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  369. },
  370. fromArray: function ( array ) {
  371. this.r = array[ 0 ];
  372. this.g = array[ 1 ];
  373. this.b = array[ 2 ];
  374. return this;
  375. },
  376. toArray: function () {
  377. return [ this.r, this.g, this.b ];
  378. },
  379. clone: function () {
  380. return new THREE.Color().setRGB( this.r, this.g, this.b );
  381. }
  382. };
  383. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF,
  384. "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2,
  385. "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50,
  386. "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B,
  387. "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B,
  388. "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F,
  389. "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3,
  390. "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222,
  391. "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700,
  392. "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4,
  393. "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00,
  394. "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3,
  395. "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA,
  396. "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32,
  397. "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3,
  398. "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC,
  399. "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD,
  400. "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6,
  401. "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9,
  402. "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F,
  403. "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE,
  404. "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA,
  405. "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0,
  406. "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  407. /**
  408. * @author mikael emtinger / http://gomo.se/
  409. * @author alteredq / http://alteredqualia.com/
  410. * @author WestLangley / http://github.com/WestLangley
  411. * @author bhouston / http://exocortex.com
  412. */
  413. THREE.Quaternion = function ( x, y, z, w ) {
  414. this._x = x || 0;
  415. this._y = y || 0;
  416. this._z = z || 0;
  417. this._w = ( w !== undefined ) ? w : 1;
  418. };
  419. THREE.Quaternion.prototype = {
  420. constructor: THREE.Quaternion,
  421. _x: 0,_y: 0, _z: 0, _w: 0,
  422. _euler: undefined,
  423. _updateEuler: function ( callback ) {
  424. if ( this._euler !== undefined ) {
  425. this._euler.setFromQuaternion( this, undefined, false );
  426. }
  427. },
  428. get x () {
  429. return this._x;
  430. },
  431. set x ( value ) {
  432. this._x = value;
  433. this._updateEuler();
  434. },
  435. get y () {
  436. return this._y;
  437. },
  438. set y ( value ) {
  439. this._y = value;
  440. this._updateEuler();
  441. },
  442. get z () {
  443. return this._z;
  444. },
  445. set z ( value ) {
  446. this._z = value;
  447. this._updateEuler();
  448. },
  449. get w () {
  450. return this._w;
  451. },
  452. set w ( value ) {
  453. this._w = value;
  454. this._updateEuler();
  455. },
  456. set: function ( x, y, z, w ) {
  457. this._x = x;
  458. this._y = y;
  459. this._z = z;
  460. this._w = w;
  461. this._updateEuler();
  462. return this;
  463. },
  464. copy: function ( quaternion ) {
  465. this._x = quaternion._x;
  466. this._y = quaternion._y;
  467. this._z = quaternion._z;
  468. this._w = quaternion._w;
  469. this._updateEuler();
  470. return this;
  471. },
  472. setFromEuler: function ( euler, update ) {
  473. if ( euler instanceof THREE.Euler === false ) {
  474. throw new Error( 'ERROR: Quaternion\'s .setFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  475. }
  476. // http://www.mathworks.com/matlabcentral/fileexchange/
  477. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  478. // content/SpinCalc.m
  479. var c1 = Math.cos( euler._x / 2 );
  480. var c2 = Math.cos( euler._y / 2 );
  481. var c3 = Math.cos( euler._z / 2 );
  482. var s1 = Math.sin( euler._x / 2 );
  483. var s2 = Math.sin( euler._y / 2 );
  484. var s3 = Math.sin( euler._z / 2 );
  485. if ( euler.order === 'XYZ' ) {
  486. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  487. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  488. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  489. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  490. } else if ( euler.order === 'YXZ' ) {
  491. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  492. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  493. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  494. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  495. } else if ( euler.order === 'ZXY' ) {
  496. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  497. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  498. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  499. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  500. } else if ( euler.order === 'ZYX' ) {
  501. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  502. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  503. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  504. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  505. } else if ( euler.order === 'YZX' ) {
  506. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  507. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  508. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  509. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  510. } else if ( euler.order === 'XZY' ) {
  511. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  512. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  513. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  514. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  515. }
  516. if ( update !== false ) this._updateEuler();
  517. return this;
  518. },
  519. setFromAxisAngle: function ( axis, angle ) {
  520. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  521. // axis have to be normalized
  522. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  523. this._x = axis.x * s;
  524. this._y = axis.y * s;
  525. this._z = axis.z * s;
  526. this._w = Math.cos( halfAngle );
  527. this._updateEuler();
  528. return this;
  529. },
  530. setFromRotationMatrix: function ( m ) {
  531. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  532. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  533. var te = m.elements,
  534. m11 = te[0], m12 = te[4], m13 = te[8],
  535. m21 = te[1], m22 = te[5], m23 = te[9],
  536. m31 = te[2], m32 = te[6], m33 = te[10],
  537. trace = m11 + m22 + m33,
  538. s;
  539. if ( trace > 0 ) {
  540. s = 0.5 / Math.sqrt( trace + 1.0 );
  541. this._w = 0.25 / s;
  542. this._x = ( m32 - m23 ) * s;
  543. this._y = ( m13 - m31 ) * s;
  544. this._z = ( m21 - m12 ) * s;
  545. } else if ( m11 > m22 && m11 > m33 ) {
  546. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  547. this._w = (m32 - m23 ) / s;
  548. this._x = 0.25 * s;
  549. this._y = (m12 + m21 ) / s;
  550. this._z = (m13 + m31 ) / s;
  551. } else if ( m22 > m33 ) {
  552. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  553. this._w = (m13 - m31 ) / s;
  554. this._x = (m12 + m21 ) / s;
  555. this._y = 0.25 * s;
  556. this._z = (m23 + m32 ) / s;
  557. } else {
  558. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  559. this._w = ( m21 - m12 ) / s;
  560. this._x = ( m13 + m31 ) / s;
  561. this._y = ( m23 + m32 ) / s;
  562. this._z = 0.25 * s;
  563. }
  564. this._updateEuler();
  565. return this;
  566. },
  567. inverse: function () {
  568. this.conjugate().normalize();
  569. return this;
  570. },
  571. conjugate: function () {
  572. this._x *= -1;
  573. this._y *= -1;
  574. this._z *= -1;
  575. this._updateEuler();
  576. return this;
  577. },
  578. lengthSq: function () {
  579. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  580. },
  581. length: function () {
  582. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  583. },
  584. normalize: function () {
  585. var l = this.length();
  586. if ( l === 0 ) {
  587. this._x = 0;
  588. this._y = 0;
  589. this._z = 0;
  590. this._w = 1;
  591. } else {
  592. l = 1 / l;
  593. this._x = this._x * l;
  594. this._y = this._y * l;
  595. this._z = this._z * l;
  596. this._w = this._w * l;
  597. }
  598. return this;
  599. },
  600. multiply: function ( q, p ) {
  601. if ( p !== undefined ) {
  602. console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  603. return this.multiplyQuaternions( q, p );
  604. }
  605. return this.multiplyQuaternions( this, q );
  606. },
  607. multiplyQuaternions: function ( a, b ) {
  608. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  609. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  610. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  611. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  612. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  613. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  614. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  615. this._updateEuler();
  616. return this;
  617. },
  618. multiplyVector3: function ( vector ) {
  619. console.warn( 'DEPRECATED: Quaternion\'s .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  620. return vector.applyQuaternion( this );
  621. },
  622. slerp: function ( qb, t ) {
  623. var x = this._x, y = this._y, z = this._z, w = this._w;
  624. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  625. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  626. if ( cosHalfTheta < 0 ) {
  627. this._w = -qb._w;
  628. this._x = -qb._x;
  629. this._y = -qb._y;
  630. this._z = -qb._z;
  631. cosHalfTheta = -cosHalfTheta;
  632. } else {
  633. this.copy( qb );
  634. }
  635. if ( cosHalfTheta >= 1.0 ) {
  636. this._w = w;
  637. this._x = x;
  638. this._y = y;
  639. this._z = z;
  640. return this;
  641. }
  642. var halfTheta = Math.acos( cosHalfTheta );
  643. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  644. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  645. this._w = 0.5 * ( w + this._w );
  646. this._x = 0.5 * ( x + this._x );
  647. this._y = 0.5 * ( y + this._y );
  648. this._z = 0.5 * ( z + this._z );
  649. return this;
  650. }
  651. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  652. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  653. this._w = ( w * ratioA + this._w * ratioB );
  654. this._x = ( x * ratioA + this._x * ratioB );
  655. this._y = ( y * ratioA + this._y * ratioB );
  656. this._z = ( z * ratioA + this._z * ratioB );
  657. this._updateEuler();
  658. return this;
  659. },
  660. equals: function ( quaternion ) {
  661. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  662. },
  663. fromArray: function ( array ) {
  664. this._x = array[ 0 ];
  665. this._y = array[ 1 ];
  666. this._z = array[ 2 ];
  667. this._w = array[ 3 ];
  668. this._updateEuler();
  669. return this;
  670. },
  671. toArray: function () {
  672. return [ this._x, this._y, this._z, this._w ];
  673. },
  674. clone: function () {
  675. return new THREE.Quaternion( this._x, this._y, this._z, this._w );
  676. }
  677. };
  678. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  679. return qm.copy( qa ).slerp( qb, t );
  680. }
  681. /**
  682. * @author mrdoob / http://mrdoob.com/
  683. * @author philogb / http://blog.thejit.org/
  684. * @author egraether / http://egraether.com/
  685. * @author zz85 / http://www.lab4games.net/zz85/blog
  686. */
  687. THREE.Vector2 = function ( x, y ) {
  688. this.x = x || 0;
  689. this.y = y || 0;
  690. };
  691. THREE.Vector2.prototype = {
  692. constructor: THREE.Vector2,
  693. set: function ( x, y ) {
  694. this.x = x;
  695. this.y = y;
  696. return this;
  697. },
  698. setX: function ( x ) {
  699. this.x = x;
  700. return this;
  701. },
  702. setY: function ( y ) {
  703. this.y = y;
  704. return this;
  705. },
  706. setComponent: function ( index, value ) {
  707. switch ( index ) {
  708. case 0: this.x = value; break;
  709. case 1: this.y = value; break;
  710. default: throw new Error( "index is out of range: " + index );
  711. }
  712. },
  713. getComponent: function ( index ) {
  714. switch ( index ) {
  715. case 0: return this.x;
  716. case 1: return this.y;
  717. default: throw new Error( "index is out of range: " + index );
  718. }
  719. },
  720. copy: function ( v ) {
  721. this.x = v.x;
  722. this.y = v.y;
  723. return this;
  724. },
  725. add: function ( v, w ) {
  726. if ( w !== undefined ) {
  727. console.warn( 'DEPRECATED: Vector2\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  728. return this.addVectors( v, w );
  729. }
  730. this.x += v.x;
  731. this.y += v.y;
  732. return this;
  733. },
  734. addVectors: function ( a, b ) {
  735. this.x = a.x + b.x;
  736. this.y = a.y + b.y;
  737. return this;
  738. },
  739. addScalar: function ( s ) {
  740. this.x += s;
  741. this.y += s;
  742. return this;
  743. },
  744. sub: function ( v, w ) {
  745. if ( w !== undefined ) {
  746. console.warn( 'DEPRECATED: Vector2\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  747. return this.subVectors( v, w );
  748. }
  749. this.x -= v.x;
  750. this.y -= v.y;
  751. return this;
  752. },
  753. subVectors: function ( a, b ) {
  754. this.x = a.x - b.x;
  755. this.y = a.y - b.y;
  756. return this;
  757. },
  758. multiplyScalar: function ( s ) {
  759. this.x *= s;
  760. this.y *= s;
  761. return this;
  762. },
  763. divideScalar: function ( scalar ) {
  764. if ( scalar !== 0 ) {
  765. var invScalar = 1 / scalar;
  766. this.x *= invScalar;
  767. this.y *= invScalar;
  768. } else {
  769. this.x = 0;
  770. this.y = 0;
  771. }
  772. return this;
  773. },
  774. min: function ( v ) {
  775. if ( this.x > v.x ) {
  776. this.x = v.x;
  777. }
  778. if ( this.y > v.y ) {
  779. this.y = v.y;
  780. }
  781. return this;
  782. },
  783. max: function ( v ) {
  784. if ( this.x < v.x ) {
  785. this.x = v.x;
  786. }
  787. if ( this.y < v.y ) {
  788. this.y = v.y;
  789. }
  790. return this;
  791. },
  792. clamp: function ( min, max ) {
  793. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  794. if ( this.x < min.x ) {
  795. this.x = min.x;
  796. } else if ( this.x > max.x ) {
  797. this.x = max.x;
  798. }
  799. if ( this.y < min.y ) {
  800. this.y = min.y;
  801. } else if ( this.y > max.y ) {
  802. this.y = max.y;
  803. }
  804. return this;
  805. },
  806. negate: function() {
  807. return this.multiplyScalar( - 1 );
  808. },
  809. dot: function ( v ) {
  810. return this.x * v.x + this.y * v.y;
  811. },
  812. lengthSq: function () {
  813. return this.x * this.x + this.y * this.y;
  814. },
  815. length: function () {
  816. return Math.sqrt( this.x * this.x + this.y * this.y );
  817. },
  818. normalize: function () {
  819. return this.divideScalar( this.length() );
  820. },
  821. distanceTo: function ( v ) {
  822. return Math.sqrt( this.distanceToSquared( v ) );
  823. },
  824. distanceToSquared: function ( v ) {
  825. var dx = this.x - v.x, dy = this.y - v.y;
  826. return dx * dx + dy * dy;
  827. },
  828. setLength: function ( l ) {
  829. var oldLength = this.length();
  830. if ( oldLength !== 0 && l !== oldLength ) {
  831. this.multiplyScalar( l / oldLength );
  832. }
  833. return this;
  834. },
  835. lerp: function ( v, alpha ) {
  836. this.x += ( v.x - this.x ) * alpha;
  837. this.y += ( v.y - this.y ) * alpha;
  838. return this;
  839. },
  840. equals: function( v ) {
  841. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  842. },
  843. fromArray: function ( array ) {
  844. this.x = array[ 0 ];
  845. this.y = array[ 1 ];
  846. return this;
  847. },
  848. toArray: function () {
  849. return [ this.x, this.y ];
  850. },
  851. clone: function () {
  852. return new THREE.Vector2( this.x, this.y );
  853. }
  854. };
  855. /**
  856. * @author mrdoob / http://mrdoob.com/
  857. * @author *kile / http://kile.stravaganza.org/
  858. * @author philogb / http://blog.thejit.org/
  859. * @author mikael emtinger / http://gomo.se/
  860. * @author egraether / http://egraether.com/
  861. * @author WestLangley / http://github.com/WestLangley
  862. */
  863. THREE.Vector3 = function ( x, y, z ) {
  864. this.x = x || 0;
  865. this.y = y || 0;
  866. this.z = z || 0;
  867. };
  868. THREE.Vector3.prototype = {
  869. constructor: THREE.Vector3,
  870. set: function ( x, y, z ) {
  871. this.x = x;
  872. this.y = y;
  873. this.z = z;
  874. return this;
  875. },
  876. setX: function ( x ) {
  877. this.x = x;
  878. return this;
  879. },
  880. setY: function ( y ) {
  881. this.y = y;
  882. return this;
  883. },
  884. setZ: function ( z ) {
  885. this.z = z;
  886. return this;
  887. },
  888. setComponent: function ( index, value ) {
  889. switch ( index ) {
  890. case 0: this.x = value; break;
  891. case 1: this.y = value; break;
  892. case 2: this.z = value; break;
  893. default: throw new Error( "index is out of range: " + index );
  894. }
  895. },
  896. getComponent: function ( index ) {
  897. switch ( index ) {
  898. case 0: return this.x;
  899. case 1: return this.y;
  900. case 2: return this.z;
  901. default: throw new Error( "index is out of range: " + index );
  902. }
  903. },
  904. copy: function ( v ) {
  905. this.x = v.x;
  906. this.y = v.y;
  907. this.z = v.z;
  908. return this;
  909. },
  910. add: function ( v, w ) {
  911. if ( w !== undefined ) {
  912. console.warn( 'DEPRECATED: Vector3\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  913. return this.addVectors( v, w );
  914. }
  915. this.x += v.x;
  916. this.y += v.y;
  917. this.z += v.z;
  918. return this;
  919. },
  920. addScalar: function ( s ) {
  921. this.x += s;
  922. this.y += s;
  923. this.z += s;
  924. return this;
  925. },
  926. addVectors: function ( a, b ) {
  927. this.x = a.x + b.x;
  928. this.y = a.y + b.y;
  929. this.z = a.z + b.z;
  930. return this;
  931. },
  932. sub: function ( v, w ) {
  933. if ( w !== undefined ) {
  934. console.warn( 'DEPRECATED: Vector3\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  935. return this.subVectors( v, w );
  936. }
  937. this.x -= v.x;
  938. this.y -= v.y;
  939. this.z -= v.z;
  940. return this;
  941. },
  942. subVectors: function ( a, b ) {
  943. this.x = a.x - b.x;
  944. this.y = a.y - b.y;
  945. this.z = a.z - b.z;
  946. return this;
  947. },
  948. multiply: function ( v, w ) {
  949. if ( w !== undefined ) {
  950. console.warn( 'DEPRECATED: Vector3\'s .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  951. return this.multiplyVectors( v, w );
  952. }
  953. this.x *= v.x;
  954. this.y *= v.y;
  955. this.z *= v.z;
  956. return this;
  957. },
  958. multiplyScalar: function ( scalar ) {
  959. this.x *= scalar;
  960. this.y *= scalar;
  961. this.z *= scalar;
  962. return this;
  963. },
  964. multiplyVectors: function ( a, b ) {
  965. this.x = a.x * b.x;
  966. this.y = a.y * b.y;
  967. this.z = a.z * b.z;
  968. return this;
  969. },
  970. applyMatrix3: function ( m ) {
  971. var x = this.x;
  972. var y = this.y;
  973. var z = this.z;
  974. var e = m.elements;
  975. this.x = e[0] * x + e[3] * y + e[6] * z;
  976. this.y = e[1] * x + e[4] * y + e[7] * z;
  977. this.z = e[2] * x + e[5] * y + e[8] * z;
  978. return this;
  979. },
  980. applyMatrix4: function ( m ) {
  981. // input: THREE.Matrix4 affine matrix
  982. var x = this.x, y = this.y, z = this.z;
  983. var e = m.elements;
  984. this.x = e[0] * x + e[4] * y + e[8] * z + e[12];
  985. this.y = e[1] * x + e[5] * y + e[9] * z + e[13];
  986. this.z = e[2] * x + e[6] * y + e[10] * z + e[14];
  987. return this;
  988. },
  989. applyProjection: function ( m ) {
  990. // input: THREE.Matrix4 projection matrix
  991. var x = this.x, y = this.y, z = this.z;
  992. var e = m.elements;
  993. var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] ); // perspective divide
  994. this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
  995. this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
  996. this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
  997. return this;
  998. },
  999. applyQuaternion: function ( q ) {
  1000. var x = this.x;
  1001. var y = this.y;
  1002. var z = this.z;
  1003. var qx = q.x;
  1004. var qy = q.y;
  1005. var qz = q.z;
  1006. var qw = q.w;
  1007. // calculate quat * vector
  1008. var ix = qw * x + qy * z - qz * y;
  1009. var iy = qw * y + qz * x - qx * z;
  1010. var iz = qw * z + qx * y - qy * x;
  1011. var iw = -qx * x - qy * y - qz * z;
  1012. // calculate result * inverse quat
  1013. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  1014. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  1015. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  1016. return this;
  1017. },
  1018. transformDirection: function ( m ) {
  1019. // input: THREE.Matrix4 affine matrix
  1020. // vector interpreted as a direction
  1021. var x = this.x, y = this.y, z = this.z;
  1022. var e = m.elements;
  1023. this.x = e[0] * x + e[4] * y + e[8] * z;
  1024. this.y = e[1] * x + e[5] * y + e[9] * z;
  1025. this.z = e[2] * x + e[6] * y + e[10] * z;
  1026. this.normalize();
  1027. return this;
  1028. },
  1029. divide: function ( v ) {
  1030. this.x /= v.x;
  1031. this.y /= v.y;
  1032. this.z /= v.z;
  1033. return this;
  1034. },
  1035. divideScalar: function ( scalar ) {
  1036. if ( scalar !== 0 ) {
  1037. var invScalar = 1 / scalar;
  1038. this.x *= invScalar;
  1039. this.y *= invScalar;
  1040. this.z *= invScalar;
  1041. } else {
  1042. this.x = 0;
  1043. this.y = 0;
  1044. this.z = 0;
  1045. }
  1046. return this;
  1047. },
  1048. min: function ( v ) {
  1049. if ( this.x > v.x ) {
  1050. this.x = v.x;
  1051. }
  1052. if ( this.y > v.y ) {
  1053. this.y = v.y;
  1054. }
  1055. if ( this.z > v.z ) {
  1056. this.z = v.z;
  1057. }
  1058. return this;
  1059. },
  1060. max: function ( v ) {
  1061. if ( this.x < v.x ) {
  1062. this.x = v.x;
  1063. }
  1064. if ( this.y < v.y ) {
  1065. this.y = v.y;
  1066. }
  1067. if ( this.z < v.z ) {
  1068. this.z = v.z;
  1069. }
  1070. return this;
  1071. },
  1072. clamp: function ( min, max ) {
  1073. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1074. if ( this.x < min.x ) {
  1075. this.x = min.x;
  1076. } else if ( this.x > max.x ) {
  1077. this.x = max.x;
  1078. }
  1079. if ( this.y < min.y ) {
  1080. this.y = min.y;
  1081. } else if ( this.y > max.y ) {
  1082. this.y = max.y;
  1083. }
  1084. if ( this.z < min.z ) {
  1085. this.z = min.z;
  1086. } else if ( this.z > max.z ) {
  1087. this.z = max.z;
  1088. }
  1089. return this;
  1090. },
  1091. negate: function () {
  1092. return this.multiplyScalar( - 1 );
  1093. },
  1094. dot: function ( v ) {
  1095. return this.x * v.x + this.y * v.y + this.z * v.z;
  1096. },
  1097. lengthSq: function () {
  1098. return this.x * this.x + this.y * this.y + this.z * this.z;
  1099. },
  1100. length: function () {
  1101. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1102. },
  1103. lengthManhattan: function () {
  1104. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1105. },
  1106. normalize: function () {
  1107. return this.divideScalar( this.length() );
  1108. },
  1109. setLength: function ( l ) {
  1110. var oldLength = this.length();
  1111. if ( oldLength !== 0 && l !== oldLength ) {
  1112. this.multiplyScalar( l / oldLength );
  1113. }
  1114. return this;
  1115. },
  1116. lerp: function ( v, alpha ) {
  1117. this.x += ( v.x - this.x ) * alpha;
  1118. this.y += ( v.y - this.y ) * alpha;
  1119. this.z += ( v.z - this.z ) * alpha;
  1120. return this;
  1121. },
  1122. cross: function ( v, w ) {
  1123. if ( w !== undefined ) {
  1124. console.warn( 'DEPRECATED: Vector3\'s .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1125. return this.crossVectors( v, w );
  1126. }
  1127. var x = this.x, y = this.y, z = this.z;
  1128. this.x = y * v.z - z * v.y;
  1129. this.y = z * v.x - x * v.z;
  1130. this.z = x * v.y - y * v.x;
  1131. return this;
  1132. },
  1133. crossVectors: function ( a, b ) {
  1134. var ax = a.x, ay = a.y, az = a.z;
  1135. var bx = b.x, by = b.y, bz = b.z;
  1136. this.x = ay * bz - az * by;
  1137. this.y = az * bx - ax * bz;
  1138. this.z = ax * by - ay * bx;
  1139. return this;
  1140. },
  1141. angleTo: function ( v ) {
  1142. var theta = this.dot( v ) / ( this.length() * v.length() );
  1143. // clamp, to handle numerical problems
  1144. return Math.acos( THREE.Math.clamp( theta, -1, 1 ) );
  1145. },
  1146. distanceTo: function ( v ) {
  1147. return Math.sqrt( this.distanceToSquared( v ) );
  1148. },
  1149. distanceToSquared: function ( v ) {
  1150. var dx = this.x - v.x;
  1151. var dy = this.y - v.y;
  1152. var dz = this.z - v.z;
  1153. return dx * dx + dy * dy + dz * dz;
  1154. },
  1155. setEulerFromRotationMatrix: function ( m, order ) {
  1156. console.error( "REMOVED: Vector3\'s setEulerFromRotationMatrix has been removed in favor of Euler.setFromRotationMatrix(), please update your code.");
  1157. },
  1158. setEulerFromQuaternion: function ( q, order ) {
  1159. console.error( "REMOVED: Vector3\'s setEulerFromQuaternion: has been removed in favor of Euler.setFromQuaternion(), please update your code.");
  1160. },
  1161. getPositionFromMatrix: function ( m ) {
  1162. console.warn( "DEPRECATED: Vector3\'s .getPositionFromMatrix() has been renamed to .setFromMatrixPosition(). Please update your code." );
  1163. return this.setFromMatrixPosition( m );
  1164. },
  1165. getScaleFromMatrix: function ( m ) {
  1166. console.warn( "DEPRECATED: Vector3\'s .getScaleFromMatrix() has been renamed to .setFromMatrixScale(). Please update your code." );
  1167. return this.setFromMatrixScale( m );
  1168. },
  1169. getColumnFromMatrix: function ( index, matrix ) {
  1170. console.warn( "DEPRECATED: Vector3\'s .getColumnFromMatrix() has been renamed to .setFromMatrixColumn(). Please update your code." );
  1171. return this.setFromMatrixColumn( index, matrix );
  1172. },
  1173. setFromMatrixPosition: function ( m ) {
  1174. this.x = m.elements[ 12 ];
  1175. this.y = m.elements[ 13 ];
  1176. this.z = m.elements[ 14 ];
  1177. return this;
  1178. },
  1179. setFromMatrixScale: function ( m ) {
  1180. var sx = this.set( m.elements[ 0 ], m.elements[ 1 ], m.elements[ 2 ] ).length();
  1181. var sy = this.set( m.elements[ 4 ], m.elements[ 5 ], m.elements[ 6 ] ).length();
  1182. var sz = this.set( m.elements[ 8 ], m.elements[ 9 ], m.elements[ 10 ] ).length();
  1183. this.x = sx;
  1184. this.y = sy;
  1185. this.z = sz;
  1186. return this;
  1187. },
  1188. setFromMatrixColumn: function ( index, matrix ) {
  1189. var offset = index * 4;
  1190. var me = matrix.elements;
  1191. this.x = me[ offset ];
  1192. this.y = me[ offset + 1 ];
  1193. this.z = me[ offset + 2 ];
  1194. return this;
  1195. },
  1196. equals: function ( v ) {
  1197. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1198. },
  1199. fromArray: function ( array ) {
  1200. this.x = array[ 0 ];
  1201. this.y = array[ 1 ];
  1202. this.z = array[ 2 ];
  1203. return this;
  1204. },
  1205. toArray: function () {
  1206. return [ this.x, this.y, this.z ];
  1207. },
  1208. clone: function () {
  1209. return new THREE.Vector3( this.x, this.y, this.z );
  1210. }
  1211. };
  1212. THREE.extend( THREE.Vector3.prototype, {
  1213. applyEuler: function () {
  1214. var quaternion = new THREE.Quaternion();
  1215. return function ( euler ) {
  1216. if ( euler instanceof THREE.Euler === false ) {
  1217. console.error( 'ERROR: Vector3\'s .applyEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  1218. }
  1219. this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1220. return this;
  1221. };
  1222. }(),
  1223. applyAxisAngle: function () {
  1224. var quaternion = new THREE.Quaternion();
  1225. return function ( axis, angle ) {
  1226. this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1227. return this;
  1228. };
  1229. }(),
  1230. projectOnVector: function () {
  1231. var v1 = new THREE.Vector3();
  1232. return function ( vector ) {
  1233. v1.copy( vector ).normalize();
  1234. var d = this.dot( v1 );
  1235. return this.copy( v1 ).multiplyScalar( d );
  1236. };
  1237. }(),
  1238. projectOnPlane: function () {
  1239. var v1 = new THREE.Vector3();
  1240. return function ( planeNormal ) {
  1241. v1.copy( this ).projectOnVector( planeNormal );
  1242. return this.sub( v1 );
  1243. }
  1244. }(),
  1245. reflect: function () {
  1246. // reflect incident vector off plane orthogonal to normal
  1247. // normal is assumed to have unit length
  1248. var v1 = new THREE.Vector3();
  1249. return function ( normal ) {
  1250. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1251. }
  1252. }()
  1253. } );
  1254. /**
  1255. * @author supereggbert / http://www.paulbrunt.co.uk/
  1256. * @author philogb / http://blog.thejit.org/
  1257. * @author mikael emtinger / http://gomo.se/
  1258. * @author egraether / http://egraether.com/
  1259. * @author WestLangley / http://github.com/WestLangley
  1260. */
  1261. THREE.Vector4 = function ( x, y, z, w ) {
  1262. this.x = x || 0;
  1263. this.y = y || 0;
  1264. this.z = z || 0;
  1265. this.w = ( w !== undefined ) ? w : 1;
  1266. };
  1267. THREE.Vector4.prototype = {
  1268. constructor: THREE.Vector4,
  1269. set: function ( x, y, z, w ) {
  1270. this.x = x;
  1271. this.y = y;
  1272. this.z = z;
  1273. this.w = w;
  1274. return this;
  1275. },
  1276. setX: function ( x ) {
  1277. this.x = x;
  1278. return this;
  1279. },
  1280. setY: function ( y ) {
  1281. this.y = y;
  1282. return this;
  1283. },
  1284. setZ: function ( z ) {
  1285. this.z = z;
  1286. return this;
  1287. },
  1288. setW: function ( w ) {
  1289. this.w = w;
  1290. return this;
  1291. },
  1292. setComponent: function ( index, value ) {
  1293. switch ( index ) {
  1294. case 0: this.x = value; break;
  1295. case 1: this.y = value; break;
  1296. case 2: this.z = value; break;
  1297. case 3: this.w = value; break;
  1298. default: throw new Error( "index is out of range: " + index );
  1299. }
  1300. },
  1301. getComponent: function ( index ) {
  1302. switch ( index ) {
  1303. case 0: return this.x;
  1304. case 1: return this.y;
  1305. case 2: return this.z;
  1306. case 3: return this.w;
  1307. default: throw new Error( "index is out of range: " + index );
  1308. }
  1309. },
  1310. copy: function ( v ) {
  1311. this.x = v.x;
  1312. this.y = v.y;
  1313. this.z = v.z;
  1314. this.w = ( v.w !== undefined ) ? v.w : 1;
  1315. return this;
  1316. },
  1317. add: function ( v, w ) {
  1318. if ( w !== undefined ) {
  1319. console.warn( 'DEPRECATED: Vector4\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1320. return this.addVectors( v, w );
  1321. }
  1322. this.x += v.x;
  1323. this.y += v.y;
  1324. this.z += v.z;
  1325. this.w += v.w;
  1326. return this;
  1327. },
  1328. addScalar: function ( s ) {
  1329. this.x += s;
  1330. this.y += s;
  1331. this.z += s;
  1332. this.w += s;
  1333. return this;
  1334. },
  1335. addVectors: function ( a, b ) {
  1336. this.x = a.x + b.x;
  1337. this.y = a.y + b.y;
  1338. this.z = a.z + b.z;
  1339. this.w = a.w + b.w;
  1340. return this;
  1341. },
  1342. sub: function ( v, w ) {
  1343. if ( w !== undefined ) {
  1344. console.warn( 'DEPRECATED: Vector4\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1345. return this.subVectors( v, w );
  1346. }
  1347. this.x -= v.x;
  1348. this.y -= v.y;
  1349. this.z -= v.z;
  1350. this.w -= v.w;
  1351. return this;
  1352. },
  1353. subVectors: function ( a, b ) {
  1354. this.x = a.x - b.x;
  1355. this.y = a.y - b.y;
  1356. this.z = a.z - b.z;
  1357. this.w = a.w - b.w;
  1358. return this;
  1359. },
  1360. multiplyScalar: function ( scalar ) {
  1361. this.x *= scalar;
  1362. this.y *= scalar;
  1363. this.z *= scalar;
  1364. this.w *= scalar;
  1365. return this;
  1366. },
  1367. applyMatrix4: function ( m ) {
  1368. var x = this.x;
  1369. var y = this.y;
  1370. var z = this.z;
  1371. var w = this.w;
  1372. var e = m.elements;
  1373. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1374. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1375. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1376. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1377. return this;
  1378. },
  1379. divideScalar: function ( scalar ) {
  1380. if ( scalar !== 0 ) {
  1381. var invScalar = 1 / scalar;
  1382. this.x *= invScalar;
  1383. this.y *= invScalar;
  1384. this.z *= invScalar;
  1385. this.w *= invScalar;
  1386. } else {
  1387. this.x = 0;
  1388. this.y = 0;
  1389. this.z = 0;
  1390. this.w = 1;
  1391. }
  1392. return this;
  1393. },
  1394. setAxisAngleFromQuaternion: function ( q ) {
  1395. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1396. // q is assumed to be normalized
  1397. this.w = 2 * Math.acos( q.w );
  1398. var s = Math.sqrt( 1 - q.w * q.w );
  1399. if ( s < 0.0001 ) {
  1400. this.x = 1;
  1401. this.y = 0;
  1402. this.z = 0;
  1403. } else {
  1404. this.x = q.x / s;
  1405. this.y = q.y / s;
  1406. this.z = q.z / s;
  1407. }
  1408. return this;
  1409. },
  1410. setAxisAngleFromRotationMatrix: function ( m ) {
  1411. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1412. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1413. var angle, x, y, z, // variables for result
  1414. epsilon = 0.01, // margin to allow for rounding errors
  1415. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1416. te = m.elements,
  1417. m11 = te[0], m12 = te[4], m13 = te[8],
  1418. m21 = te[1], m22 = te[5], m23 = te[9],
  1419. m31 = te[2], m32 = te[6], m33 = te[10];
  1420. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1421. && ( Math.abs( m13 - m31 ) < epsilon )
  1422. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1423. // singularity found
  1424. // first check for identity matrix which must have +1 for all terms
  1425. // in leading diagonal and zero in other terms
  1426. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1427. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1428. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1429. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1430. // this singularity is identity matrix so angle = 0
  1431. this.set( 1, 0, 0, 0 );
  1432. return this; // zero angle, arbitrary axis
  1433. }
  1434. // otherwise this singularity is angle = 180
  1435. angle = Math.PI;
  1436. var xx = ( m11 + 1 ) / 2;
  1437. var yy = ( m22 + 1 ) / 2;
  1438. var zz = ( m33 + 1 ) / 2;
  1439. var xy = ( m12 + m21 ) / 4;
  1440. var xz = ( m13 + m31 ) / 4;
  1441. var yz = ( m23 + m32 ) / 4;
  1442. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1443. if ( xx < epsilon ) {
  1444. x = 0;
  1445. y = 0.707106781;
  1446. z = 0.707106781;
  1447. } else {
  1448. x = Math.sqrt( xx );
  1449. y = xy / x;
  1450. z = xz / x;
  1451. }
  1452. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1453. if ( yy < epsilon ) {
  1454. x = 0.707106781;
  1455. y = 0;
  1456. z = 0.707106781;
  1457. } else {
  1458. y = Math.sqrt( yy );
  1459. x = xy / y;
  1460. z = yz / y;
  1461. }
  1462. } else { // m33 is the largest diagonal term so base result on this
  1463. if ( zz < epsilon ) {
  1464. x = 0.707106781;
  1465. y = 0.707106781;
  1466. z = 0;
  1467. } else {
  1468. z = Math.sqrt( zz );
  1469. x = xz / z;
  1470. y = yz / z;
  1471. }
  1472. }
  1473. this.set( x, y, z, angle );
  1474. return this; // return 180 deg rotation
  1475. }
  1476. // as we have reached here there are no singularities so we can handle normally
  1477. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1478. + ( m13 - m31 ) * ( m13 - m31 )
  1479. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1480. if ( Math.abs( s ) < 0.001 ) s = 1;
  1481. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1482. // caught by singularity test above, but I've left it in just in case
  1483. this.x = ( m32 - m23 ) / s;
  1484. this.y = ( m13 - m31 ) / s;
  1485. this.z = ( m21 - m12 ) / s;
  1486. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1487. return this;
  1488. },
  1489. min: function ( v ) {
  1490. if ( this.x > v.x ) {
  1491. this.x = v.x;
  1492. }
  1493. if ( this.y > v.y ) {
  1494. this.y = v.y;
  1495. }
  1496. if ( this.z > v.z ) {
  1497. this.z = v.z;
  1498. }
  1499. if ( this.w > v.w ) {
  1500. this.w = v.w;
  1501. }
  1502. return this;
  1503. },
  1504. max: function ( v ) {
  1505. if ( this.x < v.x ) {
  1506. this.x = v.x;
  1507. }
  1508. if ( this.y < v.y ) {
  1509. this.y = v.y;
  1510. }
  1511. if ( this.z < v.z ) {
  1512. this.z = v.z;
  1513. }
  1514. if ( this.w < v.w ) {
  1515. this.w = v.w;
  1516. }
  1517. return this;
  1518. },
  1519. clamp: function ( min, max ) {
  1520. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1521. if ( this.x < min.x ) {
  1522. this.x = min.x;
  1523. } else if ( this.x > max.x ) {
  1524. this.x = max.x;
  1525. }
  1526. if ( this.y < min.y ) {
  1527. this.y = min.y;
  1528. } else if ( this.y > max.y ) {
  1529. this.y = max.y;
  1530. }
  1531. if ( this.z < min.z ) {
  1532. this.z = min.z;
  1533. } else if ( this.z > max.z ) {
  1534. this.z = max.z;
  1535. }
  1536. if ( this.w < min.w ) {
  1537. this.w = min.w;
  1538. } else if ( this.w > max.w ) {
  1539. this.w = max.w;
  1540. }
  1541. return this;
  1542. },
  1543. negate: function() {
  1544. return this.multiplyScalar( -1 );
  1545. },
  1546. dot: function ( v ) {
  1547. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1548. },
  1549. lengthSq: function () {
  1550. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1551. },
  1552. length: function () {
  1553. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1554. },
  1555. lengthManhattan: function () {
  1556. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1557. },
  1558. normalize: function () {
  1559. return this.divideScalar( this.length() );
  1560. },
  1561. setLength: function ( l ) {
  1562. var oldLength = this.length();
  1563. if ( oldLength !== 0 && l !== oldLength ) {
  1564. this.multiplyScalar( l / oldLength );
  1565. }
  1566. return this;
  1567. },
  1568. lerp: function ( v, alpha ) {
  1569. this.x += ( v.x - this.x ) * alpha;
  1570. this.y += ( v.y - this.y ) * alpha;
  1571. this.z += ( v.z - this.z ) * alpha;
  1572. this.w += ( v.w - this.w ) * alpha;
  1573. return this;
  1574. },
  1575. equals: function ( v ) {
  1576. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1577. },
  1578. fromArray: function ( array ) {
  1579. this.x = array[ 0 ];
  1580. this.y = array[ 1 ];
  1581. this.z = array[ 2 ];
  1582. this.w = array[ 3 ];
  1583. return this;
  1584. },
  1585. toArray: function () {
  1586. return [ this.x, this.y, this.z, this.w ];
  1587. },
  1588. clone: function () {
  1589. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1590. }
  1591. };
  1592. /**
  1593. * @author mrdoob / http://mrdoob.com/
  1594. * @author WestLangley / http://github.com/WestLangley
  1595. * @author bhouston / http://exocortex.com
  1596. */
  1597. THREE.Euler = function ( x, y, z, order ) {
  1598. this._x = x || 0;
  1599. this._y = y || 0;
  1600. this._z = z || 0;
  1601. this._order = order || THREE.Euler.DefaultOrder;
  1602. };
  1603. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1604. THREE.Euler.DefaultOrder = 'XYZ';
  1605. THREE.Euler.prototype = {
  1606. constructor: THREE.Euler,
  1607. _x: 0, _y: 0, _z: 0, _order: THREE.Euler.DefaultOrder,
  1608. _quaternion: undefined,
  1609. _updateQuaternion: function () {
  1610. if ( this._quaternion !== undefined ) {
  1611. this._quaternion.setFromEuler( this, false );
  1612. }
  1613. },
  1614. get x () {
  1615. return this._x;
  1616. },
  1617. set x ( value ) {
  1618. this._x = value;
  1619. this._updateQuaternion();
  1620. },
  1621. get y () {
  1622. return this._y;
  1623. },
  1624. set y ( value ) {
  1625. this._y = value;
  1626. this._updateQuaternion();
  1627. },
  1628. get z () {
  1629. return this._z;
  1630. },
  1631. set z ( value ) {
  1632. this._z = value;
  1633. this._updateQuaternion();
  1634. },
  1635. get order () {
  1636. return this._order;
  1637. },
  1638. set order ( value ) {
  1639. this._order = value;
  1640. this._updateQuaternion();
  1641. },
  1642. set: function ( x, y, z, order ) {
  1643. this._x = x;
  1644. this._y = y;
  1645. this._z = z;
  1646. this._order = order || this._order;
  1647. this._updateQuaternion();
  1648. return this;
  1649. },
  1650. copy: function ( euler ) {
  1651. this._x = euler._x;
  1652. this._y = euler._y;
  1653. this._z = euler._z;
  1654. this._order = euler._order;
  1655. this._updateQuaternion();
  1656. return this;
  1657. },
  1658. setFromRotationMatrix: function ( m, order ) {
  1659. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1660. // clamp, to handle numerical problems
  1661. function clamp( x ) {
  1662. return Math.min( Math.max( x, -1 ), 1 );
  1663. }
  1664. var te = m.elements;
  1665. var m11 = te[0], m12 = te[4], m13 = te[8];
  1666. var m21 = te[1], m22 = te[5], m23 = te[9];
  1667. var m31 = te[2], m32 = te[6], m33 = te[10];
  1668. order = order || this._order;
  1669. if ( order === 'XYZ' ) {
  1670. this._y = Math.asin( clamp( m13 ) );
  1671. if ( Math.abs( m13 ) < 0.99999 ) {
  1672. this._x = Math.atan2( - m23, m33 );
  1673. this._z = Math.atan2( - m12, m11 );
  1674. } else {
  1675. this._x = Math.atan2( m32, m22 );
  1676. this._z = 0;
  1677. }
  1678. } else if ( order === 'YXZ' ) {
  1679. this._x = Math.asin( - clamp( m23 ) );
  1680. if ( Math.abs( m23 ) < 0.99999 ) {
  1681. this._y = Math.atan2( m13, m33 );
  1682. this._z = Math.atan2( m21, m22 );
  1683. } else {
  1684. this._y = Math.atan2( - m31, m11 );
  1685. this._z = 0;
  1686. }
  1687. } else if ( order === 'ZXY' ) {
  1688. this._x = Math.asin( clamp( m32 ) );
  1689. if ( Math.abs( m32 ) < 0.99999 ) {
  1690. this._y = Math.atan2( - m31, m33 );
  1691. this._z = Math.atan2( - m12, m22 );
  1692. } else {
  1693. this._y = 0;
  1694. this._z = Math.atan2( m21, m11 );
  1695. }
  1696. } else if ( order === 'ZYX' ) {
  1697. this._y = Math.asin( - clamp( m31 ) );
  1698. if ( Math.abs( m31 ) < 0.99999 ) {
  1699. this._x = Math.atan2( m32, m33 );
  1700. this._z = Math.atan2( m21, m11 );
  1701. } else {
  1702. this._x = 0;
  1703. this._z = Math.atan2( - m12, m22 );
  1704. }
  1705. } else if ( order === 'YZX' ) {
  1706. this._z = Math.asin( clamp( m21 ) );
  1707. if ( Math.abs( m21 ) < 0.99999 ) {
  1708. this._x = Math.atan2( - m23, m22 );
  1709. this._y = Math.atan2( - m31, m11 );
  1710. } else {
  1711. this._x = 0;
  1712. this._y = Math.atan2( m13, m33 );
  1713. }
  1714. } else if ( order === 'XZY' ) {
  1715. this._z = Math.asin( - clamp( m12 ) );
  1716. if ( Math.abs( m12 ) < 0.99999 ) {
  1717. this._x = Math.atan2( m32, m22 );
  1718. this._y = Math.atan2( m13, m11 );
  1719. } else {
  1720. this._x = Math.atan2( - m23, m33 );
  1721. this._y = 0;
  1722. }
  1723. } else {
  1724. console.warn( 'WARNING: Euler.setFromRotationMatrix() given unsupported order: ' + order )
  1725. }
  1726. this._order = order;
  1727. this._updateQuaternion();
  1728. return this;
  1729. },
  1730. setFromQuaternion: function ( q, order, update ) {
  1731. // q is assumed to be normalized
  1732. // clamp, to handle numerical problems
  1733. function clamp( x ) {
  1734. return Math.min( Math.max( x, -1 ), 1 );
  1735. }
  1736. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  1737. var sqx = q.x * q.x;
  1738. var sqy = q.y * q.y;
  1739. var sqz = q.z * q.z;
  1740. var sqw = q.w * q.w;
  1741. order = order || this._order;
  1742. if ( order === 'XYZ' ) {
  1743. this._x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  1744. this._y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  1745. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  1746. } else if ( order === 'YXZ' ) {
  1747. this._x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  1748. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  1749. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  1750. } else if ( order === 'ZXY' ) {
  1751. this._x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  1752. this._y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  1753. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  1754. } else if ( order === 'ZYX' ) {
  1755. this._x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  1756. this._y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  1757. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  1758. } else if ( order === 'YZX' ) {
  1759. this._x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  1760. this._y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  1761. this._z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  1762. } else if ( order === 'XZY' ) {
  1763. this._x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  1764. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  1765. this._z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  1766. } else {
  1767. console.warn( 'WARNING: Euler.setFromQuaternion() given unsupported order: ' + order )
  1768. }
  1769. this._order = order;
  1770. if ( update !== false ) this._updateQuaternion();
  1771. return this;
  1772. },
  1773. reorder: function () {
  1774. // WARNING: this discards revolution information -bhouston
  1775. var q = new THREE.Quaternion();
  1776. return function ( newOrder ) {
  1777. q.setFromEuler( this );
  1778. this.setFromQuaternion( q, newOrder );
  1779. };
  1780. }(),
  1781. fromArray: function ( array ) {
  1782. this._x = array[ 0 ];
  1783. this._y = array[ 1 ];
  1784. this._z = array[ 2 ];
  1785. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  1786. this._updateQuaternion();
  1787. return this;
  1788. },
  1789. toArray: function () {
  1790. return [ this._x, this._y, this._z, this._order ];
  1791. },
  1792. equals: function ( euler ) {
  1793. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  1794. },
  1795. clone: function () {
  1796. return new THREE.Euler( this._x, this._y, this._z, this._order );
  1797. }
  1798. };
  1799. /**
  1800. * @author bhouston / http://exocortex.com
  1801. */
  1802. THREE.Line3 = function ( start, end ) {
  1803. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  1804. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  1805. };
  1806. THREE.Line3.prototype = {
  1807. constructor: THREE.Line3,
  1808. set: function ( start, end ) {
  1809. this.start.copy( start );
  1810. this.end.copy( end );
  1811. return this;
  1812. },
  1813. copy: function ( line ) {
  1814. this.start.copy( line.start );
  1815. this.end.copy( line.end );
  1816. return this;
  1817. },
  1818. center: function ( optionalTarget ) {
  1819. var result = optionalTarget || new THREE.Vector3();
  1820. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  1821. },
  1822. delta: function ( optionalTarget ) {
  1823. var result = optionalTarget || new THREE.Vector3();
  1824. return result.subVectors( this.end, this.start );
  1825. },
  1826. distanceSq: function () {
  1827. return this.start.distanceToSquared( this.end );
  1828. },
  1829. distance: function () {
  1830. return this.start.distanceTo( this.end );
  1831. },
  1832. at: function ( t, optionalTarget ) {
  1833. var result = optionalTarget || new THREE.Vector3();
  1834. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1835. },
  1836. closestPointToPointParameter: function() {
  1837. var startP = new THREE.Vector3();
  1838. var startEnd = new THREE.Vector3();
  1839. return function ( point, clampToLine ) {
  1840. startP.subVectors( point, this.start );
  1841. startEnd.subVectors( this.end, this.start );
  1842. var startEnd2 = startEnd.dot( startEnd );
  1843. var startEnd_startP = startEnd.dot( startP );
  1844. var t = startEnd_startP / startEnd2;
  1845. if ( clampToLine ) {
  1846. t = THREE.Math.clamp( t, 0, 1 );
  1847. }
  1848. return t;
  1849. };
  1850. }(),
  1851. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  1852. var t = this.closestPointToPointParameter( point, clampToLine );
  1853. var result = optionalTarget || new THREE.Vector3();
  1854. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1855. },
  1856. applyMatrix4: function ( matrix ) {
  1857. this.start.applyMatrix4( matrix );
  1858. this.end.applyMatrix4( matrix );
  1859. return this;
  1860. },
  1861. equals: function ( line ) {
  1862. return line.start.equals( this.start ) && line.end.equals( this.end );
  1863. },
  1864. clone: function () {
  1865. return new THREE.Line3().copy( this );
  1866. }
  1867. };
  1868. /**
  1869. * @author bhouston / http://exocortex.com
  1870. */
  1871. THREE.Box2 = function ( min, max ) {
  1872. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  1873. this.max = ( max !== undefined ) ? max : new THREE.Vector2( -Infinity, -Infinity );
  1874. };
  1875. THREE.Box2.prototype = {
  1876. constructor: THREE.Box2,
  1877. set: function ( min, max ) {
  1878. this.min.copy( min );
  1879. this.max.copy( max );
  1880. return this;
  1881. },
  1882. setFromPoints: function ( points ) {
  1883. if ( points.length > 0 ) {
  1884. var point = points[ 0 ];
  1885. this.min.copy( point );
  1886. this.max.copy( point );
  1887. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1888. point = points[ i ];
  1889. if ( point.x < this.min.x ) {
  1890. this.min.x = point.x;
  1891. } else if ( point.x > this.max.x ) {
  1892. this.max.x = point.x;
  1893. }
  1894. if ( point.y < this.min.y ) {
  1895. this.min.y = point.y;
  1896. } else if ( point.y > this.max.y ) {
  1897. this.max.y = point.y;
  1898. }
  1899. }
  1900. } else {
  1901. this.makeEmpty();
  1902. }
  1903. return this;
  1904. },
  1905. setFromCenterAndSize: function () {
  1906. var v1 = new THREE.Vector2();
  1907. return function ( center, size ) {
  1908. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1909. this.min.copy( center ).sub( halfSize );
  1910. this.max.copy( center ).add( halfSize );
  1911. return this;
  1912. };
  1913. }(),
  1914. copy: function ( box ) {
  1915. this.min.copy( box.min );
  1916. this.max.copy( box.max );
  1917. return this;
  1918. },
  1919. makeEmpty: function () {
  1920. this.min.x = this.min.y = Infinity;
  1921. this.max.x = this.max.y = -Infinity;
  1922. return this;
  1923. },
  1924. empty: function () {
  1925. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1926. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  1927. },
  1928. center: function ( optionalTarget ) {
  1929. var result = optionalTarget || new THREE.Vector2();
  1930. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1931. },
  1932. size: function ( optionalTarget ) {
  1933. var result = optionalTarget || new THREE.Vector2();
  1934. return result.subVectors( this.max, this.min );
  1935. },
  1936. expandByPoint: function ( point ) {
  1937. this.min.min( point );
  1938. this.max.max( point );
  1939. return this;
  1940. },
  1941. expandByVector: function ( vector ) {
  1942. this.min.sub( vector );
  1943. this.max.add( vector );
  1944. return this;
  1945. },
  1946. expandByScalar: function ( scalar ) {
  1947. this.min.addScalar( -scalar );
  1948. this.max.addScalar( scalar );
  1949. return this;
  1950. },
  1951. containsPoint: function ( point ) {
  1952. if ( point.x < this.min.x || point.x > this.max.x ||
  1953. point.y < this.min.y || point.y > this.max.y ) {
  1954. return false;
  1955. }
  1956. return true;
  1957. },
  1958. containsBox: function ( box ) {
  1959. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1960. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  1961. return true;
  1962. }
  1963. return false;
  1964. },
  1965. getParameter: function ( point, optionalTarget ) {
  1966. // This can potentially have a divide by zero if the box
  1967. // has a size dimension of 0.
  1968. var result = optionalTarget || new THREE.Vector2();
  1969. return result.set(
  1970. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1971. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  1972. );
  1973. },
  1974. isIntersectionBox: function ( box ) {
  1975. // using 6 splitting planes to rule out intersections.
  1976. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  1977. box.max.y < this.min.y || box.min.y > this.max.y ) {
  1978. return false;
  1979. }
  1980. return true;
  1981. },
  1982. clampPoint: function ( point, optionalTarget ) {
  1983. var result = optionalTarget || new THREE.Vector2();
  1984. return result.copy( point ).clamp( this.min, this.max );
  1985. },
  1986. distanceToPoint: function () {
  1987. var v1 = new THREE.Vector2();
  1988. return function ( point ) {
  1989. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  1990. return clampedPoint.sub( point ).length();
  1991. };
  1992. }(),
  1993. intersect: function ( box ) {
  1994. this.min.max( box.min );
  1995. this.max.min( box.max );
  1996. return this;
  1997. },
  1998. union: function ( box ) {
  1999. this.min.min( box.min );
  2000. this.max.max( box.max );
  2001. return this;
  2002. },
  2003. translate: function ( offset ) {
  2004. this.min.add( offset );
  2005. this.max.add( offset );
  2006. return this;
  2007. },
  2008. equals: function ( box ) {
  2009. return box.min.equals( this.min ) && box.max.equals( this.max );
  2010. },
  2011. clone: function () {
  2012. return new THREE.Box2().copy( this );
  2013. }
  2014. };
  2015. /**
  2016. * @author bhouston / http://exocortex.com
  2017. * @author WestLangley / http://github.com/WestLangley
  2018. */
  2019. THREE.Box3 = function ( min, max ) {
  2020. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  2021. this.max = ( max !== undefined ) ? max : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  2022. };
  2023. THREE.Box3.prototype = {
  2024. constructor: THREE.Box3,
  2025. set: function ( min, max ) {
  2026. this.min.copy( min );
  2027. this.max.copy( max );
  2028. return this;
  2029. },
  2030. addPoint: function ( point ) {
  2031. if ( point.x < this.min.x ) {
  2032. this.min.x = point.x;
  2033. } else if ( point.x > this.max.x ) {
  2034. this.max.x = point.x;
  2035. }
  2036. if ( point.y < this.min.y ) {
  2037. this.min.y = point.y;
  2038. } else if ( point.y > this.max.y ) {
  2039. this.max.y = point.y;
  2040. }
  2041. if ( point.z < this.min.z ) {
  2042. this.min.z = point.z;
  2043. } else if ( point.z > this.max.z ) {
  2044. this.max.z = point.z;
  2045. }
  2046. },
  2047. setFromPoints: function ( points ) {
  2048. if ( points.length > 0 ) {
  2049. var point = points[ 0 ];
  2050. this.min.copy( point );
  2051. this.max.copy( point );
  2052. for ( var i = 1, il = points.length; i < il; i ++ ) {
  2053. this.addPoint( points[ i ] )
  2054. }
  2055. } else {
  2056. this.makeEmpty();
  2057. }
  2058. return this;
  2059. },
  2060. setFromCenterAndSize: function() {
  2061. var v1 = new THREE.Vector3();
  2062. return function ( center, size ) {
  2063. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2064. this.min.copy( center ).sub( halfSize );
  2065. this.max.copy( center ).add( halfSize );
  2066. return this;
  2067. };
  2068. }(),
  2069. setFromObject: function() {
  2070. // Computes the world-axis-aligned bounding box of an object (including its children),
  2071. // accounting for both the object's, and childrens', world transforms
  2072. var v1 = new THREE.Vector3();
  2073. return function( object ) {
  2074. var scope = this;
  2075. object.updateMatrixWorld( true );
  2076. this.makeEmpty();
  2077. object.traverse( function ( node ) {
  2078. if ( node.geometry !== undefined && node.geometry.vertices !== undefined ) {
  2079. var vertices = node.geometry.vertices;
  2080. for ( var i = 0, il = vertices.length; i < il; i++ ) {
  2081. v1.copy( vertices[ i ] );
  2082. v1.applyMatrix4( node.matrixWorld );
  2083. scope.expandByPoint( v1 );
  2084. }
  2085. }
  2086. } );
  2087. return this;
  2088. };
  2089. }(),
  2090. copy: function ( box ) {
  2091. this.min.copy( box.min );
  2092. this.max.copy( box.max );
  2093. return this;
  2094. },
  2095. makeEmpty: function () {
  2096. this.min.x = this.min.y = this.min.z = Infinity;
  2097. this.max.x = this.max.y = this.max.z = -Infinity;
  2098. return this;
  2099. },
  2100. empty: function () {
  2101. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2102. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2103. },
  2104. center: function ( optionalTarget ) {
  2105. var result = optionalTarget || new THREE.Vector3();
  2106. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2107. },
  2108. size: function ( optionalTarget ) {
  2109. var result = optionalTarget || new THREE.Vector3();
  2110. return result.subVectors( this.max, this.min );
  2111. },
  2112. expandByPoint: function ( point ) {
  2113. this.min.min( point );
  2114. this.max.max( point );
  2115. return this;
  2116. },
  2117. expandByVector: function ( vector ) {
  2118. this.min.sub( vector );
  2119. this.max.add( vector );
  2120. return this;
  2121. },
  2122. expandByScalar: function ( scalar ) {
  2123. this.min.addScalar( -scalar );
  2124. this.max.addScalar( scalar );
  2125. return this;
  2126. },
  2127. containsPoint: function ( point ) {
  2128. if ( point.x < this.min.x || point.x > this.max.x ||
  2129. point.y < this.min.y || point.y > this.max.y ||
  2130. point.z < this.min.z || point.z > this.max.z ) {
  2131. return false;
  2132. }
  2133. return true;
  2134. },
  2135. containsBox: function ( box ) {
  2136. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2137. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2138. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2139. return true;
  2140. }
  2141. return false;
  2142. },
  2143. getParameter: function ( point, optionalTarget ) {
  2144. // This can potentially have a divide by zero if the box
  2145. // has a size dimension of 0.
  2146. var result = optionalTarget || new THREE.Vector3();
  2147. return result.set(
  2148. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2149. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2150. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2151. );
  2152. },
  2153. isIntersectionBox: function ( box ) {
  2154. // using 6 splitting planes to rule out intersections.
  2155. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2156. box.max.y < this.min.y || box.min.y > this.max.y ||
  2157. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2158. return false;
  2159. }
  2160. return true;
  2161. },
  2162. clampPoint: function ( point, optionalTarget ) {
  2163. var result = optionalTarget || new THREE.Vector3();
  2164. return result.copy( point ).clamp( this.min, this.max );
  2165. },
  2166. distanceToPoint: function() {
  2167. var v1 = new THREE.Vector3();
  2168. return function ( point ) {
  2169. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2170. return clampedPoint.sub( point ).length();
  2171. };
  2172. }(),
  2173. getBoundingSphere: function() {
  2174. var v1 = new THREE.Vector3();
  2175. return function ( optionalTarget ) {
  2176. var result = optionalTarget || new THREE.Sphere();
  2177. result.center = this.center();
  2178. result.radius = this.size( v1 ).length() * 0.5;
  2179. return result;
  2180. };
  2181. }(),
  2182. intersect: function ( box ) {
  2183. this.min.max( box.min );
  2184. this.max.min( box.max );
  2185. return this;
  2186. },
  2187. union: function ( box ) {
  2188. this.min.min( box.min );
  2189. this.max.max( box.max );
  2190. return this;
  2191. },
  2192. applyMatrix4: function() {
  2193. var points = [
  2194. new THREE.Vector3(),
  2195. new THREE.Vector3(),
  2196. new THREE.Vector3(),
  2197. new THREE.Vector3(),
  2198. new THREE.Vector3(),
  2199. new THREE.Vector3(),
  2200. new THREE.Vector3(),
  2201. new THREE.Vector3()
  2202. ];
  2203. return function ( matrix ) {
  2204. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2205. points[0].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2206. points[1].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2207. points[2].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2208. points[3].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2209. points[4].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2210. points[5].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2211. points[6].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2212. points[7].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2213. this.makeEmpty();
  2214. this.setFromPoints( points );
  2215. return this;
  2216. };
  2217. }(),
  2218. translate: function ( offset ) {
  2219. this.min.add( offset );
  2220. this.max.add( offset );
  2221. return this;
  2222. },
  2223. equals: function ( box ) {
  2224. return box.min.equals( this.min ) && box.max.equals( this.max );
  2225. },
  2226. clone: function () {
  2227. return new THREE.Box3().copy( this );
  2228. }
  2229. };
  2230. /**
  2231. * @author alteredq / http://alteredqualia.com/
  2232. * @author WestLangley / http://github.com/WestLangley
  2233. * @author bhouston / http://exocortex.com
  2234. */
  2235. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2236. this.elements = new Float32Array(9);
  2237. this.set(
  2238. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0,
  2239. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0,
  2240. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1
  2241. );
  2242. };
  2243. THREE.Matrix3.prototype = {
  2244. constructor: THREE.Matrix3,
  2245. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2246. var te = this.elements;
  2247. te[0] = n11; te[3] = n12; te[6] = n13;
  2248. te[1] = n21; te[4] = n22; te[7] = n23;
  2249. te[2] = n31; te[5] = n32; te[8] = n33;
  2250. return this;
  2251. },
  2252. identity: function () {
  2253. this.set(
  2254. 1, 0, 0,
  2255. 0, 1, 0,
  2256. 0, 0, 1
  2257. );
  2258. return this;
  2259. },
  2260. copy: function ( m ) {
  2261. var me = m.elements;
  2262. this.set(
  2263. me[0], me[3], me[6],
  2264. me[1], me[4], me[7],
  2265. me[2], me[5], me[8]
  2266. );
  2267. return this;
  2268. },
  2269. multiplyVector3: function ( vector ) {
  2270. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2271. return vector.applyMatrix3( this );
  2272. },
  2273. multiplyVector3Array: function() {
  2274. var v1 = new THREE.Vector3();
  2275. return function ( a ) {
  2276. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2277. v1.x = a[ i ];
  2278. v1.y = a[ i + 1 ];
  2279. v1.z = a[ i + 2 ];
  2280. v1.applyMatrix3(this);
  2281. a[ i ] = v1.x;
  2282. a[ i + 1 ] = v1.y;
  2283. a[ i + 2 ] = v1.z;
  2284. }
  2285. return a;
  2286. };
  2287. }(),
  2288. multiplyScalar: function ( s ) {
  2289. var te = this.elements;
  2290. te[0] *= s; te[3] *= s; te[6] *= s;
  2291. te[1] *= s; te[4] *= s; te[7] *= s;
  2292. te[2] *= s; te[5] *= s; te[8] *= s;
  2293. return this;
  2294. },
  2295. determinant: function () {
  2296. var te = this.elements;
  2297. var a = te[0], b = te[1], c = te[2],
  2298. d = te[3], e = te[4], f = te[5],
  2299. g = te[6], h = te[7], i = te[8];
  2300. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  2301. },
  2302. getInverse: function ( matrix, throwOnInvertible ) {
  2303. // input: THREE.Matrix4
  2304. // ( based on http://code.google.com/p/webgl-mjs/ )
  2305. var me = matrix.elements;
  2306. var te = this.elements;
  2307. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  2308. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  2309. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  2310. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  2311. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  2312. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  2313. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  2314. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  2315. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  2316. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2317. // no inverse
  2318. if ( det === 0 ) {
  2319. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2320. if ( throwOnInvertible || false ) {
  2321. throw new Error( msg );
  2322. } else {
  2323. console.warn( msg );
  2324. }
  2325. this.identity();
  2326. return this;
  2327. }
  2328. this.multiplyScalar( 1.0 / det );
  2329. return this;
  2330. },
  2331. transpose: function () {
  2332. var tmp, m = this.elements;
  2333. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  2334. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  2335. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  2336. return this;
  2337. },
  2338. getNormalMatrix: function ( m ) {
  2339. // input: THREE.Matrix4
  2340. this.getInverse( m ).transpose();
  2341. return this;
  2342. },
  2343. transposeIntoArray: function ( r ) {
  2344. var m = this.elements;
  2345. r[ 0 ] = m[ 0 ];
  2346. r[ 1 ] = m[ 3 ];
  2347. r[ 2 ] = m[ 6 ];
  2348. r[ 3 ] = m[ 1 ];
  2349. r[ 4 ] = m[ 4 ];
  2350. r[ 5 ] = m[ 7 ];
  2351. r[ 6 ] = m[ 2 ];
  2352. r[ 7 ] = m[ 5 ];
  2353. r[ 8 ] = m[ 8 ];
  2354. return this;
  2355. },
  2356. fromArray: function ( array ) {
  2357. this.elements.set( array );
  2358. return this;
  2359. },
  2360. toArray: function () {
  2361. var te = this.elements;
  2362. return [
  2363. te[ 0 ], te[ 1 ], te[ 2 ],
  2364. te[ 3 ], te[ 4 ], te[ 5 ],
  2365. te[ 6 ], te[ 7 ], te[ 8 ]
  2366. ];
  2367. },
  2368. clone: function () {
  2369. var te = this.elements;
  2370. return new THREE.Matrix3(
  2371. te[0], te[3], te[6],
  2372. te[1], te[4], te[7],
  2373. te[2], te[5], te[8]
  2374. );
  2375. }
  2376. };
  2377. /**
  2378. * @author mrdoob / http://mrdoob.com/
  2379. * @author supereggbert / http://www.paulbrunt.co.uk/
  2380. * @author philogb / http://blog.thejit.org/
  2381. * @author jordi_ros / http://plattsoft.com
  2382. * @author D1plo1d / http://github.com/D1plo1d
  2383. * @author alteredq / http://alteredqualia.com/
  2384. * @author mikael emtinger / http://gomo.se/
  2385. * @author timknip / http://www.floorplanner.com/
  2386. * @author bhouston / http://exocortex.com
  2387. * @author WestLangley / http://github.com/WestLangley
  2388. */
  2389. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2390. this.elements = new Float32Array( 16 );
  2391. // TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix
  2392. // we should not support semi specification of Matrix4, it is just weird.
  2393. var te = this.elements;
  2394. te[0] = ( n11 !== undefined ) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  2395. te[1] = n21 || 0; te[5] = ( n22 !== undefined ) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  2396. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = ( n33 !== undefined ) ? n33 : 1; te[14] = n34 || 0;
  2397. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = ( n44 !== undefined ) ? n44 : 1;
  2398. };
  2399. THREE.Matrix4.prototype = {
  2400. constructor: THREE.Matrix4,
  2401. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2402. var te = this.elements;
  2403. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  2404. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  2405. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  2406. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  2407. return this;
  2408. },
  2409. identity: function () {
  2410. this.set(
  2411. 1, 0, 0, 0,
  2412. 0, 1, 0, 0,
  2413. 0, 0, 1, 0,
  2414. 0, 0, 0, 1
  2415. );
  2416. return this;
  2417. },
  2418. copy: function ( m ) {
  2419. this.elements.set( m.elements );
  2420. return this;
  2421. },
  2422. extractPosition: function ( m ) {
  2423. console.warn( 'DEPRECATED: Matrix4\'s .extractPosition() has been renamed to .copyPosition().' );
  2424. return this.copyPosition( m );
  2425. },
  2426. copyPosition: function ( m ) {
  2427. var te = this.elements;
  2428. var me = m.elements;
  2429. te[12] = me[12];
  2430. te[13] = me[13];
  2431. te[14] = me[14];
  2432. return this;
  2433. },
  2434. extractRotation: function () {
  2435. var v1 = new THREE.Vector3();
  2436. return function ( m ) {
  2437. var te = this.elements;
  2438. var me = m.elements;
  2439. var scaleX = 1 / v1.set( me[0], me[1], me[2] ).length();
  2440. var scaleY = 1 / v1.set( me[4], me[5], me[6] ).length();
  2441. var scaleZ = 1 / v1.set( me[8], me[9], me[10] ).length();
  2442. te[0] = me[0] * scaleX;
  2443. te[1] = me[1] * scaleX;
  2444. te[2] = me[2] * scaleX;
  2445. te[4] = me[4] * scaleY;
  2446. te[5] = me[5] * scaleY;
  2447. te[6] = me[6] * scaleY;
  2448. te[8] = me[8] * scaleZ;
  2449. te[9] = me[9] * scaleZ;
  2450. te[10] = me[10] * scaleZ;
  2451. return this;
  2452. };
  2453. }(),
  2454. makeRotationFromEuler: function ( euler ) {
  2455. if ( euler instanceof THREE.Euler === false ) {
  2456. console.error( 'ERROR: Matrix\'s .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  2457. }
  2458. var te = this.elements;
  2459. var x = euler.x, y = euler.y, z = euler.z;
  2460. var a = Math.cos( x ), b = Math.sin( x );
  2461. var c = Math.cos( y ), d = Math.sin( y );
  2462. var e = Math.cos( z ), f = Math.sin( z );
  2463. if ( euler.order === 'XYZ' ) {
  2464. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2465. te[0] = c * e;
  2466. te[4] = - c * f;
  2467. te[8] = d;
  2468. te[1] = af + be * d;
  2469. te[5] = ae - bf * d;
  2470. te[9] = - b * c;
  2471. te[2] = bf - ae * d;
  2472. te[6] = be + af * d;
  2473. te[10] = a * c;
  2474. } else if ( euler.order === 'YXZ' ) {
  2475. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2476. te[0] = ce + df * b;
  2477. te[4] = de * b - cf;
  2478. te[8] = a * d;
  2479. te[1] = a * f;
  2480. te[5] = a * e;
  2481. te[9] = - b;
  2482. te[2] = cf * b - de;
  2483. te[6] = df + ce * b;
  2484. te[10] = a * c;
  2485. } else if ( euler.order === 'ZXY' ) {
  2486. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2487. te[0] = ce - df * b;
  2488. te[4] = - a * f;
  2489. te[8] = de + cf * b;
  2490. te[1] = cf + de * b;
  2491. te[5] = a * e;
  2492. te[9] = df - ce * b;
  2493. te[2] = - a * d;
  2494. te[6] = b;
  2495. te[10] = a * c;
  2496. } else if ( euler.order === 'ZYX' ) {
  2497. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2498. te[0] = c * e;
  2499. te[4] = be * d - af;
  2500. te[8] = ae * d + bf;
  2501. te[1] = c * f;
  2502. te[5] = bf * d + ae;
  2503. te[9] = af * d - be;
  2504. te[2] = - d;
  2505. te[6] = b * c;
  2506. te[10] = a * c;
  2507. } else if ( euler.order === 'YZX' ) {
  2508. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2509. te[0] = c * e;
  2510. te[4] = bd - ac * f;
  2511. te[8] = bc * f + ad;
  2512. te[1] = f;
  2513. te[5] = a * e;
  2514. te[9] = - b * e;
  2515. te[2] = - d * e;
  2516. te[6] = ad * f + bc;
  2517. te[10] = ac - bd * f;
  2518. } else if ( euler.order === 'XZY' ) {
  2519. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2520. te[0] = c * e;
  2521. te[4] = - f;
  2522. te[8] = d * e;
  2523. te[1] = ac * f + bd;
  2524. te[5] = a * e;
  2525. te[9] = ad * f - bc;
  2526. te[2] = bc * f - ad;
  2527. te[6] = b * e;
  2528. te[10] = bd * f + ac;
  2529. }
  2530. // last column
  2531. te[3] = 0;
  2532. te[7] = 0;
  2533. te[11] = 0;
  2534. // bottom row
  2535. te[12] = 0;
  2536. te[13] = 0;
  2537. te[14] = 0;
  2538. te[15] = 1;
  2539. return this;
  2540. },
  2541. setRotationFromQuaternion: function ( q ) {
  2542. console.warn( 'DEPRECATED: Matrix4\'s .setRotationFromQuaternion() has been deprecated in favor of makeRotationFromQuaternion. Please update your code.' );
  2543. return this.makeRotationFromQuaternion( q );
  2544. },
  2545. makeRotationFromQuaternion: function ( q ) {
  2546. var te = this.elements;
  2547. var x = q.x, y = q.y, z = q.z, w = q.w;
  2548. var x2 = x + x, y2 = y + y, z2 = z + z;
  2549. var xx = x * x2, xy = x * y2, xz = x * z2;
  2550. var yy = y * y2, yz = y * z2, zz = z * z2;
  2551. var wx = w * x2, wy = w * y2, wz = w * z2;
  2552. te[0] = 1 - ( yy + zz );
  2553. te[4] = xy - wz;
  2554. te[8] = xz + wy;
  2555. te[1] = xy + wz;
  2556. te[5] = 1 - ( xx + zz );
  2557. te[9] = yz - wx;
  2558. te[2] = xz - wy;
  2559. te[6] = yz + wx;
  2560. te[10] = 1 - ( xx + yy );
  2561. // last column
  2562. te[3] = 0;
  2563. te[7] = 0;
  2564. te[11] = 0;
  2565. // bottom row
  2566. te[12] = 0;
  2567. te[13] = 0;
  2568. te[14] = 0;
  2569. te[15] = 1;
  2570. return this;
  2571. },
  2572. lookAt: function() {
  2573. var x = new THREE.Vector3();
  2574. var y = new THREE.Vector3();
  2575. var z = new THREE.Vector3();
  2576. return function ( eye, target, up ) {
  2577. var te = this.elements;
  2578. z.subVectors( eye, target ).normalize();
  2579. if ( z.length() === 0 ) {
  2580. z.z = 1;
  2581. }
  2582. x.crossVectors( up, z ).normalize();
  2583. if ( x.length() === 0 ) {
  2584. z.x += 0.0001;
  2585. x.crossVectors( up, z ).normalize();
  2586. }
  2587. y.crossVectors( z, x );
  2588. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  2589. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  2590. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  2591. return this;
  2592. };
  2593. }(),
  2594. multiply: function ( m, n ) {
  2595. if ( n !== undefined ) {
  2596. console.warn( 'DEPRECATED: Matrix4\'s .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2597. return this.multiplyMatrices( m, n );
  2598. }
  2599. return this.multiplyMatrices( this, m );
  2600. },
  2601. multiplyMatrices: function ( a, b ) {
  2602. var ae = a.elements;
  2603. var be = b.elements;
  2604. var te = this.elements;
  2605. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  2606. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  2607. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  2608. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  2609. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  2610. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  2611. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  2612. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  2613. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2614. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2615. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2616. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2617. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2618. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2619. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2620. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2621. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2622. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2623. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2624. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2625. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2626. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2627. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2628. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2629. return this;
  2630. },
  2631. multiplyToArray: function ( a, b, r ) {
  2632. var te = this.elements;
  2633. this.multiplyMatrices( a, b );
  2634. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  2635. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  2636. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  2637. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  2638. return this;
  2639. },
  2640. multiplyScalar: function ( s ) {
  2641. var te = this.elements;
  2642. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  2643. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  2644. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  2645. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  2646. return this;
  2647. },
  2648. multiplyVector3: function ( vector ) {
  2649. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2650. return vector.applyProjection( this );
  2651. },
  2652. multiplyVector4: function ( vector ) {
  2653. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2654. return vector.applyMatrix4( this );
  2655. },
  2656. multiplyVector3Array: function() {
  2657. var v1 = new THREE.Vector3();
  2658. return function ( a ) {
  2659. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2660. v1.x = a[ i ];
  2661. v1.y = a[ i + 1 ];
  2662. v1.z = a[ i + 2 ];
  2663. v1.applyProjection( this );
  2664. a[ i ] = v1.x;
  2665. a[ i + 1 ] = v1.y;
  2666. a[ i + 2 ] = v1.z;
  2667. }
  2668. return a;
  2669. };
  2670. }(),
  2671. rotateAxis: function ( v ) {
  2672. console.warn( 'DEPRECATED: Matrix4\'s .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2673. v.transformDirection( this );
  2674. },
  2675. crossVector: function ( vector ) {
  2676. console.warn( 'DEPRECATED: Matrix4\'s .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2677. return vector.applyMatrix4( this );
  2678. },
  2679. determinant: function () {
  2680. var te = this.elements;
  2681. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  2682. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  2683. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  2684. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  2685. //TODO: make this more efficient
  2686. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2687. return (
  2688. n41 * (
  2689. +n14 * n23 * n32
  2690. -n13 * n24 * n32
  2691. -n14 * n22 * n33
  2692. +n12 * n24 * n33
  2693. +n13 * n22 * n34
  2694. -n12 * n23 * n34
  2695. ) +
  2696. n42 * (
  2697. +n11 * n23 * n34
  2698. -n11 * n24 * n33
  2699. +n14 * n21 * n33
  2700. -n13 * n21 * n34
  2701. +n13 * n24 * n31
  2702. -n14 * n23 * n31
  2703. ) +
  2704. n43 * (
  2705. +n11 * n24 * n32
  2706. -n11 * n22 * n34
  2707. -n14 * n21 * n32
  2708. +n12 * n21 * n34
  2709. +n14 * n22 * n31
  2710. -n12 * n24 * n31
  2711. ) +
  2712. n44 * (
  2713. -n13 * n22 * n31
  2714. -n11 * n23 * n32
  2715. +n11 * n22 * n33
  2716. +n13 * n21 * n32
  2717. -n12 * n21 * n33
  2718. +n12 * n23 * n31
  2719. )
  2720. );
  2721. },
  2722. transpose: function () {
  2723. var te = this.elements;
  2724. var tmp;
  2725. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  2726. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  2727. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  2728. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  2729. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  2730. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  2731. return this;
  2732. },
  2733. flattenToArray: function ( flat ) {
  2734. var te = this.elements;
  2735. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  2736. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  2737. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  2738. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  2739. return flat;
  2740. },
  2741. flattenToArrayOffset: function( flat, offset ) {
  2742. var te = this.elements;
  2743. flat[ offset ] = te[0];
  2744. flat[ offset + 1 ] = te[1];
  2745. flat[ offset + 2 ] = te[2];
  2746. flat[ offset + 3 ] = te[3];
  2747. flat[ offset + 4 ] = te[4];
  2748. flat[ offset + 5 ] = te[5];
  2749. flat[ offset + 6 ] = te[6];
  2750. flat[ offset + 7 ] = te[7];
  2751. flat[ offset + 8 ] = te[8];
  2752. flat[ offset + 9 ] = te[9];
  2753. flat[ offset + 10 ] = te[10];
  2754. flat[ offset + 11 ] = te[11];
  2755. flat[ offset + 12 ] = te[12];
  2756. flat[ offset + 13 ] = te[13];
  2757. flat[ offset + 14 ] = te[14];
  2758. flat[ offset + 15 ] = te[15];
  2759. return flat;
  2760. },
  2761. getPosition: function() {
  2762. var v1 = new THREE.Vector3();
  2763. return function () {
  2764. console.warn( 'DEPRECATED: Matrix4\'s .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  2765. var te = this.elements;
  2766. return v1.set( te[12], te[13], te[14] );
  2767. };
  2768. }(),
  2769. setPosition: function ( v ) {
  2770. var te = this.elements;
  2771. te[12] = v.x;
  2772. te[13] = v.y;
  2773. te[14] = v.z;
  2774. return this;
  2775. },
  2776. getInverse: function ( m, throwOnInvertible ) {
  2777. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2778. var te = this.elements;
  2779. var me = m.elements;
  2780. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2781. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2782. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2783. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2784. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2785. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2786. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2787. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2788. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2789. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2790. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2791. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2792. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2793. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2794. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2795. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2796. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2797. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2798. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2799. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2800. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  2801. if ( det == 0 ) {
  2802. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2803. if ( throwOnInvertible || false ) {
  2804. throw new Error( msg );
  2805. } else {
  2806. console.warn( msg );
  2807. }
  2808. this.identity();
  2809. return this;
  2810. }
  2811. this.multiplyScalar( 1 / det );
  2812. return this;
  2813. },
  2814. translate: function ( v ) {
  2815. console.warn( 'DEPRECATED: Matrix4\'s .translate() has been removed.');
  2816. },
  2817. rotateX: function ( angle ) {
  2818. console.warn( 'DEPRECATED: Matrix4\'s .rotateX() has been removed.');
  2819. },
  2820. rotateY: function ( angle ) {
  2821. console.warn( 'DEPRECATED: Matrix4\'s .rotateY() has been removed.');
  2822. },
  2823. rotateZ: function ( angle ) {
  2824. console.warn( 'DEPRECATED: Matrix4\'s .rotateZ() has been removed.');
  2825. },
  2826. rotateByAxis: function ( axis, angle ) {
  2827. console.warn( 'DEPRECATED: Matrix4\'s .rotateByAxis() has been removed.');
  2828. },
  2829. scale: function ( v ) {
  2830. var te = this.elements;
  2831. var x = v.x, y = v.y, z = v.z;
  2832. te[0] *= x; te[4] *= y; te[8] *= z;
  2833. te[1] *= x; te[5] *= y; te[9] *= z;
  2834. te[2] *= x; te[6] *= y; te[10] *= z;
  2835. te[3] *= x; te[7] *= y; te[11] *= z;
  2836. return this;
  2837. },
  2838. getMaxScaleOnAxis: function () {
  2839. var te = this.elements;
  2840. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2841. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2842. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2843. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2844. },
  2845. makeTranslation: function ( x, y, z ) {
  2846. this.set(
  2847. 1, 0, 0, x,
  2848. 0, 1, 0, y,
  2849. 0, 0, 1, z,
  2850. 0, 0, 0, 1
  2851. );
  2852. return this;
  2853. },
  2854. makeRotationX: function ( theta ) {
  2855. var c = Math.cos( theta ), s = Math.sin( theta );
  2856. this.set(
  2857. 1, 0, 0, 0,
  2858. 0, c, -s, 0,
  2859. 0, s, c, 0,
  2860. 0, 0, 0, 1
  2861. );
  2862. return this;
  2863. },
  2864. makeRotationY: function ( theta ) {
  2865. var c = Math.cos( theta ), s = Math.sin( theta );
  2866. this.set(
  2867. c, 0, s, 0,
  2868. 0, 1, 0, 0,
  2869. -s, 0, c, 0,
  2870. 0, 0, 0, 1
  2871. );
  2872. return this;
  2873. },
  2874. makeRotationZ: function ( theta ) {
  2875. var c = Math.cos( theta ), s = Math.sin( theta );
  2876. this.set(
  2877. c, -s, 0, 0,
  2878. s, c, 0, 0,
  2879. 0, 0, 1, 0,
  2880. 0, 0, 0, 1
  2881. );
  2882. return this;
  2883. },
  2884. makeRotationAxis: function ( axis, angle ) {
  2885. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2886. var c = Math.cos( angle );
  2887. var s = Math.sin( angle );
  2888. var t = 1 - c;
  2889. var x = axis.x, y = axis.y, z = axis.z;
  2890. var tx = t * x, ty = t * y;
  2891. this.set(
  2892. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2893. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2894. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2895. 0, 0, 0, 1
  2896. );
  2897. return this;
  2898. },
  2899. makeScale: function ( x, y, z ) {
  2900. this.set(
  2901. x, 0, 0, 0,
  2902. 0, y, 0, 0,
  2903. 0, 0, z, 0,
  2904. 0, 0, 0, 1
  2905. );
  2906. return this;
  2907. },
  2908. compose: function ( position, quaternion, scale ) {
  2909. this.makeRotationFromQuaternion( quaternion );
  2910. this.scale( scale );
  2911. this.setPosition( position );
  2912. return this;
  2913. },
  2914. decompose: function () {
  2915. var vector = new THREE.Vector3();
  2916. var matrix = new THREE.Matrix4();
  2917. return function ( position, quaternion, scale ) {
  2918. var te = this.elements;
  2919. var sx = vector.set( te[0], te[1], te[2] ).length();
  2920. var sy = vector.set( te[4], te[5], te[6] ).length();
  2921. var sz = vector.set( te[8], te[9], te[10] ).length();
  2922. // if determine is negative, we need to invert one scale
  2923. var det = this.determinant();
  2924. if( det < 0 ) {
  2925. sx = -sx;
  2926. }
  2927. position.x = te[12];
  2928. position.y = te[13];
  2929. position.z = te[14];
  2930. // scale the rotation part
  2931. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  2932. var invSX = 1 / sx;
  2933. var invSY = 1 / sy;
  2934. var invSZ = 1 / sz;
  2935. matrix.elements[0] *= invSX;
  2936. matrix.elements[1] *= invSX;
  2937. matrix.elements[2] *= invSX;
  2938. matrix.elements[4] *= invSY;
  2939. matrix.elements[5] *= invSY;
  2940. matrix.elements[6] *= invSY;
  2941. matrix.elements[8] *= invSZ;
  2942. matrix.elements[9] *= invSZ;
  2943. matrix.elements[10] *= invSZ;
  2944. quaternion.setFromRotationMatrix( matrix );
  2945. scale.x = sx;
  2946. scale.y = sy;
  2947. scale.z = sz;
  2948. return this;
  2949. };
  2950. }(),
  2951. makeFrustum: function ( left, right, bottom, top, near, far ) {
  2952. var te = this.elements;
  2953. var x = 2 * near / ( right - left );
  2954. var y = 2 * near / ( top - bottom );
  2955. var a = ( right + left ) / ( right - left );
  2956. var b = ( top + bottom ) / ( top - bottom );
  2957. var c = - ( far + near ) / ( far - near );
  2958. var d = - 2 * far * near / ( far - near );
  2959. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  2960. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  2961. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  2962. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  2963. return this;
  2964. },
  2965. makePerspective: function ( fov, aspect, near, far ) {
  2966. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  2967. var ymin = - ymax;
  2968. var xmin = ymin * aspect;
  2969. var xmax = ymax * aspect;
  2970. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  2971. },
  2972. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2973. var te = this.elements;
  2974. var w = right - left;
  2975. var h = top - bottom;
  2976. var p = far - near;
  2977. var x = ( right + left ) / w;
  2978. var y = ( top + bottom ) / h;
  2979. var z = ( far + near ) / p;
  2980. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  2981. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  2982. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  2983. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  2984. return this;
  2985. },
  2986. fromArray: function ( array ) {
  2987. this.elements.set( array );
  2988. return this;
  2989. },
  2990. toArray: function () {
  2991. var te = this.elements;
  2992. return [
  2993. te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ],
  2994. te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ],
  2995. te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ],
  2996. te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ]
  2997. ];
  2998. },
  2999. clone: function () {
  3000. var te = this.elements;
  3001. return new THREE.Matrix4(
  3002. te[0], te[4], te[8], te[12],
  3003. te[1], te[5], te[9], te[13],
  3004. te[2], te[6], te[10], te[14],
  3005. te[3], te[7], te[11], te[15]
  3006. );
  3007. }
  3008. };
  3009. /**
  3010. * @author bhouston / http://exocortex.com
  3011. */
  3012. THREE.Ray = function ( origin, direction ) {
  3013. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  3014. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  3015. };
  3016. THREE.Ray.prototype = {
  3017. constructor: THREE.Ray,
  3018. set: function ( origin, direction ) {
  3019. this.origin.copy( origin );
  3020. this.direction.copy( direction );
  3021. return this;
  3022. },
  3023. copy: function ( ray ) {
  3024. this.origin.copy( ray.origin );
  3025. this.direction.copy( ray.direction );
  3026. return this;
  3027. },
  3028. at: function ( t, optionalTarget ) {
  3029. var result = optionalTarget || new THREE.Vector3();
  3030. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3031. },
  3032. recast: function () {
  3033. var v1 = new THREE.Vector3();
  3034. return function ( t ) {
  3035. this.origin.copy( this.at( t, v1 ) );
  3036. return this;
  3037. };
  3038. }(),
  3039. closestPointToPoint: function ( point, optionalTarget ) {
  3040. var result = optionalTarget || new THREE.Vector3();
  3041. result.subVectors( point, this.origin );
  3042. var directionDistance = result.dot( this.direction );
  3043. if ( directionDistance < 0 ) {
  3044. return result.copy( this.origin );
  3045. }
  3046. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3047. },
  3048. distanceToPoint: function () {
  3049. var v1 = new THREE.Vector3();
  3050. return function ( point ) {
  3051. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  3052. // point behind the ray
  3053. if ( directionDistance < 0 ) {
  3054. return this.origin.distanceTo( point );
  3055. }
  3056. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3057. return v1.distanceTo( point );
  3058. };
  3059. }(),
  3060. distanceSqToSegment: function( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3061. // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp
  3062. // It returns the min distance between the ray and the segment
  3063. // defined by v0 and v1
  3064. // It can also set two optional targets :
  3065. // - The closest point on the ray
  3066. // - The closest point on the segment
  3067. var segCenter = v0.clone().add( v1 ).multiplyScalar( 0.5 );
  3068. var segDir = v1.clone().sub( v0 ).normalize();
  3069. var segExtent = v0.distanceTo( v1 ) * 0.5;
  3070. var diff = this.origin.clone().sub( segCenter );
  3071. var a01 = - this.direction.dot( segDir );
  3072. var b0 = diff.dot( this.direction );
  3073. var b1 = - diff.dot( segDir );
  3074. var c = diff.lengthSq();
  3075. var det = Math.abs( 1 - a01 * a01 );
  3076. var s0, s1, sqrDist, extDet;
  3077. if ( det >= 0 ) {
  3078. // The ray and segment are not parallel.
  3079. s0 = a01 * b1 - b0;
  3080. s1 = a01 * b0 - b1;
  3081. extDet = segExtent * det;
  3082. if ( s0 >= 0 ) {
  3083. if ( s1 >= - extDet ) {
  3084. if ( s1 <= extDet ) {
  3085. // region 0
  3086. // Minimum at interior points of ray and segment.
  3087. var invDet = 1 / det;
  3088. s0 *= invDet;
  3089. s1 *= invDet;
  3090. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3091. } else {
  3092. // region 1
  3093. s1 = segExtent;
  3094. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3095. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3096. }
  3097. } else {
  3098. // region 5
  3099. s1 = - segExtent;
  3100. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3101. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3102. }
  3103. } else {
  3104. if ( s1 <= - extDet) {
  3105. // region 4
  3106. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3107. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3108. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3109. } else if ( s1 <= extDet ) {
  3110. // region 3
  3111. s0 = 0;
  3112. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3113. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3114. } else {
  3115. // region 2
  3116. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3117. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3118. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3119. }
  3120. }
  3121. } else {
  3122. // Ray and segment are parallel.
  3123. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3124. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3125. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3126. }
  3127. if ( optionalPointOnRay ) {
  3128. optionalPointOnRay.copy( this.direction.clone().multiplyScalar( s0 ).add( this.origin ) );
  3129. }
  3130. if ( optionalPointOnSegment ) {
  3131. optionalPointOnSegment.copy( segDir.clone().multiplyScalar( s1 ).add( segCenter ) );
  3132. }
  3133. return sqrDist;
  3134. },
  3135. isIntersectionSphere: function ( sphere ) {
  3136. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  3137. },
  3138. isIntersectionPlane: function ( plane ) {
  3139. // check if the ray lies on the plane first
  3140. var distToPoint = plane.distanceToPoint( this.origin );
  3141. if ( distToPoint === 0 ) {
  3142. return true;
  3143. }
  3144. var denominator = plane.normal.dot( this.direction );
  3145. if ( denominator * distToPoint < 0 ) {
  3146. return true
  3147. }
  3148. // ray origin is behind the plane (and is pointing behind it)
  3149. return false;
  3150. },
  3151. distanceToPlane: function ( plane ) {
  3152. var denominator = plane.normal.dot( this.direction );
  3153. if ( denominator == 0 ) {
  3154. // line is coplanar, return origin
  3155. if( plane.distanceToPoint( this.origin ) == 0 ) {
  3156. return 0;
  3157. }
  3158. // Null is preferable to undefined since undefined means.... it is undefined
  3159. return null;
  3160. }
  3161. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3162. // Return if the ray never intersects the plane
  3163. return t >= 0 ? t : null;
  3164. },
  3165. intersectPlane: function ( plane, optionalTarget ) {
  3166. var t = this.distanceToPlane( plane );
  3167. if ( t === null ) {
  3168. return null;
  3169. }
  3170. return this.at( t, optionalTarget );
  3171. },
  3172. isIntersectionBox: function () {
  3173. var v = new THREE.Vector3();
  3174. return function ( box ) {
  3175. return this.intersectBox( box, v ) !== null;
  3176. }
  3177. }(),
  3178. intersectBox: function ( box , optionalTarget ) {
  3179. // http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/
  3180. var tmin,tmax,tymin,tymax,tzmin,tzmax;
  3181. var invdirx = 1/this.direction.x,
  3182. invdiry = 1/this.direction.y,
  3183. invdirz = 1/this.direction.z;
  3184. var origin = this.origin;
  3185. if (invdirx >= 0) {
  3186. tmin = (box.min.x - origin.x) * invdirx;
  3187. tmax = (box.max.x - origin.x) * invdirx;
  3188. } else {
  3189. tmin = (box.max.x - origin.x) * invdirx;
  3190. tmax = (box.min.x - origin.x) * invdirx;
  3191. }
  3192. if (invdiry >= 0) {
  3193. tymin = (box.min.y - origin.y) * invdiry;
  3194. tymax = (box.max.y - origin.y) * invdiry;
  3195. } else {
  3196. tymin = (box.max.y - origin.y) * invdiry;
  3197. tymax = (box.min.y - origin.y) * invdiry;
  3198. }
  3199. if ((tmin > tymax) || (tymin > tmax)) return null;
  3200. // These lines also handle the case where tmin or tmax is NaN
  3201. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3202. if (tymin > tmin || tmin !== tmin ) tmin = tymin;
  3203. if (tymax < tmax || tmax !== tmax ) tmax = tymax;
  3204. if (invdirz >= 0) {
  3205. tzmin = (box.min.z - origin.z) * invdirz;
  3206. tzmax = (box.max.z - origin.z) * invdirz;
  3207. } else {
  3208. tzmin = (box.max.z - origin.z) * invdirz;
  3209. tzmax = (box.min.z - origin.z) * invdirz;
  3210. }
  3211. if ((tmin > tzmax) || (tzmin > tmax)) return null;
  3212. if (tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3213. if (tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3214. //return point closest to the ray (positive side)
  3215. if ( tmax < 0 ) return null;
  3216. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  3217. },
  3218. intersectTriangle: function() {
  3219. // Compute the offset origin, edges, and normal.
  3220. var diff = new THREE.Vector3();
  3221. var edge1 = new THREE.Vector3();
  3222. var edge2 = new THREE.Vector3();
  3223. var normal = new THREE.Vector3();
  3224. return function ( a, b, c, backfaceCulling, optionalTarget ) {
  3225. // from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp
  3226. edge1.subVectors( b, a );
  3227. edge2.subVectors( c, a );
  3228. normal.crossVectors( edge1, edge2 );
  3229. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3230. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3231. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3232. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3233. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3234. var DdN = this.direction.dot( normal );
  3235. var sign;
  3236. if ( DdN > 0 ) {
  3237. if ( backfaceCulling ) return null;
  3238. sign = 1;
  3239. } else if ( DdN < 0 ) {
  3240. sign = - 1;
  3241. DdN = - DdN;
  3242. } else {
  3243. return null;
  3244. }
  3245. diff.subVectors( this.origin, a );
  3246. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  3247. // b1 < 0, no intersection
  3248. if ( DdQxE2 < 0 ) {
  3249. return null;
  3250. }
  3251. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  3252. // b2 < 0, no intersection
  3253. if ( DdE1xQ < 0 ) {
  3254. return null;
  3255. }
  3256. // b1+b2 > 1, no intersection
  3257. if ( DdQxE2 + DdE1xQ > DdN ) {
  3258. return null;
  3259. }
  3260. // Line intersects triangle, check if ray does.
  3261. var QdN = - sign * diff.dot( normal );
  3262. // t < 0, no intersection
  3263. if ( QdN < 0 ) {
  3264. return null;
  3265. }
  3266. // Ray intersects triangle.
  3267. return this.at( QdN / DdN, optionalTarget );
  3268. }
  3269. }(),
  3270. applyMatrix4: function ( matrix4 ) {
  3271. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3272. this.origin.applyMatrix4( matrix4 );
  3273. this.direction.sub( this.origin );
  3274. this.direction.normalize();
  3275. return this;
  3276. },
  3277. equals: function ( ray ) {
  3278. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3279. },
  3280. clone: function () {
  3281. return new THREE.Ray().copy( this );
  3282. }
  3283. };
  3284. /**
  3285. * @author bhouston / http://exocortex.com
  3286. * @author mrdoob / http://mrdoob.com/
  3287. */
  3288. THREE.Sphere = function ( center, radius ) {
  3289. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3290. this.radius = ( radius !== undefined ) ? radius : 0;
  3291. };
  3292. THREE.Sphere.prototype = {
  3293. constructor: THREE.Sphere,
  3294. set: function ( center, radius ) {
  3295. this.center.copy( center );
  3296. this.radius = radius;
  3297. return this;
  3298. },
  3299. setFromPoints: function () {
  3300. var box = new THREE.Box3();
  3301. return function ( points, optionalCenter ) {
  3302. var center = this.center;
  3303. if ( optionalCenter !== undefined ) {
  3304. center.copy( optionalCenter );
  3305. } else {
  3306. box.setFromPoints( points ).center( center );
  3307. }
  3308. var maxRadiusSq = 0;
  3309. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3310. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3311. }
  3312. this.radius = Math.sqrt( maxRadiusSq );
  3313. return this;
  3314. };
  3315. }(),
  3316. copy: function ( sphere ) {
  3317. this.center.copy( sphere.center );
  3318. this.radius = sphere.radius;
  3319. return this;
  3320. },
  3321. empty: function () {
  3322. return ( this.radius <= 0 );
  3323. },
  3324. containsPoint: function ( point ) {
  3325. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3326. },
  3327. distanceToPoint: function ( point ) {
  3328. return ( point.distanceTo( this.center ) - this.radius );
  3329. },
  3330. intersectsSphere: function ( sphere ) {
  3331. var radiusSum = this.radius + sphere.radius;
  3332. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3333. },
  3334. clampPoint: function ( point, optionalTarget ) {
  3335. var deltaLengthSq = this.center.distanceToSquared( point );
  3336. var result = optionalTarget || new THREE.Vector3();
  3337. result.copy( point );
  3338. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3339. result.sub( this.center ).normalize();
  3340. result.multiplyScalar( this.radius ).add( this.center );
  3341. }
  3342. return result;
  3343. },
  3344. getBoundingBox: function ( optionalTarget ) {
  3345. var box = optionalTarget || new THREE.Box3();
  3346. box.set( this.center, this.center );
  3347. box.expandByScalar( this.radius );
  3348. return box;
  3349. },
  3350. applyMatrix4: function ( matrix ) {
  3351. this.center.applyMatrix4( matrix );
  3352. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3353. return this;
  3354. },
  3355. translate: function ( offset ) {
  3356. this.center.add( offset );
  3357. return this;
  3358. },
  3359. equals: function ( sphere ) {
  3360. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3361. },
  3362. clone: function () {
  3363. return new THREE.Sphere().copy( this );
  3364. }
  3365. };
  3366. /**
  3367. * @author mrdoob / http://mrdoob.com/
  3368. * @author alteredq / http://alteredqualia.com/
  3369. * @author bhouston / http://exocortex.com
  3370. */
  3371. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3372. this.planes = [
  3373. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3374. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3375. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3376. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3377. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3378. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3379. ];
  3380. };
  3381. THREE.Frustum.prototype = {
  3382. constructor: THREE.Frustum,
  3383. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3384. var planes = this.planes;
  3385. planes[0].copy( p0 );
  3386. planes[1].copy( p1 );
  3387. planes[2].copy( p2 );
  3388. planes[3].copy( p3 );
  3389. planes[4].copy( p4 );
  3390. planes[5].copy( p5 );
  3391. return this;
  3392. },
  3393. copy: function ( frustum ) {
  3394. var planes = this.planes;
  3395. for( var i = 0; i < 6; i ++ ) {
  3396. planes[i].copy( frustum.planes[i] );
  3397. }
  3398. return this;
  3399. },
  3400. setFromMatrix: function ( m ) {
  3401. var planes = this.planes;
  3402. var me = m.elements;
  3403. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  3404. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  3405. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  3406. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  3407. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3408. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3409. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3410. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3411. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3412. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3413. return this;
  3414. },
  3415. intersectsObject: function () {
  3416. var sphere = new THREE.Sphere();
  3417. return function ( object ) {
  3418. var geometry = object.geometry;
  3419. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  3420. sphere.copy( geometry.boundingSphere );
  3421. sphere.applyMatrix4( object.matrixWorld );
  3422. return this.intersectsSphere( sphere );
  3423. };
  3424. }(),
  3425. intersectsSphere: function ( sphere ) {
  3426. var planes = this.planes;
  3427. var center = sphere.center;
  3428. var negRadius = -sphere.radius;
  3429. for ( var i = 0; i < 6; i ++ ) {
  3430. var distance = planes[ i ].distanceToPoint( center );
  3431. if ( distance < negRadius ) {
  3432. return false;
  3433. }
  3434. }
  3435. return true;
  3436. },
  3437. intersectsBox : function() {
  3438. var p1 = new THREE.Vector3(),
  3439. p2 = new THREE.Vector3();
  3440. return function( box ) {
  3441. var planes = this.planes;
  3442. for ( var i = 0; i < 6 ; i ++ ) {
  3443. var plane = planes[i];
  3444. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  3445. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  3446. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  3447. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  3448. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  3449. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  3450. var d1 = plane.distanceToPoint( p1 );
  3451. var d2 = plane.distanceToPoint( p2 );
  3452. // if both outside plane, no intersection
  3453. if ( d1 < 0 && d2 < 0 ) {
  3454. return false;
  3455. }
  3456. }
  3457. return true;
  3458. };
  3459. }(),
  3460. containsPoint: function ( point ) {
  3461. var planes = this.planes;
  3462. for ( var i = 0; i < 6; i ++ ) {
  3463. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3464. return false;
  3465. }
  3466. }
  3467. return true;
  3468. },
  3469. clone: function () {
  3470. return new THREE.Frustum().copy( this );
  3471. }
  3472. };
  3473. /**
  3474. * @author bhouston / http://exocortex.com
  3475. */
  3476. THREE.Plane = function ( normal, constant ) {
  3477. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3478. this.constant = ( constant !== undefined ) ? constant : 0;
  3479. };
  3480. THREE.Plane.prototype = {
  3481. constructor: THREE.Plane,
  3482. set: function ( normal, constant ) {
  3483. this.normal.copy( normal );
  3484. this.constant = constant;
  3485. return this;
  3486. },
  3487. setComponents: function ( x, y, z, w ) {
  3488. this.normal.set( x, y, z );
  3489. this.constant = w;
  3490. return this;
  3491. },
  3492. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3493. this.normal.copy( normal );
  3494. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3495. return this;
  3496. },
  3497. setFromCoplanarPoints: function() {
  3498. var v1 = new THREE.Vector3();
  3499. var v2 = new THREE.Vector3();
  3500. return function ( a, b, c ) {
  3501. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3502. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3503. this.setFromNormalAndCoplanarPoint( normal, a );
  3504. return this;
  3505. };
  3506. }(),
  3507. copy: function ( plane ) {
  3508. this.normal.copy( plane.normal );
  3509. this.constant = plane.constant;
  3510. return this;
  3511. },
  3512. normalize: function () {
  3513. // Note: will lead to a divide by zero if the plane is invalid.
  3514. var inverseNormalLength = 1.0 / this.normal.length();
  3515. this.normal.multiplyScalar( inverseNormalLength );
  3516. this.constant *= inverseNormalLength;
  3517. return this;
  3518. },
  3519. negate: function () {
  3520. this.constant *= -1;
  3521. this.normal.negate();
  3522. return this;
  3523. },
  3524. distanceToPoint: function ( point ) {
  3525. return this.normal.dot( point ) + this.constant;
  3526. },
  3527. distanceToSphere: function ( sphere ) {
  3528. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3529. },
  3530. projectPoint: function ( point, optionalTarget ) {
  3531. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3532. },
  3533. orthoPoint: function ( point, optionalTarget ) {
  3534. var perpendicularMagnitude = this.distanceToPoint( point );
  3535. var result = optionalTarget || new THREE.Vector3();
  3536. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3537. },
  3538. isIntersectionLine: function ( line ) {
  3539. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3540. var startSign = this.distanceToPoint( line.start );
  3541. var endSign = this.distanceToPoint( line.end );
  3542. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3543. },
  3544. intersectLine: function() {
  3545. var v1 = new THREE.Vector3();
  3546. return function ( line, optionalTarget ) {
  3547. var result = optionalTarget || new THREE.Vector3();
  3548. var direction = line.delta( v1 );
  3549. var denominator = this.normal.dot( direction );
  3550. if ( denominator == 0 ) {
  3551. // line is coplanar, return origin
  3552. if( this.distanceToPoint( line.start ) == 0 ) {
  3553. return result.copy( line.start );
  3554. }
  3555. // Unsure if this is the correct method to handle this case.
  3556. return undefined;
  3557. }
  3558. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3559. if( t < 0 || t > 1 ) {
  3560. return undefined;
  3561. }
  3562. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3563. };
  3564. }(),
  3565. coplanarPoint: function ( optionalTarget ) {
  3566. var result = optionalTarget || new THREE.Vector3();
  3567. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3568. },
  3569. applyMatrix4: function() {
  3570. var v1 = new THREE.Vector3();
  3571. var v2 = new THREE.Vector3();
  3572. var m1 = new THREE.Matrix3();
  3573. return function ( matrix, optionalNormalMatrix ) {
  3574. // compute new normal based on theory here:
  3575. // http://www.songho.ca/opengl/gl_normaltransform.html
  3576. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  3577. var newNormal = v1.copy( this.normal ).applyMatrix3( normalMatrix );
  3578. var newCoplanarPoint = this.coplanarPoint( v2 );
  3579. newCoplanarPoint.applyMatrix4( matrix );
  3580. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3581. return this;
  3582. };
  3583. }(),
  3584. translate: function ( offset ) {
  3585. this.constant = this.constant - offset.dot( this.normal );
  3586. return this;
  3587. },
  3588. equals: function ( plane ) {
  3589. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3590. },
  3591. clone: function () {
  3592. return new THREE.Plane().copy( this );
  3593. }
  3594. };
  3595. /**
  3596. * @author alteredq / http://alteredqualia.com/
  3597. * @author mrdoob / http://mrdoob.com/
  3598. */
  3599. THREE.Math = {
  3600. PI2: Math.PI * 2,
  3601. generateUUID: function () {
  3602. // http://www.broofa.com/Tools/Math.uuid.htm
  3603. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  3604. var uuid = new Array(36);
  3605. var rnd = 0, r;
  3606. return function () {
  3607. for ( var i = 0; i < 36; i ++ ) {
  3608. if ( i == 8 || i == 13 || i == 18 || i == 23 ) {
  3609. uuid[ i ] = '-';
  3610. } else if ( i == 14 ) {
  3611. uuid[ i ] = '4';
  3612. } else {
  3613. if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
  3614. r = rnd & 0xf;
  3615. rnd = rnd >> 4;
  3616. uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
  3617. }
  3618. }
  3619. return uuid.join('');
  3620. };
  3621. }(),
  3622. // Clamp value to range <a, b>
  3623. clamp: function ( x, a, b ) {
  3624. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3625. },
  3626. // Clamp value to range <a, inf)
  3627. clampBottom: function ( x, a ) {
  3628. return x < a ? a : x;
  3629. },
  3630. // Linear mapping from range <a1, a2> to range <b1, b2>
  3631. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3632. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3633. },
  3634. // http://en.wikipedia.org/wiki/Smoothstep
  3635. smoothstep: function ( x, min, max ) {
  3636. if ( x <= min ) return 0;
  3637. if ( x >= max ) return 1;
  3638. x = ( x - min )/( max - min );
  3639. return x*x*(3 - 2*x);
  3640. },
  3641. smootherstep: function ( x, min, max ) {
  3642. if ( x <= min ) return 0;
  3643. if ( x >= max ) return 1;
  3644. x = ( x - min )/( max - min );
  3645. return x*x*x*(x*(x*6 - 15) + 10);
  3646. },
  3647. // Random float from <0, 1> with 16 bits of randomness
  3648. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3649. random16: function () {
  3650. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3651. },
  3652. // Random integer from <low, high> interval
  3653. randInt: function ( low, high ) {
  3654. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  3655. },
  3656. // Random float from <low, high> interval
  3657. randFloat: function ( low, high ) {
  3658. return low + Math.random() * ( high - low );
  3659. },
  3660. // Random float from <-range/2, range/2> interval
  3661. randFloatSpread: function ( range ) {
  3662. return range * ( 0.5 - Math.random() );
  3663. },
  3664. sign: function ( x ) {
  3665. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  3666. },
  3667. degToRad: function() {
  3668. var degreeToRadiansFactor = Math.PI / 180;
  3669. return function ( degrees ) {
  3670. return degrees * degreeToRadiansFactor;
  3671. };
  3672. }(),
  3673. radToDeg: function() {
  3674. var radianToDegreesFactor = 180 / Math.PI;
  3675. return function ( radians ) {
  3676. return radians * radianToDegreesFactor;
  3677. };
  3678. }(),
  3679. isPowerOfTwo: function ( value ) {
  3680. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  3681. }
  3682. };
  3683. /**
  3684. * Spline from Tween.js, slightly optimized (and trashed)
  3685. * http://sole.github.com/tween.js/examples/05_spline.html
  3686. *
  3687. * @author mrdoob / http://mrdoob.com/
  3688. * @author alteredq / http://alteredqualia.com/
  3689. */
  3690. THREE.Spline = function ( points ) {
  3691. this.points = points;
  3692. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3693. point, intPoint, weight, w2, w3,
  3694. pa, pb, pc, pd;
  3695. this.initFromArray = function( a ) {
  3696. this.points = [];
  3697. for ( var i = 0; i < a.length; i++ ) {
  3698. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3699. }
  3700. };
  3701. this.getPoint = function ( k ) {
  3702. point = ( this.points.length - 1 ) * k;
  3703. intPoint = Math.floor( point );
  3704. weight = point - intPoint;
  3705. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3706. c[ 1 ] = intPoint;
  3707. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3708. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3709. pa = this.points[ c[ 0 ] ];
  3710. pb = this.points[ c[ 1 ] ];
  3711. pc = this.points[ c[ 2 ] ];
  3712. pd = this.points[ c[ 3 ] ];
  3713. w2 = weight * weight;
  3714. w3 = weight * w2;
  3715. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3716. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3717. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3718. return v3;
  3719. };
  3720. this.getControlPointsArray = function () {
  3721. var i, p, l = this.points.length,
  3722. coords = [];
  3723. for ( i = 0; i < l; i ++ ) {
  3724. p = this.points[ i ];
  3725. coords[ i ] = [ p.x, p.y, p.z ];
  3726. }
  3727. return coords;
  3728. };
  3729. // approximate length by summing linear segments
  3730. this.getLength = function ( nSubDivisions ) {
  3731. var i, index, nSamples, position,
  3732. point = 0, intPoint = 0, oldIntPoint = 0,
  3733. oldPosition = new THREE.Vector3(),
  3734. tmpVec = new THREE.Vector3(),
  3735. chunkLengths = [],
  3736. totalLength = 0;
  3737. // first point has 0 length
  3738. chunkLengths[ 0 ] = 0;
  3739. if ( !nSubDivisions ) nSubDivisions = 100;
  3740. nSamples = this.points.length * nSubDivisions;
  3741. oldPosition.copy( this.points[ 0 ] );
  3742. for ( i = 1; i < nSamples; i ++ ) {
  3743. index = i / nSamples;
  3744. position = this.getPoint( index );
  3745. tmpVec.copy( position );
  3746. totalLength += tmpVec.distanceTo( oldPosition );
  3747. oldPosition.copy( position );
  3748. point = ( this.points.length - 1 ) * index;
  3749. intPoint = Math.floor( point );
  3750. if ( intPoint != oldIntPoint ) {
  3751. chunkLengths[ intPoint ] = totalLength;
  3752. oldIntPoint = intPoint;
  3753. }
  3754. }
  3755. // last point ends with total length
  3756. chunkLengths[ chunkLengths.length ] = totalLength;
  3757. return { chunks: chunkLengths, total: totalLength };
  3758. };
  3759. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3760. var i, j,
  3761. index, indexCurrent, indexNext,
  3762. linearDistance, realDistance,
  3763. sampling, position,
  3764. newpoints = [],
  3765. tmpVec = new THREE.Vector3(),
  3766. sl = this.getLength();
  3767. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3768. for ( i = 1; i < this.points.length; i++ ) {
  3769. //tmpVec.copy( this.points[ i - 1 ] );
  3770. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3771. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3772. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3773. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3774. indexNext = i / ( this.points.length - 1 );
  3775. for ( j = 1; j < sampling - 1; j++ ) {
  3776. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3777. position = this.getPoint( index );
  3778. newpoints.push( tmpVec.copy( position ).clone() );
  3779. }
  3780. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3781. }
  3782. this.points = newpoints;
  3783. };
  3784. // Catmull-Rom
  3785. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3786. var v0 = ( p2 - p0 ) * 0.5,
  3787. v1 = ( p3 - p1 ) * 0.5;
  3788. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3789. };
  3790. };
  3791. /**
  3792. * @author bhouston / http://exocortex.com
  3793. * @author mrdoob / http://mrdoob.com/
  3794. */
  3795. THREE.Triangle = function ( a, b, c ) {
  3796. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3797. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3798. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3799. };
  3800. THREE.Triangle.normal = function() {
  3801. var v0 = new THREE.Vector3();
  3802. return function ( a, b, c, optionalTarget ) {
  3803. var result = optionalTarget || new THREE.Vector3();
  3804. result.subVectors( c, b );
  3805. v0.subVectors( a, b );
  3806. result.cross( v0 );
  3807. var resultLengthSq = result.lengthSq();
  3808. if( resultLengthSq > 0 ) {
  3809. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3810. }
  3811. return result.set( 0, 0, 0 );
  3812. };
  3813. }();
  3814. // static/instance method to calculate barycoordinates
  3815. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3816. THREE.Triangle.barycoordFromPoint = function() {
  3817. var v0 = new THREE.Vector3();
  3818. var v1 = new THREE.Vector3();
  3819. var v2 = new THREE.Vector3();
  3820. return function ( point, a, b, c, optionalTarget ) {
  3821. v0.subVectors( c, a );
  3822. v1.subVectors( b, a );
  3823. v2.subVectors( point, a );
  3824. var dot00 = v0.dot( v0 );
  3825. var dot01 = v0.dot( v1 );
  3826. var dot02 = v0.dot( v2 );
  3827. var dot11 = v1.dot( v1 );
  3828. var dot12 = v1.dot( v2 );
  3829. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3830. var result = optionalTarget || new THREE.Vector3();
  3831. // colinear or singular triangle
  3832. if( denom == 0 ) {
  3833. // arbitrary location outside of triangle?
  3834. // not sure if this is the best idea, maybe should be returning undefined
  3835. return result.set( -2, -1, -1 );
  3836. }
  3837. var invDenom = 1 / denom;
  3838. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3839. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3840. // barycoordinates must always sum to 1
  3841. return result.set( 1 - u - v, v, u );
  3842. };
  3843. }();
  3844. THREE.Triangle.containsPoint = function() {
  3845. var v1 = new THREE.Vector3();
  3846. return function ( point, a, b, c ) {
  3847. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  3848. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3849. };
  3850. }();
  3851. THREE.Triangle.prototype = {
  3852. constructor: THREE.Triangle,
  3853. set: function ( a, b, c ) {
  3854. this.a.copy( a );
  3855. this.b.copy( b );
  3856. this.c.copy( c );
  3857. return this;
  3858. },
  3859. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3860. this.a.copy( points[i0] );
  3861. this.b.copy( points[i1] );
  3862. this.c.copy( points[i2] );
  3863. return this;
  3864. },
  3865. copy: function ( triangle ) {
  3866. this.a.copy( triangle.a );
  3867. this.b.copy( triangle.b );
  3868. this.c.copy( triangle.c );
  3869. return this;
  3870. },
  3871. area: function() {
  3872. var v0 = new THREE.Vector3();
  3873. var v1 = new THREE.Vector3();
  3874. return function () {
  3875. v0.subVectors( this.c, this.b );
  3876. v1.subVectors( this.a, this.b );
  3877. return v0.cross( v1 ).length() * 0.5;
  3878. };
  3879. }(),
  3880. midpoint: function ( optionalTarget ) {
  3881. var result = optionalTarget || new THREE.Vector3();
  3882. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  3883. },
  3884. normal: function ( optionalTarget ) {
  3885. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3886. },
  3887. plane: function ( optionalTarget ) {
  3888. var result = optionalTarget || new THREE.Plane();
  3889. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  3890. },
  3891. barycoordFromPoint: function ( point, optionalTarget ) {
  3892. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  3893. },
  3894. containsPoint: function ( point ) {
  3895. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  3896. },
  3897. equals: function ( triangle ) {
  3898. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  3899. },
  3900. clone: function () {
  3901. return new THREE.Triangle().copy( this );
  3902. }
  3903. };
  3904. /**
  3905. * @author mrdoob / http://mrdoob.com/
  3906. */
  3907. THREE.Vertex = function ( v ) {
  3908. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  3909. return v;
  3910. };
  3911. /**
  3912. * @author mrdoob / http://mrdoob.com/
  3913. */
  3914. THREE.UV = function ( u, v ) {
  3915. console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
  3916. return new THREE.Vector2( u, v );
  3917. };
  3918. /**
  3919. * @author alteredq / http://alteredqualia.com/
  3920. */
  3921. THREE.Clock = function ( autoStart ) {
  3922. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  3923. this.startTime = 0;
  3924. this.oldTime = 0;
  3925. this.elapsedTime = 0;
  3926. this.running = false;
  3927. };
  3928. THREE.Clock.prototype = {
  3929. constructor: THREE.Clock,
  3930. start: function () {
  3931. this.startTime = self.performance !== undefined && self.performance.now !== undefined
  3932. ? self.performance.now()
  3933. : Date.now();
  3934. this.oldTime = this.startTime;
  3935. this.running = true;
  3936. },
  3937. stop: function () {
  3938. this.getElapsedTime();
  3939. this.running = false;
  3940. },
  3941. getElapsedTime: function () {
  3942. this.getDelta();
  3943. return this.elapsedTime;
  3944. },
  3945. getDelta: function () {
  3946. var diff = 0;
  3947. if ( this.autoStart && ! this.running ) {
  3948. this.start();
  3949. }
  3950. if ( this.running ) {
  3951. var newTime = self.performance !== undefined && self.performance.now !== undefined
  3952. ? self.performance.now()
  3953. : Date.now();
  3954. diff = 0.001 * ( newTime - this.oldTime );
  3955. this.oldTime = newTime;
  3956. this.elapsedTime += diff;
  3957. }
  3958. return diff;
  3959. }
  3960. };
  3961. /**
  3962. * https://github.com/mrdoob/eventdispatcher.js/
  3963. */
  3964. THREE.EventDispatcher = function () {}
  3965. THREE.EventDispatcher.prototype = {
  3966. constructor: THREE.EventDispatcher,
  3967. apply: function ( object ) {
  3968. object.addEventListener = THREE.EventDispatcher.prototype.addEventListener;
  3969. object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener;
  3970. object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener;
  3971. object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent;
  3972. },
  3973. addEventListener: function ( type, listener ) {
  3974. if ( this._listeners === undefined ) this._listeners = {};
  3975. var listeners = this._listeners;
  3976. if ( listeners[ type ] === undefined ) {
  3977. listeners[ type ] = [];
  3978. }
  3979. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  3980. listeners[ type ].push( listener );
  3981. }
  3982. },
  3983. hasEventListener: function ( type, listener ) {
  3984. if ( this._listeners === undefined ) return false;
  3985. var listeners = this._listeners;
  3986. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  3987. return true;
  3988. }
  3989. return false;
  3990. },
  3991. removeEventListener: function ( type, listener ) {
  3992. if ( this._listeners === undefined ) return;
  3993. var listeners = this._listeners;
  3994. var listenerArray = listeners[ type ];
  3995. if ( listenerArray !== undefined ) {
  3996. var index = listenerArray.indexOf( listener );
  3997. if ( index !== - 1 ) {
  3998. listenerArray.splice( index, 1 );
  3999. }
  4000. }
  4001. },
  4002. dispatchEvent: function () {
  4003. var array = [];
  4004. return function ( event ) {
  4005. if ( this._listeners === undefined ) return;
  4006. var listeners = this._listeners;
  4007. var listenerArray = listeners[ event.type ];
  4008. if ( listenerArray !== undefined ) {
  4009. event.target = this;
  4010. var length = listenerArray.length;
  4011. for ( var i = 0; i < length; i ++ ) {
  4012. array[ i ] = listenerArray[ i ];
  4013. }
  4014. for ( var i = 0; i < length; i ++ ) {
  4015. array[ i ].call( this, event );
  4016. }
  4017. }
  4018. };
  4019. }()
  4020. };
  4021. /**
  4022. * @author mrdoob / http://mrdoob.com/
  4023. * @author bhouston / http://exocortex.com/
  4024. * @author stephomi / http://stephaneginier.com/
  4025. */
  4026. ( function ( THREE ) {
  4027. THREE.Raycaster = function ( origin, direction, near, far ) {
  4028. this.ray = new THREE.Ray( origin, direction );
  4029. // direction is assumed to be normalized (for accurate distance calculations)
  4030. this.near = near || 0;
  4031. this.far = far || Infinity;
  4032. };
  4033. var sphere = new THREE.Sphere();
  4034. var localRay = new THREE.Ray();
  4035. var facePlane = new THREE.Plane();
  4036. var intersectPoint = new THREE.Vector3();
  4037. var matrixPosition = new THREE.Vector3();
  4038. var inverseMatrix = new THREE.Matrix4();
  4039. var descSort = function ( a, b ) {
  4040. return a.distance - b.distance;
  4041. };
  4042. var vA = new THREE.Vector3();
  4043. var vB = new THREE.Vector3();
  4044. var vC = new THREE.Vector3();
  4045. var intersectObject = function ( object, raycaster, intersects ) {
  4046. if ( object instanceof THREE.Sprite ) {
  4047. matrixPosition.setFromMatrixPosition( object.matrixWorld );
  4048. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  4049. if ( distance > object.scale.x ) {
  4050. return intersects;
  4051. }
  4052. intersects.push( {
  4053. distance: distance,
  4054. point: object.position,
  4055. face: null,
  4056. object: object
  4057. } );
  4058. } else if ( object instanceof THREE.LOD ) {
  4059. matrixPosition.setFromMatrixPosition( object.matrixWorld );
  4060. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  4061. intersectObject( object.getObjectForDistance( distance ), raycaster, intersects );
  4062. } else if ( object instanceof THREE.Mesh ) {
  4063. var geometry = object.geometry;
  4064. // Checking boundingSphere distance to ray
  4065. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  4066. sphere.copy( geometry.boundingSphere );
  4067. sphere.applyMatrix4( object.matrixWorld );
  4068. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  4069. return intersects;
  4070. }
  4071. // Check boundingBox before continuing
  4072. inverseMatrix.getInverse( object.matrixWorld );
  4073. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  4074. if ( geometry.boundingBox !== null ) {
  4075. if ( localRay.isIntersectionBox( geometry.boundingBox ) === false ) {
  4076. return intersects;
  4077. }
  4078. }
  4079. if ( geometry instanceof THREE.BufferGeometry ) {
  4080. var material = object.material;
  4081. if ( material === undefined ) return intersects;
  4082. if ( geometry.dynamic === false ) return intersects;
  4083. var a, b, c;
  4084. var precision = raycaster.precision;
  4085. if ( geometry.attributes.index !== undefined ) {
  4086. var offsets = geometry.offsets;
  4087. var indices = geometry.attributes.index.array;
  4088. var positions = geometry.attributes.position.array;
  4089. var offLength = geometry.offsets.length;
  4090. var fl = geometry.attributes.index.array.length / 3;
  4091. for ( var oi = 0; oi < offLength; ++oi ) {
  4092. var start = offsets[ oi ].start;
  4093. var count = offsets[ oi ].count;
  4094. var index = offsets[ oi ].index;
  4095. for ( var i = start, il = start + count; i < il; i += 3 ) {
  4096. a = index + indices[ i ];
  4097. b = index + indices[ i + 1 ];
  4098. c = index + indices[ i + 2 ];
  4099. vA.set(
  4100. positions[ a * 3 ],
  4101. positions[ a * 3 + 1 ],
  4102. positions[ a * 3 + 2 ]
  4103. );
  4104. vB.set(
  4105. positions[ b * 3 ],
  4106. positions[ b * 3 + 1 ],
  4107. positions[ b * 3 + 2 ]
  4108. );
  4109. vC.set(
  4110. positions[ c * 3 ],
  4111. positions[ c * 3 + 1 ],
  4112. positions[ c * 3 + 2 ]
  4113. );
  4114. if ( material.side === THREE.BackSide ) {
  4115. var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );
  4116. } else {
  4117. var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  4118. }
  4119. if ( intersectionPoint === null ) continue;
  4120. intersectionPoint.applyMatrix4( object.matrixWorld );
  4121. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4122. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4123. intersects.push( {
  4124. distance: distance,
  4125. point: intersectionPoint,
  4126. face: null,
  4127. faceIndex: null,
  4128. object: object
  4129. } );
  4130. }
  4131. }
  4132. } else {
  4133. var offsets = geometry.offsets;
  4134. var positions = geometry.attributes.position.array;
  4135. var offLength = geometry.offsets.length;
  4136. var fl = geometry.attributes.position.array.length;
  4137. for ( var i = 0; i < fl; i += 3 ) {
  4138. a = i;
  4139. b = i + 1;
  4140. c = i + 2;
  4141. vA.set(
  4142. positions[ a * 3 ],
  4143. positions[ a * 3 + 1 ],
  4144. positions[ a * 3 + 2 ]
  4145. );
  4146. vB.set(
  4147. positions[ b * 3 ],
  4148. positions[ b * 3 + 1 ],
  4149. positions[ b * 3 + 2 ]
  4150. );
  4151. vC.set(
  4152. positions[ c * 3 ],
  4153. positions[ c * 3 + 1 ],
  4154. positions[ c * 3 + 2 ]
  4155. );
  4156. if ( material.side === THREE.BackSide ) {
  4157. var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );
  4158. } else {
  4159. var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  4160. }
  4161. if ( intersectionPoint === null ) continue;
  4162. intersectionPoint.applyMatrix4( object.matrixWorld );
  4163. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4164. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4165. intersects.push( {
  4166. distance: distance,
  4167. point: intersectionPoint,
  4168. face: null,
  4169. faceIndex: null,
  4170. object: object
  4171. } );
  4172. }
  4173. }
  4174. } else if ( geometry instanceof THREE.Geometry ) {
  4175. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4176. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  4177. var a, b, c, d;
  4178. var precision = raycaster.precision;
  4179. var vertices = geometry.vertices;
  4180. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  4181. var face = geometry.faces[ f ];
  4182. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  4183. if ( material === undefined ) continue;
  4184. a = vertices[ face.a ];
  4185. b = vertices[ face.b ];
  4186. c = vertices[ face.c ];
  4187. if ( material.morphTargets === true ) {
  4188. var morphTargets = geometry.morphTargets;
  4189. var morphInfluences = object.morphTargetInfluences;
  4190. vA.set( 0, 0, 0 );
  4191. vB.set( 0, 0, 0 );
  4192. vC.set( 0, 0, 0 );
  4193. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  4194. var influence = morphInfluences[ t ];
  4195. if ( influence === 0 ) continue;
  4196. var targets = morphTargets[ t ].vertices;
  4197. vA.x += ( targets[ face.a ].x - a.x ) * influence;
  4198. vA.y += ( targets[ face.a ].y - a.y ) * influence;
  4199. vA.z += ( targets[ face.a ].z - a.z ) * influence;
  4200. vB.x += ( targets[ face.b ].x - b.x ) * influence;
  4201. vB.y += ( targets[ face.b ].y - b.y ) * influence;
  4202. vB.z += ( targets[ face.b ].z - b.z ) * influence;
  4203. vC.x += ( targets[ face.c ].x - c.x ) * influence;
  4204. vC.y += ( targets[ face.c ].y - c.y ) * influence;
  4205. vC.z += ( targets[ face.c ].z - c.z ) * influence;
  4206. }
  4207. vA.add( a );
  4208. vB.add( b );
  4209. vC.add( c );
  4210. a = vA;
  4211. b = vB;
  4212. c = vC;
  4213. }
  4214. if ( material.side === THREE.BackSide ) {
  4215. var intersectionPoint = localRay.intersectTriangle( c, b, a, true );
  4216. } else {
  4217. var intersectionPoint = localRay.intersectTriangle( a, b, c, material.side !== THREE.DoubleSide );
  4218. }
  4219. if ( intersectionPoint === null ) continue;
  4220. intersectionPoint.applyMatrix4( object.matrixWorld );
  4221. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4222. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4223. intersects.push( {
  4224. distance: distance,
  4225. point: intersectionPoint,
  4226. face: face,
  4227. faceIndex: f,
  4228. object: object
  4229. } );
  4230. }
  4231. }
  4232. } else if ( object instanceof THREE.Line ) {
  4233. var precision = raycaster.linePrecision;
  4234. var precisionSq = precision * precision;
  4235. var geometry = object.geometry;
  4236. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  4237. // Checking boundingSphere distance to ray
  4238. sphere.copy( geometry.boundingSphere );
  4239. sphere.applyMatrix4( object.matrixWorld );
  4240. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  4241. return intersects;
  4242. }
  4243. inverseMatrix.getInverse( object.matrixWorld );
  4244. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  4245. /* if ( geometry instanceof THREE.BufferGeometry ) {
  4246. } else */ if ( geometry instanceof THREE.Geometry ) {
  4247. var vertices = geometry.vertices;
  4248. var nbVertices = vertices.length;
  4249. var interSegment = new THREE.Vector3();
  4250. var interRay = new THREE.Vector3();
  4251. var step = object.type === THREE.LineStrip ? 1 : 2;
  4252. for ( var i = 0; i < nbVertices - 1; i = i + step ) {
  4253. var distSq = localRay.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  4254. if ( distSq > precisionSq ) continue;
  4255. var distance = localRay.origin.distanceTo( interRay );
  4256. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  4257. intersects.push( {
  4258. distance: distance,
  4259. // What do we want? intersection point on the ray or on the segment??
  4260. // point: raycaster.ray.at( distance ),
  4261. point: interSegment.clone().applyMatrix4( object.matrixWorld ),
  4262. face: null,
  4263. faceIndex: null,
  4264. object: object
  4265. } );
  4266. }
  4267. }
  4268. }
  4269. };
  4270. var intersectDescendants = function ( object, raycaster, intersects ) {
  4271. var descendants = object.getDescendants();
  4272. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  4273. intersectObject( descendants[ i ], raycaster, intersects );
  4274. }
  4275. };
  4276. //
  4277. THREE.Raycaster.prototype.precision = 0.0001;
  4278. THREE.Raycaster.prototype.linePrecision = 1;
  4279. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  4280. this.ray.set( origin, direction );
  4281. // direction is assumed to be normalized (for accurate distance calculations)
  4282. };
  4283. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  4284. var intersects = [];
  4285. if ( recursive === true ) {
  4286. intersectDescendants( object, this, intersects );
  4287. }
  4288. intersectObject( object, this, intersects );
  4289. intersects.sort( descSort );
  4290. return intersects;
  4291. };
  4292. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  4293. var intersects = [];
  4294. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  4295. intersectObject( objects[ i ], this, intersects );
  4296. if ( recursive === true ) {
  4297. intersectDescendants( objects[ i ], this, intersects );
  4298. }
  4299. }
  4300. intersects.sort( descSort );
  4301. return intersects;
  4302. };
  4303. }( THREE ) );
  4304. /**
  4305. * @author mrdoob / http://mrdoob.com/
  4306. * @author mikael emtinger / http://gomo.se/
  4307. * @author alteredq / http://alteredqualia.com/
  4308. * @author WestLangley / http://github.com/WestLangley
  4309. */
  4310. THREE.Object3D = function () {
  4311. this.id = THREE.Object3DIdCount ++;
  4312. this.uuid = THREE.Math.generateUUID();
  4313. this.name = '';
  4314. this.parent = undefined;
  4315. this.children = [];
  4316. this.up = new THREE.Vector3( 0, 1, 0 );
  4317. this.position = new THREE.Vector3();
  4318. this._rotation = new THREE.Euler();
  4319. this._quaternion = new THREE.Quaternion();
  4320. this.scale = new THREE.Vector3( 1, 1, 1 );
  4321. // keep rotation and quaternion in sync
  4322. this._rotation._quaternion = this.quaternion;
  4323. this._quaternion._euler = this.rotation;
  4324. this.renderDepth = null;
  4325. this.rotationAutoUpdate = true;
  4326. this.matrix = new THREE.Matrix4();
  4327. this.matrixWorld = new THREE.Matrix4();
  4328. this.matrixAutoUpdate = true;
  4329. this.matrixWorldNeedsUpdate = true;
  4330. this.visible = true;
  4331. this.castShadow = false;
  4332. this.receiveShadow = false;
  4333. this.frustumCulled = true;
  4334. this.userData = {};
  4335. };
  4336. THREE.Object3D.prototype = {
  4337. constructor: THREE.Object3D,
  4338. get rotation () {
  4339. return this._rotation;
  4340. },
  4341. set rotation ( value ) {
  4342. this._rotation = value;
  4343. this._rotation._quaternion = this._quaternion;
  4344. this._quaternion._euler = this._rotation;
  4345. this._rotation._updateQuaternion();
  4346. },
  4347. get quaternion () {
  4348. return this._quaternion;
  4349. },
  4350. set quaternion ( value ) {
  4351. this._quaternion = value;
  4352. this._quaternion._euler = this._rotation;
  4353. this._rotation._quaternion = this._quaternion;
  4354. this._quaternion._updateEuler();
  4355. },
  4356. get eulerOrder () {
  4357. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4358. return this.rotation.order;
  4359. },
  4360. set eulerOrder ( value ) {
  4361. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4362. this.rotation.order = value;
  4363. },
  4364. get useQuaternion () {
  4365. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4366. },
  4367. set useQuaternion ( value ) {
  4368. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4369. },
  4370. applyMatrix: function ( matrix ) {
  4371. this.matrix.multiplyMatrices( matrix, this.matrix );
  4372. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4373. },
  4374. setRotationFromAxisAngle: function ( axis, angle ) {
  4375. // assumes axis is normalized
  4376. this.quaternion.setFromAxisAngle( axis, angle );
  4377. },
  4378. setRotationFromEuler: function ( euler ) {
  4379. this.quaternion.setFromEuler( euler, true );
  4380. },
  4381. setRotationFromMatrix: function ( m ) {
  4382. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4383. this.quaternion.setFromRotationMatrix( m );
  4384. },
  4385. setRotationFromQuaternion: function ( q ) {
  4386. // assumes q is normalized
  4387. this.quaternion.copy( q );
  4388. },
  4389. rotateOnAxis: function() {
  4390. // rotate object on axis in object space
  4391. // axis is assumed to be normalized
  4392. var q1 = new THREE.Quaternion();
  4393. return function ( axis, angle ) {
  4394. q1.setFromAxisAngle( axis, angle );
  4395. this.quaternion.multiply( q1 );
  4396. return this;
  4397. }
  4398. }(),
  4399. rotateX: function () {
  4400. var v1 = new THREE.Vector3( 1, 0, 0 );
  4401. return function ( angle ) {
  4402. return this.rotateOnAxis( v1, angle );
  4403. };
  4404. }(),
  4405. rotateY: function () {
  4406. var v1 = new THREE.Vector3( 0, 1, 0 );
  4407. return function ( angle ) {
  4408. return this.rotateOnAxis( v1, angle );
  4409. };
  4410. }(),
  4411. rotateZ: function () {
  4412. var v1 = new THREE.Vector3( 0, 0, 1 );
  4413. return function ( angle ) {
  4414. return this.rotateOnAxis( v1, angle );
  4415. };
  4416. }(),
  4417. translateOnAxis: function () {
  4418. // translate object by distance along axis in object space
  4419. // axis is assumed to be normalized
  4420. var v1 = new THREE.Vector3();
  4421. return function ( axis, distance ) {
  4422. v1.copy( axis );
  4423. v1.applyQuaternion( this.quaternion );
  4424. this.position.add( v1.multiplyScalar( distance ) );
  4425. return this;
  4426. }
  4427. }(),
  4428. translate: function ( distance, axis ) {
  4429. console.warn( 'DEPRECATED: Object3D\'s .translate() has been removed. Use .translateOnAxis( axis, distance ) instead. Note args have been changed.' );
  4430. return this.translateOnAxis( axis, distance );
  4431. },
  4432. translateX: function () {
  4433. var v1 = new THREE.Vector3( 1, 0, 0 );
  4434. return function ( distance ) {
  4435. return this.translateOnAxis( v1, distance );
  4436. };
  4437. }(),
  4438. translateY: function () {
  4439. var v1 = new THREE.Vector3( 0, 1, 0 );
  4440. return function ( distance ) {
  4441. return this.translateOnAxis( v1, distance );
  4442. };
  4443. }(),
  4444. translateZ: function () {
  4445. var v1 = new THREE.Vector3( 0, 0, 1 );
  4446. return function ( distance ) {
  4447. return this.translateOnAxis( v1, distance );
  4448. };
  4449. }(),
  4450. localToWorld: function ( vector ) {
  4451. return vector.applyMatrix4( this.matrixWorld );
  4452. },
  4453. worldToLocal: function () {
  4454. var m1 = new THREE.Matrix4();
  4455. return function ( vector ) {
  4456. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  4457. };
  4458. }(),
  4459. lookAt: function () {
  4460. // This routine does not support objects with rotated and/or translated parent(s)
  4461. var m1 = new THREE.Matrix4();
  4462. return function ( vector ) {
  4463. m1.lookAt( vector, this.position, this.up );
  4464. this.quaternion.setFromRotationMatrix( m1 );
  4465. };
  4466. }(),
  4467. add: function ( object ) {
  4468. if ( object === this ) {
  4469. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  4470. return;
  4471. }
  4472. if ( object instanceof THREE.Object3D ) {
  4473. if ( object.parent !== undefined ) {
  4474. object.parent.remove( object );
  4475. }
  4476. object.parent = this;
  4477. object.dispatchEvent( { type: 'added' } );
  4478. this.children.push( object );
  4479. // add to scene
  4480. var scene = this;
  4481. while ( scene.parent !== undefined ) {
  4482. scene = scene.parent;
  4483. }
  4484. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4485. scene.__addObject( object );
  4486. }
  4487. }
  4488. },
  4489. remove: function ( object ) {
  4490. var index = this.children.indexOf( object );
  4491. if ( index !== - 1 ) {
  4492. object.parent = undefined;
  4493. object.dispatchEvent( { type: 'removed' } );
  4494. this.children.splice( index, 1 );
  4495. // remove from scene
  4496. var scene = this;
  4497. while ( scene.parent !== undefined ) {
  4498. scene = scene.parent;
  4499. }
  4500. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4501. scene.__removeObject( object );
  4502. }
  4503. }
  4504. },
  4505. traverse: function ( callback ) {
  4506. callback( this );
  4507. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4508. this.children[ i ].traverse( callback );
  4509. }
  4510. },
  4511. getObjectById: function ( id, recursive ) {
  4512. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4513. var child = this.children[ i ];
  4514. if ( child.id === id ) {
  4515. return child;
  4516. }
  4517. if ( recursive === true ) {
  4518. child = child.getObjectById( id, recursive );
  4519. if ( child !== undefined ) {
  4520. return child;
  4521. }
  4522. }
  4523. }
  4524. return undefined;
  4525. },
  4526. getObjectByName: function ( name, recursive ) {
  4527. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4528. var child = this.children[ i ];
  4529. if ( child.name === name ) {
  4530. return child;
  4531. }
  4532. if ( recursive === true ) {
  4533. child = child.getObjectByName( name, recursive );
  4534. if ( child !== undefined ) {
  4535. return child;
  4536. }
  4537. }
  4538. }
  4539. return undefined;
  4540. },
  4541. getChildByName: function ( name, recursive ) {
  4542. console.warn( 'DEPRECATED: Object3D\'s .getChildByName() has been renamed to .getObjectByName().' );
  4543. return this.getObjectByName( name, recursive );
  4544. },
  4545. getDescendants: function ( array ) {
  4546. if ( array === undefined ) array = [];
  4547. Array.prototype.push.apply( array, this.children );
  4548. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4549. this.children[ i ].getDescendants( array );
  4550. }
  4551. return array;
  4552. },
  4553. updateMatrix: function () {
  4554. this.matrix.compose( this.position, this.quaternion, this.scale );
  4555. this.matrixWorldNeedsUpdate = true;
  4556. },
  4557. updateMatrixWorld: function ( force ) {
  4558. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  4559. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  4560. if ( this.parent === undefined ) {
  4561. this.matrixWorld.copy( this.matrix );
  4562. } else {
  4563. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4564. }
  4565. this.matrixWorldNeedsUpdate = false;
  4566. force = true;
  4567. }
  4568. // update children
  4569. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4570. this.children[ i ].updateMatrixWorld( force );
  4571. }
  4572. },
  4573. clone: function ( object, recursive ) {
  4574. if ( object === undefined ) object = new THREE.Object3D();
  4575. if ( recursive === undefined ) recursive = true;
  4576. object.name = this.name;
  4577. object.up.copy( this.up );
  4578. object.position.copy( this.position );
  4579. object.quaternion.copy( this.quaternion );
  4580. object.scale.copy( this.scale );
  4581. object.renderDepth = this.renderDepth;
  4582. object.rotationAutoUpdate = this.rotationAutoUpdate;
  4583. object.matrix.copy( this.matrix );
  4584. object.matrixWorld.copy( this.matrixWorld );
  4585. object.matrixAutoUpdate = this.matrixAutoUpdate;
  4586. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  4587. object.visible = this.visible;
  4588. object.castShadow = this.castShadow;
  4589. object.receiveShadow = this.receiveShadow;
  4590. object.frustumCulled = this.frustumCulled;
  4591. object.userData = JSON.parse( JSON.stringify( this.userData ) );
  4592. if ( recursive === true ) {
  4593. for ( var i = 0; i < this.children.length; i ++ ) {
  4594. var child = this.children[ i ];
  4595. object.add( child.clone() );
  4596. }
  4597. }
  4598. return object;
  4599. }
  4600. };
  4601. THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype );
  4602. THREE.Object3DIdCount = 0;
  4603. /**
  4604. * @author mrdoob / http://mrdoob.com/
  4605. * @author supereggbert / http://www.paulbrunt.co.uk/
  4606. * @author julianwa / https://github.com/julianwa
  4607. */
  4608. THREE.Projector = function () {
  4609. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  4610. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  4611. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  4612. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  4613. _sprite, _spriteCount, _spritePool = [], _spritePoolLength = 0,
  4614. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  4615. _vA = new THREE.Vector3(),
  4616. _vB = new THREE.Vector3(),
  4617. _vC = new THREE.Vector3(),
  4618. _vector3 = new THREE.Vector3(),
  4619. _vector4 = new THREE.Vector4(),
  4620. _clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ),
  4621. _boundingBox = new THREE.Box3(),
  4622. _points3 = new Array( 3 ),
  4623. _points4 = new Array( 4 ),
  4624. _viewMatrix = new THREE.Matrix4(),
  4625. _viewProjectionMatrix = new THREE.Matrix4(),
  4626. _modelMatrix,
  4627. _modelViewProjectionMatrix = new THREE.Matrix4(),
  4628. _normalMatrix = new THREE.Matrix3(),
  4629. _normalViewMatrix = new THREE.Matrix3(),
  4630. _centroid = new THREE.Vector3(),
  4631. _frustum = new THREE.Frustum(),
  4632. _clippedVertex1PositionScreen = new THREE.Vector4(),
  4633. _clippedVertex2PositionScreen = new THREE.Vector4();
  4634. this.projectVector = function ( vector, camera ) {
  4635. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  4636. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  4637. return vector.applyProjection( _viewProjectionMatrix );
  4638. };
  4639. this.unprojectVector = function () {
  4640. var projectionMatrixInverse = new THREE.Matrix4();
  4641. return function ( vector, camera ) {
  4642. projectionMatrixInverse.getInverse( camera.projectionMatrix );
  4643. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, projectionMatrixInverse );
  4644. return vector.applyProjection( _viewProjectionMatrix );
  4645. };
  4646. }();
  4647. this.pickingRay = function ( vector, camera ) {
  4648. // set two vectors with opposing z values
  4649. vector.z = -1.0;
  4650. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  4651. this.unprojectVector( vector, camera );
  4652. this.unprojectVector( end, camera );
  4653. // find direction from vector to end
  4654. end.sub( vector ).normalize();
  4655. return new THREE.Raycaster( vector, end );
  4656. };
  4657. var getObject = function ( object ) {
  4658. _object = getNextObjectInPool();
  4659. _object.id = object.id;
  4660. _object.object = object;
  4661. if ( object.renderDepth !== null ) {
  4662. _object.z = object.renderDepth;
  4663. } else {
  4664. _vector3.setFromMatrixPosition( object.matrixWorld );
  4665. _vector3.applyProjection( _viewProjectionMatrix );
  4666. _object.z = _vector3.z;
  4667. }
  4668. return _object;
  4669. };
  4670. var projectObject = function ( object ) {
  4671. if ( object.visible === false ) return;
  4672. if ( object instanceof THREE.Light ) {
  4673. _renderData.lights.push( object );
  4674. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  4675. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  4676. _renderData.objects.push( getObject( object ) );
  4677. }
  4678. } else if ( object instanceof THREE.Sprite ) {
  4679. _renderData.sprites.push( getObject( object ) );
  4680. }
  4681. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  4682. projectObject( object.children[ i ] );
  4683. }
  4684. };
  4685. var projectGraph = function ( root, sortObjects ) {
  4686. _objectCount = 0;
  4687. _renderData.objects.length = 0;
  4688. _renderData.sprites.length = 0;
  4689. _renderData.lights.length = 0;
  4690. projectObject( root );
  4691. if ( sortObjects === true ) {
  4692. _renderData.objects.sort( painterSort );
  4693. }
  4694. };
  4695. var RenderState = function () {
  4696. var object = null;
  4697. var setObject = function ( value ) {
  4698. object = value;
  4699. };
  4700. var projectVertex = function ( vertex ) {
  4701. var position = vertex.position;
  4702. var positionWorld = vertex.positionWorld;
  4703. var positionScreen = vertex.positionScreen;
  4704. positionWorld.copy( position ).applyMatrix4( _modelMatrix );
  4705. positionScreen.copy( positionWorld ).applyMatrix4( _viewProjectionMatrix );
  4706. var invW = 1 / positionScreen.w;
  4707. positionScreen.x *= invW;
  4708. positionScreen.y *= invW;
  4709. positionScreen.z *= invW;
  4710. vertex.visible = positionScreen.x >= -1 && positionScreen.x <= 1 &&
  4711. positionScreen.y >= -1 && positionScreen.y <= 1 &&
  4712. positionScreen.z >= -1 && positionScreen.z <= 1;
  4713. };
  4714. var handleVertex = function ( x, y, z ) {
  4715. _vertex = getNextVertexInPool();
  4716. _vertex.position.set( x, y, z );
  4717. projectVertex( _vertex );
  4718. };
  4719. var checkTriangleVisibility = function ( v1, v2, v3 ) {
  4720. _points3[ 0 ] = v1.positionScreen;
  4721. _points3[ 1 ] = v2.positionScreen;
  4722. _points3[ 2 ] = v3.positionScreen;
  4723. if ( v1.visible === true || v2.visible === true || v3.visible === true ||
  4724. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) ) ) {
  4725. return ( ( v3.positionScreen.x - v1.positionScreen.x ) *
  4726. ( v2.positionScreen.y - v1.positionScreen.y ) -
  4727. ( v3.positionScreen.y - v1.positionScreen.y ) *
  4728. ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  4729. }
  4730. return false;
  4731. };
  4732. var handleLine = function ( a, b ) {
  4733. _line = getNextLineInPool();
  4734. _line.id = object.id;
  4735. _line.v1.copy( _vertexPool[ a ] );
  4736. _line.v2.copy( _vertexPool[ b ] );
  4737. _line.material = object.material;
  4738. _renderData.elements.push( _line );
  4739. };
  4740. var handleTriangle = function ( a, b, c ) {
  4741. var v1 = _vertexPool[ a ];
  4742. var v2 = _vertexPool[ b ];
  4743. var v3 = _vertexPool[ c ];
  4744. if ( checkTriangleVisibility( v1, v2, v3 ) === true ) {
  4745. _face = getNextFace3InPool();
  4746. _face.id = object.id;
  4747. _face.v1.copy( v1 );
  4748. _face.v2.copy( v2 );
  4749. _face.v3.copy( v3 );
  4750. _face.material = object.material;
  4751. _renderData.elements.push( _face );
  4752. }
  4753. };
  4754. return {
  4755. setObject: setObject,
  4756. projectVertex: projectVertex,
  4757. checkTriangleVisibility: checkTriangleVisibility,
  4758. handleVertex: handleVertex,
  4759. handleLine: handleLine,
  4760. handleTriangle: handleTriangle
  4761. }
  4762. };
  4763. var renderState = new RenderState();
  4764. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  4765. var object, geometry, vertices, faces, face, faceVertexNormals, faceVertexUvs, uvs,
  4766. isFaceMaterial, objectMaterials;
  4767. _face3Count = 0;
  4768. _lineCount = 0;
  4769. _spriteCount = 0;
  4770. _renderData.elements.length = 0;
  4771. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  4772. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  4773. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  4774. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  4775. _normalViewMatrix.getNormalMatrix( _viewMatrix );
  4776. _frustum.setFromMatrix( _viewProjectionMatrix );
  4777. projectGraph( scene, sortObjects );
  4778. for ( var o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  4779. object = _renderData.objects[ o ].object;
  4780. geometry = object.geometry;
  4781. renderState.setObject( object );
  4782. _modelMatrix = object.matrixWorld;
  4783. _vertexCount = 0;
  4784. if ( object instanceof THREE.Mesh ) {
  4785. if ( geometry instanceof THREE.BufferGeometry ) {
  4786. var attributes = geometry.attributes;
  4787. if ( attributes.position !== undefined ) {
  4788. var positions = attributes.position.array;
  4789. for ( var i = 0, l = positions.length; i < l; i += 3 ) {
  4790. renderState.handleVertex( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  4791. }
  4792. if ( attributes.index !== undefined ) {
  4793. var indices = attributes.index.array;
  4794. for ( var i = 0, l = indices.length; i < l; i += 3 ) {
  4795. renderState.handleTriangle( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  4796. }
  4797. } else {
  4798. for ( var i = 0, l = positions.length / 3; i < l; i += 3 ) {
  4799. renderState.handleTriangle( i, i + 1, i + 2 );
  4800. }
  4801. }
  4802. }
  4803. } else if ( geometry instanceof THREE.Geometry ) {
  4804. vertices = geometry.vertices;
  4805. faces = geometry.faces;
  4806. faceVertexUvs = geometry.faceVertexUvs;
  4807. _normalMatrix.getNormalMatrix( _modelMatrix );
  4808. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4809. objectMaterials = isFaceMaterial === true ? object.material : null;
  4810. for ( var v = 0, vl = vertices.length; v < vl; v ++ ) {
  4811. var vertex = vertices[ v ];
  4812. renderState.handleVertex( vertex.x, vertex.y, vertex.z );
  4813. }
  4814. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  4815. face = faces[ f ];
  4816. var material = isFaceMaterial === true
  4817. ? objectMaterials.materials[ face.materialIndex ]
  4818. : object.material;
  4819. if ( material === undefined ) continue;
  4820. var side = material.side;
  4821. var v1 = _vertexPool[ face.a ];
  4822. var v2 = _vertexPool[ face.b ];
  4823. var v3 = _vertexPool[ face.c ];
  4824. if ( material.morphTargets === true ) {
  4825. var morphTargets = geometry.morphTargets;
  4826. var morphInfluences = object.morphTargetInfluences;
  4827. var v1p = v1.position;
  4828. var v2p = v2.position;
  4829. var v3p = v3.position;
  4830. _vA.set( 0, 0, 0 );
  4831. _vB.set( 0, 0, 0 );
  4832. _vC.set( 0, 0, 0 );
  4833. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  4834. var influence = morphInfluences[ t ];
  4835. if ( influence === 0 ) continue;
  4836. var targets = morphTargets[ t ].vertices;
  4837. _vA.x += ( targets[ face.a ].x - v1p.x ) * influence;
  4838. _vA.y += ( targets[ face.a ].y - v1p.y ) * influence;
  4839. _vA.z += ( targets[ face.a ].z - v1p.z ) * influence;
  4840. _vB.x += ( targets[ face.b ].x - v2p.x ) * influence;
  4841. _vB.y += ( targets[ face.b ].y - v2p.y ) * influence;
  4842. _vB.z += ( targets[ face.b ].z - v2p.z ) * influence;
  4843. _vC.x += ( targets[ face.c ].x - v3p.x ) * influence;
  4844. _vC.y += ( targets[ face.c ].y - v3p.y ) * influence;
  4845. _vC.z += ( targets[ face.c ].z - v3p.z ) * influence;
  4846. }
  4847. v1.position.add( _vA );
  4848. v2.position.add( _vB );
  4849. v3.position.add( _vC );
  4850. renderState.projectVertex( v1 );
  4851. renderState.projectVertex( v2 );
  4852. renderState.projectVertex( v3 );
  4853. }
  4854. var visible = renderState.checkTriangleVisibility( v1, v2, v3 );
  4855. if ( visible === ( side === THREE.BackSide ) ) continue;
  4856. _face = getNextFace3InPool();
  4857. _face.id = object.id;
  4858. _face.v1.copy( v1 );
  4859. _face.v2.copy( v2 );
  4860. _face.v3.copy( v3 );
  4861. _face.normalModel.copy( face.normal );
  4862. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4863. _face.normalModel.negate();
  4864. }
  4865. _face.normalModel.applyMatrix3( _normalMatrix ).normalize();
  4866. _face.normalModelView.copy( _face.normalModel ).applyMatrix3( _normalViewMatrix );
  4867. _face.centroidModel.copy( face.centroid ).applyMatrix4( _modelMatrix );
  4868. faceVertexNormals = face.vertexNormals;
  4869. for ( var n = 0, nl = Math.min( faceVertexNormals.length, 3 ); n < nl; n ++ ) {
  4870. var normalModel = _face.vertexNormalsModel[ n ];
  4871. normalModel.copy( faceVertexNormals[ n ] );
  4872. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4873. normalModel.negate();
  4874. }
  4875. normalModel.applyMatrix3( _normalMatrix ).normalize();
  4876. var normalModelView = _face.vertexNormalsModelView[ n ];
  4877. normalModelView.copy( normalModel ).applyMatrix3( _normalViewMatrix );
  4878. }
  4879. _face.vertexNormalsLength = faceVertexNormals.length;
  4880. for ( var c = 0, cl = Math.min( faceVertexUvs.length, 3 ); c < cl; c ++ ) {
  4881. uvs = faceVertexUvs[ c ][ f ];
  4882. if ( uvs === undefined ) continue;
  4883. for ( var u = 0, ul = uvs.length; u < ul; u ++ ) {
  4884. _face.uvs[ c ][ u ] = uvs[ u ];
  4885. }
  4886. }
  4887. _face.color = face.color;
  4888. _face.material = material;
  4889. _centroid.copy( _face.centroidModel ).applyProjection( _viewProjectionMatrix );
  4890. _face.z = _centroid.z;
  4891. _renderData.elements.push( _face );
  4892. }
  4893. }
  4894. } else if ( object instanceof THREE.Line ) {
  4895. if ( geometry instanceof THREE.BufferGeometry ) {
  4896. var attributes = geometry.attributes;
  4897. if ( attributes.position !== undefined ) {
  4898. var positions = attributes.position.array;
  4899. for ( var i = 0, l = positions.length; i < l; i += 3 ) {
  4900. renderState.handleVertex( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  4901. }
  4902. if ( attributes.index !== undefined ) {
  4903. var indices = attributes.index.array;
  4904. for ( var i = 0, l = indices.length; i < l; i += 2 ) {
  4905. renderState.handleLine( indices[ i ], indices[ i + 1 ] );
  4906. }
  4907. } else {
  4908. for ( var i = 0, l = ( positions.length / 3 ) - 1; i < l; i ++ ) {
  4909. renderState.handleLine( i, i + 1 );
  4910. }
  4911. }
  4912. }
  4913. } else if ( geometry instanceof THREE.Geometry ) {
  4914. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  4915. vertices = object.geometry.vertices;
  4916. v1 = getNextVertexInPool();
  4917. v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
  4918. // Handle LineStrip and LinePieces
  4919. var step = object.type === THREE.LinePieces ? 2 : 1;
  4920. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  4921. v1 = getNextVertexInPool();
  4922. v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
  4923. if ( ( v + 1 ) % step > 0 ) continue;
  4924. v2 = _vertexPool[ _vertexCount - 2 ];
  4925. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  4926. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  4927. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  4928. // Perform the perspective divide
  4929. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  4930. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  4931. _line = getNextLineInPool();
  4932. _line.id = object.id;
  4933. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  4934. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  4935. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  4936. _line.material = object.material;
  4937. if ( object.material.vertexColors === THREE.VertexColors ) {
  4938. _line.vertexColors[ 0 ].copy( object.geometry.colors[ v ] );
  4939. _line.vertexColors[ 1 ].copy( object.geometry.colors[ v - 1 ] );
  4940. }
  4941. _renderData.elements.push( _line );
  4942. }
  4943. }
  4944. }
  4945. }
  4946. }
  4947. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  4948. object = _renderData.sprites[ o ].object;
  4949. _modelMatrix = object.matrixWorld;
  4950. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  4951. _vector4.applyMatrix4( _viewProjectionMatrix );
  4952. var invW = 1 / _vector4.w;
  4953. _vector4.z *= invW;
  4954. if ( _vector4.z >= -1 && _vector4.z <= 1 ) {
  4955. _sprite = getNextSpriteInPool();
  4956. _sprite.id = object.id;
  4957. _sprite.x = _vector4.x * invW;
  4958. _sprite.y = _vector4.y * invW;
  4959. _sprite.z = _vector4.z;
  4960. _sprite.object = object;
  4961. _sprite.rotation = object.rotation;
  4962. _sprite.scale.x = object.scale.x * Math.abs( _sprite.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  4963. _sprite.scale.y = object.scale.y * Math.abs( _sprite.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  4964. _sprite.material = object.material;
  4965. _renderData.elements.push( _sprite );
  4966. }
  4967. }
  4968. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  4969. return _renderData;
  4970. };
  4971. // Pools
  4972. function getNextObjectInPool() {
  4973. if ( _objectCount === _objectPoolLength ) {
  4974. var object = new THREE.RenderableObject();
  4975. _objectPool.push( object );
  4976. _objectPoolLength ++;
  4977. _objectCount ++;
  4978. return object;
  4979. }
  4980. return _objectPool[ _objectCount ++ ];
  4981. }
  4982. function getNextVertexInPool() {
  4983. if ( _vertexCount === _vertexPoolLength ) {
  4984. var vertex = new THREE.RenderableVertex();
  4985. _vertexPool.push( vertex );
  4986. _vertexPoolLength ++;
  4987. _vertexCount ++;
  4988. return vertex;
  4989. }
  4990. return _vertexPool[ _vertexCount ++ ];
  4991. }
  4992. function getNextFace3InPool() {
  4993. if ( _face3Count === _face3PoolLength ) {
  4994. var face = new THREE.RenderableFace3();
  4995. _face3Pool.push( face );
  4996. _face3PoolLength ++;
  4997. _face3Count ++;
  4998. return face;
  4999. }
  5000. return _face3Pool[ _face3Count ++ ];
  5001. }
  5002. function getNextLineInPool() {
  5003. if ( _lineCount === _linePoolLength ) {
  5004. var line = new THREE.RenderableLine();
  5005. _linePool.push( line );
  5006. _linePoolLength ++;
  5007. _lineCount ++
  5008. return line;
  5009. }
  5010. return _linePool[ _lineCount ++ ];
  5011. }
  5012. function getNextSpriteInPool() {
  5013. if ( _spriteCount === _spritePoolLength ) {
  5014. var sprite = new THREE.RenderableSprite();
  5015. _spritePool.push( sprite );
  5016. _spritePoolLength ++;
  5017. _spriteCount ++
  5018. return sprite;
  5019. }
  5020. return _spritePool[ _spriteCount ++ ];
  5021. }
  5022. //
  5023. function painterSort( a, b ) {
  5024. if ( a.z !== b.z ) {
  5025. return b.z - a.z;
  5026. } else if ( a.id !== b.id ) {
  5027. return a.id - b.id;
  5028. } else {
  5029. return 0;
  5030. }
  5031. }
  5032. function clipLine( s1, s2 ) {
  5033. var alpha1 = 0, alpha2 = 1,
  5034. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  5035. // Z = -1 and Z = +1, respectively.
  5036. bc1near = s1.z + s1.w,
  5037. bc2near = s2.z + s2.w,
  5038. bc1far = - s1.z + s1.w,
  5039. bc2far = - s2.z + s2.w;
  5040. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  5041. // Both vertices lie entirely within all clip planes.
  5042. return true;
  5043. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  5044. // Both vertices lie entirely outside one of the clip planes.
  5045. return false;
  5046. } else {
  5047. // The line segment spans at least one clip plane.
  5048. if ( bc1near < 0 ) {
  5049. // v1 lies outside the near plane, v2 inside
  5050. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  5051. } else if ( bc2near < 0 ) {
  5052. // v2 lies outside the near plane, v1 inside
  5053. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  5054. }
  5055. if ( bc1far < 0 ) {
  5056. // v1 lies outside the far plane, v2 inside
  5057. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  5058. } else if ( bc2far < 0 ) {
  5059. // v2 lies outside the far plane, v2 inside
  5060. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  5061. }
  5062. if ( alpha2 < alpha1 ) {
  5063. // The line segment spans two boundaries, but is outside both of them.
  5064. // (This can't happen when we're only clipping against just near/far but good
  5065. // to leave the check here for future usage if other clip planes are added.)
  5066. return false;
  5067. } else {
  5068. // Update the s1 and s2 vertices to match the clipped line segment.
  5069. s1.lerp( s2, alpha1 );
  5070. s2.lerp( s1, 1 - alpha2 );
  5071. return true;
  5072. }
  5073. }
  5074. }
  5075. };
  5076. /**
  5077. * @author mrdoob / http://mrdoob.com/
  5078. * @author alteredq / http://alteredqualia.com/
  5079. */
  5080. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  5081. this.a = a;
  5082. this.b = b;
  5083. this.c = c;
  5084. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  5085. this.vertexNormals = normal instanceof Array ? normal : [ ];
  5086. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  5087. this.vertexColors = color instanceof Array ? color : [];
  5088. this.vertexTangents = [];
  5089. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  5090. this.centroid = new THREE.Vector3();
  5091. };
  5092. THREE.Face3.prototype = {
  5093. constructor: THREE.Face3,
  5094. clone: function () {
  5095. var face = new THREE.Face3( this.a, this.b, this.c );
  5096. face.normal.copy( this.normal );
  5097. face.color.copy( this.color );
  5098. face.centroid.copy( this.centroid );
  5099. face.materialIndex = this.materialIndex;
  5100. var i, il;
  5101. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  5102. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  5103. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  5104. return face;
  5105. }
  5106. };
  5107. /**
  5108. * @author mrdoob / http://mrdoob.com/
  5109. */
  5110. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  5111. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.')
  5112. return new THREE.Face3( a, b, c, normal, color, materialIndex );
  5113. };
  5114. /**
  5115. * @author mrdoob / http://mrdoob.com/
  5116. * @author kile / http://kile.stravaganza.org/
  5117. * @author alteredq / http://alteredqualia.com/
  5118. * @author mikael emtinger / http://gomo.se/
  5119. * @author zz85 / http://www.lab4games.net/zz85/blog
  5120. * @author bhouston / http://exocortex.com
  5121. */
  5122. THREE.Geometry = function () {
  5123. this.id = THREE.GeometryIdCount ++;
  5124. this.uuid = THREE.Math.generateUUID();
  5125. this.name = '';
  5126. this.vertices = [];
  5127. this.colors = []; // one-to-one vertex colors, used in ParticleSystem and Line
  5128. this.faces = [];
  5129. this.faceVertexUvs = [[]];
  5130. this.morphTargets = [];
  5131. this.morphColors = [];
  5132. this.morphNormals = [];
  5133. this.skinWeights = [];
  5134. this.skinIndices = [];
  5135. this.lineDistances = [];
  5136. this.boundingBox = null;
  5137. this.boundingSphere = null;
  5138. this.hasTangents = false;
  5139. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  5140. // update flags
  5141. this.verticesNeedUpdate = false;
  5142. this.elementsNeedUpdate = false;
  5143. this.uvsNeedUpdate = false;
  5144. this.normalsNeedUpdate = false;
  5145. this.tangentsNeedUpdate = false;
  5146. this.colorsNeedUpdate = false;
  5147. this.lineDistancesNeedUpdate = false;
  5148. this.buffersNeedUpdate = false;
  5149. };
  5150. THREE.Geometry.prototype = {
  5151. constructor: THREE.Geometry,
  5152. applyMatrix: function ( matrix ) {
  5153. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5154. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  5155. var vertex = this.vertices[ i ];
  5156. vertex.applyMatrix4( matrix );
  5157. }
  5158. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  5159. var face = this.faces[ i ];
  5160. face.normal.applyMatrix3( normalMatrix ).normalize();
  5161. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  5162. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  5163. }
  5164. face.centroid.applyMatrix4( matrix );
  5165. }
  5166. if ( this.boundingBox instanceof THREE.Box3 ) {
  5167. this.computeBoundingBox();
  5168. }
  5169. if ( this.boundingSphere instanceof THREE.Sphere ) {
  5170. this.computeBoundingSphere();
  5171. }
  5172. },
  5173. computeCentroids: function () {
  5174. var f, fl, face;
  5175. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5176. face = this.faces[ f ];
  5177. face.centroid.set( 0, 0, 0 );
  5178. face.centroid.add( this.vertices[ face.a ] );
  5179. face.centroid.add( this.vertices[ face.b ] );
  5180. face.centroid.add( this.vertices[ face.c ] );
  5181. face.centroid.divideScalar( 3 );
  5182. }
  5183. },
  5184. computeFaceNormals: function () {
  5185. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5186. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5187. var face = this.faces[ f ];
  5188. var vA = this.vertices[ face.a ];
  5189. var vB = this.vertices[ face.b ];
  5190. var vC = this.vertices[ face.c ];
  5191. cb.subVectors( vC, vB );
  5192. ab.subVectors( vA, vB );
  5193. cb.cross( ab );
  5194. cb.normalize();
  5195. face.normal.copy( cb );
  5196. }
  5197. },
  5198. computeVertexNormals: function ( areaWeighted ) {
  5199. var v, vl, f, fl, face, vertices;
  5200. vertices = new Array( this.vertices.length );
  5201. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5202. vertices[ v ] = new THREE.Vector3();
  5203. }
  5204. if ( areaWeighted ) {
  5205. // vertex normals weighted by triangle areas
  5206. // http://www.iquilezles.org/www/articles/normals/normals.htm
  5207. var vA, vB, vC, vD;
  5208. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  5209. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  5210. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5211. face = this.faces[ f ];
  5212. vA = this.vertices[ face.a ];
  5213. vB = this.vertices[ face.b ];
  5214. vC = this.vertices[ face.c ];
  5215. cb.subVectors( vC, vB );
  5216. ab.subVectors( vA, vB );
  5217. cb.cross( ab );
  5218. vertices[ face.a ].add( cb );
  5219. vertices[ face.b ].add( cb );
  5220. vertices[ face.c ].add( cb );
  5221. }
  5222. } else {
  5223. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5224. face = this.faces[ f ];
  5225. vertices[ face.a ].add( face.normal );
  5226. vertices[ face.b ].add( face.normal );
  5227. vertices[ face.c ].add( face.normal );
  5228. }
  5229. }
  5230. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5231. vertices[ v ].normalize();
  5232. }
  5233. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5234. face = this.faces[ f ];
  5235. face.vertexNormals[ 0 ] = vertices[ face.a ].clone();
  5236. face.vertexNormals[ 1 ] = vertices[ face.b ].clone();
  5237. face.vertexNormals[ 2 ] = vertices[ face.c ].clone();
  5238. }
  5239. },
  5240. computeMorphNormals: function () {
  5241. var i, il, f, fl, face;
  5242. // save original normals
  5243. // - create temp variables on first access
  5244. // otherwise just copy (for faster repeated calls)
  5245. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5246. face = this.faces[ f ];
  5247. if ( ! face.__originalFaceNormal ) {
  5248. face.__originalFaceNormal = face.normal.clone();
  5249. } else {
  5250. face.__originalFaceNormal.copy( face.normal );
  5251. }
  5252. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  5253. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  5254. if ( ! face.__originalVertexNormals[ i ] ) {
  5255. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  5256. } else {
  5257. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  5258. }
  5259. }
  5260. }
  5261. // use temp geometry to compute face and vertex normals for each morph
  5262. var tmpGeo = new THREE.Geometry();
  5263. tmpGeo.faces = this.faces;
  5264. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  5265. // create on first access
  5266. if ( ! this.morphNormals[ i ] ) {
  5267. this.morphNormals[ i ] = {};
  5268. this.morphNormals[ i ].faceNormals = [];
  5269. this.morphNormals[ i ].vertexNormals = [];
  5270. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  5271. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  5272. var faceNormal, vertexNormals;
  5273. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5274. face = this.faces[ f ];
  5275. faceNormal = new THREE.Vector3();
  5276. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  5277. dstNormalsFace.push( faceNormal );
  5278. dstNormalsVertex.push( vertexNormals );
  5279. }
  5280. }
  5281. var morphNormals = this.morphNormals[ i ];
  5282. // set vertices to morph target
  5283. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  5284. // compute morph normals
  5285. tmpGeo.computeFaceNormals();
  5286. tmpGeo.computeVertexNormals();
  5287. // store morph normals
  5288. var faceNormal, vertexNormals;
  5289. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5290. face = this.faces[ f ];
  5291. faceNormal = morphNormals.faceNormals[ f ];
  5292. vertexNormals = morphNormals.vertexNormals[ f ];
  5293. faceNormal.copy( face.normal );
  5294. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  5295. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  5296. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  5297. }
  5298. }
  5299. // restore original normals
  5300. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5301. face = this.faces[ f ];
  5302. face.normal = face.__originalFaceNormal;
  5303. face.vertexNormals = face.__originalVertexNormals;
  5304. }
  5305. },
  5306. computeTangents: function () {
  5307. // based on http://www.terathon.com/code/tangent.html
  5308. // tangents go to vertices
  5309. var f, fl, v, vl, i, il, vertexIndex,
  5310. face, uv, vA, vB, vC, uvA, uvB, uvC,
  5311. x1, x2, y1, y2, z1, z2,
  5312. s1, s2, t1, t2, r, t, test,
  5313. tan1 = [], tan2 = [],
  5314. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  5315. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  5316. n = new THREE.Vector3(), w;
  5317. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5318. tan1[ v ] = new THREE.Vector3();
  5319. tan2[ v ] = new THREE.Vector3();
  5320. }
  5321. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  5322. vA = context.vertices[ a ];
  5323. vB = context.vertices[ b ];
  5324. vC = context.vertices[ c ];
  5325. uvA = uv[ ua ];
  5326. uvB = uv[ ub ];
  5327. uvC = uv[ uc ];
  5328. x1 = vB.x - vA.x;
  5329. x2 = vC.x - vA.x;
  5330. y1 = vB.y - vA.y;
  5331. y2 = vC.y - vA.y;
  5332. z1 = vB.z - vA.z;
  5333. z2 = vC.z - vA.z;
  5334. s1 = uvB.x - uvA.x;
  5335. s2 = uvC.x - uvA.x;
  5336. t1 = uvB.y - uvA.y;
  5337. t2 = uvC.y - uvA.y;
  5338. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5339. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  5340. ( t2 * y1 - t1 * y2 ) * r,
  5341. ( t2 * z1 - t1 * z2 ) * r );
  5342. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  5343. ( s1 * y2 - s2 * y1 ) * r,
  5344. ( s1 * z2 - s2 * z1 ) * r );
  5345. tan1[ a ].add( sdir );
  5346. tan1[ b ].add( sdir );
  5347. tan1[ c ].add( sdir );
  5348. tan2[ a ].add( tdir );
  5349. tan2[ b ].add( tdir );
  5350. tan2[ c ].add( tdir );
  5351. }
  5352. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5353. face = this.faces[ f ];
  5354. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  5355. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  5356. }
  5357. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  5358. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5359. face = this.faces[ f ];
  5360. for ( i = 0; i < Math.min( face.vertexNormals.length, 3 ); i++ ) {
  5361. n.copy( face.vertexNormals[ i ] );
  5362. vertexIndex = face[ faceIndex[ i ] ];
  5363. t = tan1[ vertexIndex ];
  5364. // Gram-Schmidt orthogonalize
  5365. tmp.copy( t );
  5366. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5367. // Calculate handedness
  5368. tmp2.crossVectors( face.vertexNormals[ i ], t );
  5369. test = tmp2.dot( tan2[ vertexIndex ] );
  5370. w = (test < 0.0) ? -1.0 : 1.0;
  5371. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  5372. }
  5373. }
  5374. this.hasTangents = true;
  5375. },
  5376. computeLineDistances: function ( ) {
  5377. var d = 0;
  5378. var vertices = this.vertices;
  5379. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5380. if ( i > 0 ) {
  5381. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  5382. }
  5383. this.lineDistances[ i ] = d;
  5384. }
  5385. },
  5386. computeBoundingBox: function () {
  5387. if ( this.boundingBox === null ) {
  5388. this.boundingBox = new THREE.Box3();
  5389. }
  5390. this.boundingBox.setFromPoints( this.vertices );
  5391. },
  5392. computeBoundingSphere: function () {
  5393. if ( this.boundingSphere === null ) {
  5394. this.boundingSphere = new THREE.Sphere();
  5395. }
  5396. this.boundingSphere.setFromPoints( this.vertices );
  5397. },
  5398. /*
  5399. * Checks for duplicate vertices with hashmap.
  5400. * Duplicated vertices are removed
  5401. * and faces' vertices are updated.
  5402. */
  5403. mergeVertices: function () {
  5404. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  5405. var unique = [], changes = [];
  5406. var v, key;
  5407. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  5408. var precision = Math.pow( 10, precisionPoints );
  5409. var i,il, face;
  5410. var indices, k, j, jl, u;
  5411. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  5412. v = this.vertices[ i ];
  5413. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  5414. if ( verticesMap[ key ] === undefined ) {
  5415. verticesMap[ key ] = i;
  5416. unique.push( this.vertices[ i ] );
  5417. changes[ i ] = unique.length - 1;
  5418. } else {
  5419. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  5420. changes[ i ] = changes[ verticesMap[ key ] ];
  5421. }
  5422. };
  5423. // if faces are completely degenerate after merging vertices, we
  5424. // have to remove them from the geometry.
  5425. var faceIndicesToRemove = [];
  5426. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  5427. face = this.faces[ i ];
  5428. face.a = changes[ face.a ];
  5429. face.b = changes[ face.b ];
  5430. face.c = changes[ face.c ];
  5431. indices = [ face.a, face.b, face.c ];
  5432. var dupIndex = -1;
  5433. // if any duplicate vertices are found in a Face3
  5434. // we have to remove the face as nothing can be saved
  5435. for ( var n = 0; n < 3; n ++ ) {
  5436. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  5437. dupIndex = n;
  5438. faceIndicesToRemove.push( i );
  5439. break;
  5440. }
  5441. }
  5442. }
  5443. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  5444. var idx = faceIndicesToRemove[ i ];
  5445. this.faces.splice( idx, 1 );
  5446. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  5447. this.faceVertexUvs[ j ].splice( idx, 1 );
  5448. }
  5449. }
  5450. // Use unique set of vertices
  5451. var diff = this.vertices.length - unique.length;
  5452. this.vertices = unique;
  5453. return diff;
  5454. },
  5455. clone: function () {
  5456. var geometry = new THREE.Geometry();
  5457. var vertices = this.vertices;
  5458. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5459. geometry.vertices.push( vertices[ i ].clone() );
  5460. }
  5461. var faces = this.faces;
  5462. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  5463. geometry.faces.push( faces[ i ].clone() );
  5464. }
  5465. var uvs = this.faceVertexUvs[ 0 ];
  5466. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  5467. var uv = uvs[ i ], uvCopy = [];
  5468. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  5469. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  5470. }
  5471. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  5472. }
  5473. return geometry;
  5474. },
  5475. dispose: function () {
  5476. this.dispatchEvent( { type: 'dispose' } );
  5477. }
  5478. };
  5479. THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype );
  5480. THREE.GeometryIdCount = 0;
  5481. /**
  5482. * @author alteredq / http://alteredqualia.com/
  5483. */
  5484. THREE.BufferGeometry = function () {
  5485. this.id = THREE.GeometryIdCount ++;
  5486. this.uuid = THREE.Math.generateUUID();
  5487. this.name = '';
  5488. // attributes
  5489. this.attributes = {};
  5490. // attributes typed arrays are kept only if dynamic flag is set
  5491. this.dynamic = true;
  5492. // offsets for chunks when using indexed elements
  5493. this.offsets = [];
  5494. // boundings
  5495. this.boundingBox = null;
  5496. this.boundingSphere = null;
  5497. this.hasTangents = false;
  5498. // for compatibility
  5499. this.morphTargets = [];
  5500. };
  5501. THREE.BufferGeometry.prototype = {
  5502. constructor: THREE.BufferGeometry,
  5503. addAttribute: function ( name, type, numItems, itemSize ) {
  5504. this.attributes[ name ] = {
  5505. itemSize: itemSize,
  5506. array: new type( numItems * itemSize )
  5507. };
  5508. },
  5509. applyMatrix: function ( matrix ) {
  5510. var positionArray;
  5511. var normalArray;
  5512. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  5513. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  5514. if ( positionArray !== undefined ) {
  5515. matrix.multiplyVector3Array( positionArray );
  5516. this.verticesNeedUpdate = true;
  5517. }
  5518. if ( normalArray !== undefined ) {
  5519. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5520. normalMatrix.multiplyVector3Array( normalArray );
  5521. this.normalizeNormals();
  5522. this.normalsNeedUpdate = true;
  5523. }
  5524. },
  5525. computeBoundingBox: function () {
  5526. if ( this.boundingBox === null ) {
  5527. this.boundingBox = new THREE.Box3();
  5528. }
  5529. var positions = this.attributes[ "position" ].array;
  5530. if ( positions ) {
  5531. var bb = this.boundingBox;
  5532. var x, y, z;
  5533. if( positions.length >= 3 ) {
  5534. bb.min.x = bb.max.x = positions[ 0 ];
  5535. bb.min.y = bb.max.y = positions[ 1 ];
  5536. bb.min.z = bb.max.z = positions[ 2 ];
  5537. }
  5538. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  5539. x = positions[ i ];
  5540. y = positions[ i + 1 ];
  5541. z = positions[ i + 2 ];
  5542. // bounding box
  5543. if ( x < bb.min.x ) {
  5544. bb.min.x = x;
  5545. } else if ( x > bb.max.x ) {
  5546. bb.max.x = x;
  5547. }
  5548. if ( y < bb.min.y ) {
  5549. bb.min.y = y;
  5550. } else if ( y > bb.max.y ) {
  5551. bb.max.y = y;
  5552. }
  5553. if ( z < bb.min.z ) {
  5554. bb.min.z = z;
  5555. } else if ( z > bb.max.z ) {
  5556. bb.max.z = z;
  5557. }
  5558. }
  5559. }
  5560. if ( positions === undefined || positions.length === 0 ) {
  5561. this.boundingBox.min.set( 0, 0, 0 );
  5562. this.boundingBox.max.set( 0, 0, 0 );
  5563. }
  5564. },
  5565. computeBoundingSphere: function () {
  5566. var box = new THREE.Box3();
  5567. var vector = new THREE.Vector3();
  5568. return function () {
  5569. if ( this.boundingSphere === null ) {
  5570. this.boundingSphere = new THREE.Sphere();
  5571. }
  5572. var positions = this.attributes[ "position" ].array;
  5573. if ( positions ) {
  5574. box.makeEmpty();
  5575. var center = this.boundingSphere.center;
  5576. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5577. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5578. box.addPoint( vector );
  5579. }
  5580. box.center( center );
  5581. var maxRadiusSq = 0;
  5582. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5583. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5584. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  5585. }
  5586. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5587. }
  5588. }
  5589. }(),
  5590. computeVertexNormals: function () {
  5591. if ( this.attributes[ "position" ] ) {
  5592. var i, il;
  5593. var j, jl;
  5594. var nVertexElements = this.attributes[ "position" ].array.length;
  5595. if ( this.attributes[ "normal" ] === undefined ) {
  5596. this.attributes[ "normal" ] = {
  5597. itemSize: 3,
  5598. array: new Float32Array( nVertexElements )
  5599. };
  5600. } else {
  5601. // reset existing normals to zero
  5602. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  5603. this.attributes[ "normal" ].array[ i ] = 0;
  5604. }
  5605. }
  5606. var positions = this.attributes[ "position" ].array;
  5607. var normals = this.attributes[ "normal" ].array;
  5608. var vA, vB, vC, x, y, z,
  5609. pA = new THREE.Vector3(),
  5610. pB = new THREE.Vector3(),
  5611. pC = new THREE.Vector3(),
  5612. cb = new THREE.Vector3(),
  5613. ab = new THREE.Vector3();
  5614. // indexed elements
  5615. if ( this.attributes[ "index" ] ) {
  5616. var indices = this.attributes[ "index" ].array;
  5617. var offsets = this.offsets;
  5618. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5619. var start = offsets[ j ].start;
  5620. var count = offsets[ j ].count;
  5621. var index = offsets[ j ].index;
  5622. for ( i = start, il = start + count; i < il; i += 3 ) {
  5623. vA = index + indices[ i ];
  5624. vB = index + indices[ i + 1 ];
  5625. vC = index + indices[ i + 2 ];
  5626. x = positions[ vA * 3 ];
  5627. y = positions[ vA * 3 + 1 ];
  5628. z = positions[ vA * 3 + 2 ];
  5629. pA.set( x, y, z );
  5630. x = positions[ vB * 3 ];
  5631. y = positions[ vB * 3 + 1 ];
  5632. z = positions[ vB * 3 + 2 ];
  5633. pB.set( x, y, z );
  5634. x = positions[ vC * 3 ];
  5635. y = positions[ vC * 3 + 1 ];
  5636. z = positions[ vC * 3 + 2 ];
  5637. pC.set( x, y, z );
  5638. cb.subVectors( pC, pB );
  5639. ab.subVectors( pA, pB );
  5640. cb.cross( ab );
  5641. normals[ vA * 3 ] += cb.x;
  5642. normals[ vA * 3 + 1 ] += cb.y;
  5643. normals[ vA * 3 + 2 ] += cb.z;
  5644. normals[ vB * 3 ] += cb.x;
  5645. normals[ vB * 3 + 1 ] += cb.y;
  5646. normals[ vB * 3 + 2 ] += cb.z;
  5647. normals[ vC * 3 ] += cb.x;
  5648. normals[ vC * 3 + 1 ] += cb.y;
  5649. normals[ vC * 3 + 2 ] += cb.z;
  5650. }
  5651. }
  5652. // non-indexed elements (unconnected triangle soup)
  5653. } else {
  5654. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  5655. x = positions[ i ];
  5656. y = positions[ i + 1 ];
  5657. z = positions[ i + 2 ];
  5658. pA.set( x, y, z );
  5659. x = positions[ i + 3 ];
  5660. y = positions[ i + 4 ];
  5661. z = positions[ i + 5 ];
  5662. pB.set( x, y, z );
  5663. x = positions[ i + 6 ];
  5664. y = positions[ i + 7 ];
  5665. z = positions[ i + 8 ];
  5666. pC.set( x, y, z );
  5667. cb.subVectors( pC, pB );
  5668. ab.subVectors( pA, pB );
  5669. cb.cross( ab );
  5670. normals[ i ] = cb.x;
  5671. normals[ i + 1 ] = cb.y;
  5672. normals[ i + 2 ] = cb.z;
  5673. normals[ i + 3 ] = cb.x;
  5674. normals[ i + 4 ] = cb.y;
  5675. normals[ i + 5 ] = cb.z;
  5676. normals[ i + 6 ] = cb.x;
  5677. normals[ i + 7 ] = cb.y;
  5678. normals[ i + 8 ] = cb.z;
  5679. }
  5680. }
  5681. this.normalizeNormals();
  5682. this.normalsNeedUpdate = true;
  5683. }
  5684. },
  5685. normalizeNormals: function () {
  5686. var normals = this.attributes[ "normal" ].array;
  5687. var x, y, z, n;
  5688. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5689. x = normals[ i ];
  5690. y = normals[ i + 1 ];
  5691. z = normals[ i + 2 ];
  5692. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5693. normals[ i ] *= n;
  5694. normals[ i + 1 ] *= n;
  5695. normals[ i + 2 ] *= n;
  5696. }
  5697. },
  5698. computeTangents: function () {
  5699. // based on http://www.terathon.com/code/tangent.html
  5700. // (per vertex tangents)
  5701. if ( this.attributes[ "index" ] === undefined ||
  5702. this.attributes[ "position" ] === undefined ||
  5703. this.attributes[ "normal" ] === undefined ||
  5704. this.attributes[ "uv" ] === undefined ) {
  5705. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  5706. return;
  5707. }
  5708. var indices = this.attributes[ "index" ].array;
  5709. var positions = this.attributes[ "position" ].array;
  5710. var normals = this.attributes[ "normal" ].array;
  5711. var uvs = this.attributes[ "uv" ].array;
  5712. var nVertices = positions.length / 3;
  5713. if ( this.attributes[ "tangent" ] === undefined ) {
  5714. var nTangentElements = 4 * nVertices;
  5715. this.attributes[ "tangent" ] = {
  5716. itemSize: 4,
  5717. array: new Float32Array( nTangentElements )
  5718. };
  5719. }
  5720. var tangents = this.attributes[ "tangent" ].array;
  5721. var tan1 = [], tan2 = [];
  5722. for ( var k = 0; k < nVertices; k ++ ) {
  5723. tan1[ k ] = new THREE.Vector3();
  5724. tan2[ k ] = new THREE.Vector3();
  5725. }
  5726. var xA, yA, zA,
  5727. xB, yB, zB,
  5728. xC, yC, zC,
  5729. uA, vA,
  5730. uB, vB,
  5731. uC, vC,
  5732. x1, x2, y1, y2, z1, z2,
  5733. s1, s2, t1, t2, r;
  5734. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5735. function handleTriangle( a, b, c ) {
  5736. xA = positions[ a * 3 ];
  5737. yA = positions[ a * 3 + 1 ];
  5738. zA = positions[ a * 3 + 2 ];
  5739. xB = positions[ b * 3 ];
  5740. yB = positions[ b * 3 + 1 ];
  5741. zB = positions[ b * 3 + 2 ];
  5742. xC = positions[ c * 3 ];
  5743. yC = positions[ c * 3 + 1 ];
  5744. zC = positions[ c * 3 + 2 ];
  5745. uA = uvs[ a * 2 ];
  5746. vA = uvs[ a * 2 + 1 ];
  5747. uB = uvs[ b * 2 ];
  5748. vB = uvs[ b * 2 + 1 ];
  5749. uC = uvs[ c * 2 ];
  5750. vC = uvs[ c * 2 + 1 ];
  5751. x1 = xB - xA;
  5752. x2 = xC - xA;
  5753. y1 = yB - yA;
  5754. y2 = yC - yA;
  5755. z1 = zB - zA;
  5756. z2 = zC - zA;
  5757. s1 = uB - uA;
  5758. s2 = uC - uA;
  5759. t1 = vB - vA;
  5760. t2 = vC - vA;
  5761. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5762. sdir.set(
  5763. ( t2 * x1 - t1 * x2 ) * r,
  5764. ( t2 * y1 - t1 * y2 ) * r,
  5765. ( t2 * z1 - t1 * z2 ) * r
  5766. );
  5767. tdir.set(
  5768. ( s1 * x2 - s2 * x1 ) * r,
  5769. ( s1 * y2 - s2 * y1 ) * r,
  5770. ( s1 * z2 - s2 * z1 ) * r
  5771. );
  5772. tan1[ a ].add( sdir );
  5773. tan1[ b ].add( sdir );
  5774. tan1[ c ].add( sdir );
  5775. tan2[ a ].add( tdir );
  5776. tan2[ b ].add( tdir );
  5777. tan2[ c ].add( tdir );
  5778. }
  5779. var i, il;
  5780. var j, jl;
  5781. var iA, iB, iC;
  5782. var offsets = this.offsets;
  5783. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5784. var start = offsets[ j ].start;
  5785. var count = offsets[ j ].count;
  5786. var index = offsets[ j ].index;
  5787. for ( i = start, il = start + count; i < il; i += 3 ) {
  5788. iA = index + indices[ i ];
  5789. iB = index + indices[ i + 1 ];
  5790. iC = index + indices[ i + 2 ];
  5791. handleTriangle( iA, iB, iC );
  5792. }
  5793. }
  5794. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5795. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5796. var w, t, test;
  5797. function handleVertex( v ) {
  5798. n.x = normals[ v * 3 ];
  5799. n.y = normals[ v * 3 + 1 ];
  5800. n.z = normals[ v * 3 + 2 ];
  5801. n2.copy( n );
  5802. t = tan1[ v ];
  5803. // Gram-Schmidt orthogonalize
  5804. tmp.copy( t );
  5805. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5806. // Calculate handedness
  5807. tmp2.crossVectors( n2, t );
  5808. test = tmp2.dot( tan2[ v ] );
  5809. w = ( test < 0.0 ) ? -1.0 : 1.0;
  5810. tangents[ v * 4 ] = tmp.x;
  5811. tangents[ v * 4 + 1 ] = tmp.y;
  5812. tangents[ v * 4 + 2 ] = tmp.z;
  5813. tangents[ v * 4 + 3 ] = w;
  5814. }
  5815. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5816. var start = offsets[ j ].start;
  5817. var count = offsets[ j ].count;
  5818. var index = offsets[ j ].index;
  5819. for ( i = start, il = start + count; i < il; i += 3 ) {
  5820. iA = index + indices[ i ];
  5821. iB = index + indices[ i + 1 ];
  5822. iC = index + indices[ i + 2 ];
  5823. handleVertex( iA );
  5824. handleVertex( iB );
  5825. handleVertex( iC );
  5826. }
  5827. }
  5828. this.hasTangents = true;
  5829. this.tangentsNeedUpdate = true;
  5830. },
  5831. clone: function () {
  5832. var geometry = new THREE.BufferGeometry();
  5833. var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];
  5834. for ( var attr in this.attributes ) {
  5835. var sourceAttr = this.attributes[ attr ];
  5836. var sourceArray = sourceAttr.array;
  5837. var attribute = {
  5838. itemSize: sourceAttr.itemSize,
  5839. array: null
  5840. };
  5841. for ( var i = 0, il = types.length; i < il; i ++ ) {
  5842. var type = types[ i ];
  5843. if ( sourceArray instanceof type ) {
  5844. attribute.array = new type( sourceArray );
  5845. break;
  5846. }
  5847. }
  5848. geometry.attributes[ attr ] = attribute;
  5849. }
  5850. for ( var i = 0, il = this.offsets.length; i < il; i ++ ) {
  5851. var offset = this.offsets[ i ];
  5852. geometry.offsets.push( {
  5853. start: offset.start,
  5854. index: offset.index,
  5855. count: offset.count
  5856. } );
  5857. }
  5858. return geometry;
  5859. },
  5860. dispose: function () {
  5861. this.dispatchEvent( { type: 'dispose' } );
  5862. }
  5863. };
  5864. THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype );
  5865. /**
  5866. * @author mrdoob / http://mrdoob.com/
  5867. * @author mikael emtinger / http://gomo.se/
  5868. * @author WestLangley / http://github.com/WestLangley
  5869. */
  5870. THREE.Camera = function () {
  5871. THREE.Object3D.call( this );
  5872. this.matrixWorldInverse = new THREE.Matrix4();
  5873. this.projectionMatrix = new THREE.Matrix4();
  5874. };
  5875. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  5876. THREE.Camera.prototype.lookAt = function () {
  5877. // This routine does not support cameras with rotated and/or translated parent(s)
  5878. var m1 = new THREE.Matrix4();
  5879. return function ( vector ) {
  5880. m1.lookAt( this.position, vector, this.up );
  5881. this.quaternion.setFromRotationMatrix( m1 );
  5882. };
  5883. }();
  5884. THREE.Camera.prototype.clone = function (camera) {
  5885. if ( camera === undefined ) camera = new THREE.Camera();
  5886. THREE.Object3D.prototype.clone.call( this, camera );
  5887. camera.matrixWorldInverse.copy( this.matrixWorldInverse );
  5888. camera.projectionMatrix.copy( this.projectionMatrix );
  5889. return camera;
  5890. };
  5891. /**
  5892. * @author alteredq / http://alteredqualia.com/
  5893. */
  5894. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  5895. THREE.Camera.call( this );
  5896. this.left = left;
  5897. this.right = right;
  5898. this.top = top;
  5899. this.bottom = bottom;
  5900. this.near = ( near !== undefined ) ? near : 0.1;
  5901. this.far = ( far !== undefined ) ? far : 2000;
  5902. this.updateProjectionMatrix();
  5903. };
  5904. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  5905. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  5906. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  5907. };
  5908. THREE.OrthographicCamera.prototype.clone = function () {
  5909. var camera = new THREE.OrthographicCamera();
  5910. THREE.Camera.prototype.clone.call( this, camera );
  5911. camera.left = this.left;
  5912. camera.right = this.right;
  5913. camera.top = this.top;
  5914. camera.bottom = this.bottom;
  5915. camera.near = this.near;
  5916. camera.far = this.far;
  5917. return camera;
  5918. };
  5919. /**
  5920. * @author mrdoob / http://mrdoob.com/
  5921. * @author greggman / http://games.greggman.com/
  5922. * @author zz85 / http://www.lab4games.net/zz85/blog
  5923. */
  5924. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  5925. THREE.Camera.call( this );
  5926. this.fov = fov !== undefined ? fov : 50;
  5927. this.aspect = aspect !== undefined ? aspect : 1;
  5928. this.near = near !== undefined ? near : 0.1;
  5929. this.far = far !== undefined ? far : 2000;
  5930. this.updateProjectionMatrix();
  5931. };
  5932. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  5933. /**
  5934. * Uses Focal Length (in mm) to estimate and set FOV
  5935. * 35mm (fullframe) camera is used if frame size is not specified;
  5936. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  5937. */
  5938. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  5939. if ( frameHeight === undefined ) frameHeight = 24;
  5940. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  5941. this.updateProjectionMatrix();
  5942. }
  5943. /**
  5944. * Sets an offset in a larger frustum. This is useful for multi-window or
  5945. * multi-monitor/multi-machine setups.
  5946. *
  5947. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  5948. * the monitors are in grid like this
  5949. *
  5950. * +---+---+---+
  5951. * | A | B | C |
  5952. * +---+---+---+
  5953. * | D | E | F |
  5954. * +---+---+---+
  5955. *
  5956. * then for each monitor you would call it like this
  5957. *
  5958. * var w = 1920;
  5959. * var h = 1080;
  5960. * var fullWidth = w * 3;
  5961. * var fullHeight = h * 2;
  5962. *
  5963. * --A--
  5964. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  5965. * --B--
  5966. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  5967. * --C--
  5968. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  5969. * --D--
  5970. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  5971. * --E--
  5972. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  5973. * --F--
  5974. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  5975. *
  5976. * Note there is no reason monitors have to be the same size or in a grid.
  5977. */
  5978. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  5979. this.fullWidth = fullWidth;
  5980. this.fullHeight = fullHeight;
  5981. this.x = x;
  5982. this.y = y;
  5983. this.width = width;
  5984. this.height = height;
  5985. this.updateProjectionMatrix();
  5986. };
  5987. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  5988. if ( this.fullWidth ) {
  5989. var aspect = this.fullWidth / this.fullHeight;
  5990. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  5991. var bottom = -top;
  5992. var left = aspect * bottom;
  5993. var right = aspect * top;
  5994. var width = Math.abs( right - left );
  5995. var height = Math.abs( top - bottom );
  5996. this.projectionMatrix.makeFrustum(
  5997. left + this.x * width / this.fullWidth,
  5998. left + ( this.x + this.width ) * width / this.fullWidth,
  5999. top - ( this.y + this.height ) * height / this.fullHeight,
  6000. top - this.y * height / this.fullHeight,
  6001. this.near,
  6002. this.far
  6003. );
  6004. } else {
  6005. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  6006. }
  6007. };
  6008. THREE.PerspectiveCamera.prototype.clone = function () {
  6009. var camera = new THREE.PerspectiveCamera();
  6010. THREE.Camera.prototype.clone.call( this, camera );
  6011. camera.fov = this.fov;
  6012. camera.aspect = this.aspect;
  6013. camera.near = this.near;
  6014. camera.far = this.far;
  6015. return camera;
  6016. };
  6017. /**
  6018. * @author mrdoob / http://mrdoob.com/
  6019. * @author alteredq / http://alteredqualia.com/
  6020. */
  6021. THREE.Light = function ( color ) {
  6022. THREE.Object3D.call( this );
  6023. this.color = new THREE.Color( color );
  6024. };
  6025. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  6026. THREE.Light.prototype.clone = function ( light ) {
  6027. if ( light === undefined ) light = new THREE.Light();
  6028. THREE.Object3D.prototype.clone.call( this, light );
  6029. light.color.copy( this.color );
  6030. return light;
  6031. };
  6032. /**
  6033. * @author mrdoob / http://mrdoob.com/
  6034. */
  6035. THREE.AmbientLight = function ( color ) {
  6036. THREE.Light.call( this, color );
  6037. };
  6038. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  6039. THREE.AmbientLight.prototype.clone = function () {
  6040. var light = new THREE.AmbientLight();
  6041. THREE.Light.prototype.clone.call( this, light );
  6042. return light;
  6043. };
  6044. /**
  6045. * @author MPanknin / http://www.redplant.de/
  6046. * @author alteredq / http://alteredqualia.com/
  6047. */
  6048. THREE.AreaLight = function ( color, intensity ) {
  6049. THREE.Light.call( this, color );
  6050. this.normal = new THREE.Vector3( 0, -1, 0 );
  6051. this.right = new THREE.Vector3( 1, 0, 0 );
  6052. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6053. this.width = 1.0;
  6054. this.height = 1.0;
  6055. this.constantAttenuation = 1.5;
  6056. this.linearAttenuation = 0.5;
  6057. this.quadraticAttenuation = 0.1;
  6058. };
  6059. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  6060. /**
  6061. * @author mrdoob / http://mrdoob.com/
  6062. * @author alteredq / http://alteredqualia.com/
  6063. */
  6064. THREE.DirectionalLight = function ( color, intensity ) {
  6065. THREE.Light.call( this, color );
  6066. this.position.set( 0, 1, 0 );
  6067. this.target = new THREE.Object3D();
  6068. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6069. this.castShadow = false;
  6070. this.onlyShadow = false;
  6071. //
  6072. this.shadowCameraNear = 50;
  6073. this.shadowCameraFar = 5000;
  6074. this.shadowCameraLeft = -500;
  6075. this.shadowCameraRight = 500;
  6076. this.shadowCameraTop = 500;
  6077. this.shadowCameraBottom = -500;
  6078. this.shadowCameraVisible = false;
  6079. this.shadowBias = 0;
  6080. this.shadowDarkness = 0.5;
  6081. this.shadowMapWidth = 512;
  6082. this.shadowMapHeight = 512;
  6083. //
  6084. this.shadowCascade = false;
  6085. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  6086. this.shadowCascadeCount = 2;
  6087. this.shadowCascadeBias = [ 0, 0, 0 ];
  6088. this.shadowCascadeWidth = [ 512, 512, 512 ];
  6089. this.shadowCascadeHeight = [ 512, 512, 512 ];
  6090. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  6091. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  6092. this.shadowCascadeArray = [];
  6093. //
  6094. this.shadowMap = null;
  6095. this.shadowMapSize = null;
  6096. this.shadowCamera = null;
  6097. this.shadowMatrix = null;
  6098. };
  6099. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  6100. THREE.DirectionalLight.prototype.clone = function () {
  6101. var light = new THREE.DirectionalLight();
  6102. THREE.Light.prototype.clone.call( this, light );
  6103. light.target = this.target.clone();
  6104. light.intensity = this.intensity;
  6105. light.castShadow = this.castShadow;
  6106. light.onlyShadow = this.onlyShadow;
  6107. return light;
  6108. };
  6109. /**
  6110. * @author alteredq / http://alteredqualia.com/
  6111. */
  6112. THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) {
  6113. THREE.Light.call( this, skyColor );
  6114. this.position.set( 0, 100, 0 );
  6115. this.groundColor = new THREE.Color( groundColor );
  6116. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6117. };
  6118. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  6119. THREE.HemisphereLight.prototype.clone = function () {
  6120. var light = new THREE.HemisphereLight();
  6121. THREE.Light.prototype.clone.call( this, light );
  6122. light.groundColor.copy( this.groundColor );
  6123. light.intensity = this.intensity;
  6124. return light;
  6125. };
  6126. /**
  6127. * @author mrdoob / http://mrdoob.com/
  6128. */
  6129. THREE.PointLight = function ( color, intensity, distance ) {
  6130. THREE.Light.call( this, color );
  6131. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6132. this.distance = ( distance !== undefined ) ? distance : 0;
  6133. };
  6134. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  6135. THREE.PointLight.prototype.clone = function () {
  6136. var light = new THREE.PointLight();
  6137. THREE.Light.prototype.clone.call( this, light );
  6138. light.intensity = this.intensity;
  6139. light.distance = this.distance;
  6140. return light;
  6141. };
  6142. /**
  6143. * @author alteredq / http://alteredqualia.com/
  6144. */
  6145. THREE.SpotLight = function ( color, intensity, distance, angle, exponent ) {
  6146. THREE.Light.call( this, color );
  6147. this.position.set( 0, 1, 0 );
  6148. this.target = new THREE.Object3D();
  6149. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6150. this.distance = ( distance !== undefined ) ? distance : 0;
  6151. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  6152. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  6153. this.castShadow = false;
  6154. this.onlyShadow = false;
  6155. //
  6156. this.shadowCameraNear = 50;
  6157. this.shadowCameraFar = 5000;
  6158. this.shadowCameraFov = 50;
  6159. this.shadowCameraVisible = false;
  6160. this.shadowBias = 0;
  6161. this.shadowDarkness = 0.5;
  6162. this.shadowMapWidth = 512;
  6163. this.shadowMapHeight = 512;
  6164. //
  6165. this.shadowMap = null;
  6166. this.shadowMapSize = null;
  6167. this.shadowCamera = null;
  6168. this.shadowMatrix = null;
  6169. };
  6170. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  6171. THREE.SpotLight.prototype.clone = function () {
  6172. var light = new THREE.SpotLight();
  6173. THREE.Light.prototype.clone.call( this, light );
  6174. light.target = this.target.clone();
  6175. light.intensity = this.intensity;
  6176. light.distance = this.distance;
  6177. light.angle = this.angle;
  6178. light.exponent = this.exponent;
  6179. light.castShadow = this.castShadow;
  6180. light.onlyShadow = this.onlyShadow;
  6181. return light;
  6182. };
  6183. /**
  6184. * @author alteredq / http://alteredqualia.com/
  6185. */
  6186. THREE.Loader = function ( showStatus ) {
  6187. this.showStatus = showStatus;
  6188. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  6189. this.onLoadStart = function () {};
  6190. this.onLoadProgress = function () {};
  6191. this.onLoadComplete = function () {};
  6192. };
  6193. THREE.Loader.prototype = {
  6194. constructor: THREE.Loader,
  6195. crossOrigin: undefined,
  6196. addStatusElement: function () {
  6197. var e = document.createElement( "div" );
  6198. e.style.position = "absolute";
  6199. e.style.right = "0px";
  6200. e.style.top = "0px";
  6201. e.style.fontSize = "0.8em";
  6202. e.style.textAlign = "left";
  6203. e.style.background = "rgba(0,0,0,0.25)";
  6204. e.style.color = "#fff";
  6205. e.style.width = "120px";
  6206. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  6207. e.style.zIndex = 1000;
  6208. e.innerHTML = "Loading ...";
  6209. return e;
  6210. },
  6211. updateProgress: function ( progress ) {
  6212. var message = "Loaded ";
  6213. if ( progress.total ) {
  6214. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  6215. } else {
  6216. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  6217. }
  6218. this.statusDomElement.innerHTML = message;
  6219. },
  6220. extractUrlBase: function ( url ) {
  6221. var parts = url.split( '/' );
  6222. parts.pop();
  6223. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  6224. },
  6225. initMaterials: function ( materials, texturePath ) {
  6226. var array = [];
  6227. for ( var i = 0; i < materials.length; ++ i ) {
  6228. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  6229. }
  6230. return array;
  6231. },
  6232. needsTangents: function ( materials ) {
  6233. for( var i = 0, il = materials.length; i < il; i ++ ) {
  6234. var m = materials[ i ];
  6235. if ( m instanceof THREE.ShaderMaterial ) return true;
  6236. }
  6237. return false;
  6238. },
  6239. createMaterial: function ( m, texturePath ) {
  6240. var _this = this;
  6241. function is_pow2( n ) {
  6242. var l = Math.log( n ) / Math.LN2;
  6243. return Math.floor( l ) == l;
  6244. }
  6245. function nearest_pow2( n ) {
  6246. var l = Math.log( n ) / Math.LN2;
  6247. return Math.pow( 2, Math.round( l ) );
  6248. }
  6249. function load_image( where, url ) {
  6250. var image = new Image();
  6251. image.onload = function () {
  6252. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  6253. var width = nearest_pow2( this.width );
  6254. var height = nearest_pow2( this.height );
  6255. where.image.width = width;
  6256. where.image.height = height;
  6257. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  6258. } else {
  6259. where.image = this;
  6260. }
  6261. where.needsUpdate = true;
  6262. };
  6263. if ( _this.crossOrigin !== undefined ) image.crossOrigin = _this.crossOrigin;
  6264. image.src = url;
  6265. }
  6266. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  6267. var isCompressed = /\.dds$/i.test( sourceFile );
  6268. var fullPath = texturePath + "/" + sourceFile;
  6269. if ( isCompressed ) {
  6270. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  6271. where[ name ] = texture;
  6272. } else {
  6273. var texture = document.createElement( 'canvas' );
  6274. where[ name ] = new THREE.Texture( texture );
  6275. }
  6276. where[ name ].sourceFile = sourceFile;
  6277. if( repeat ) {
  6278. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  6279. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  6280. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  6281. }
  6282. if ( offset ) {
  6283. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  6284. }
  6285. if ( wrap ) {
  6286. var wrapMap = {
  6287. "repeat": THREE.RepeatWrapping,
  6288. "mirror": THREE.MirroredRepeatWrapping
  6289. }
  6290. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  6291. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  6292. }
  6293. if ( anisotropy ) {
  6294. where[ name ].anisotropy = anisotropy;
  6295. }
  6296. if ( ! isCompressed ) {
  6297. load_image( where[ name ], fullPath );
  6298. }
  6299. }
  6300. function rgb2hex( rgb ) {
  6301. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  6302. }
  6303. // defaults
  6304. var mtype = "MeshLambertMaterial";
  6305. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  6306. // parameters from model file
  6307. if ( m.shading ) {
  6308. var shading = m.shading.toLowerCase();
  6309. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  6310. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  6311. }
  6312. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  6313. mpars.blending = THREE[ m.blending ];
  6314. }
  6315. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  6316. mpars.transparent = m.transparent;
  6317. }
  6318. if ( m.depthTest !== undefined ) {
  6319. mpars.depthTest = m.depthTest;
  6320. }
  6321. if ( m.depthWrite !== undefined ) {
  6322. mpars.depthWrite = m.depthWrite;
  6323. }
  6324. if ( m.visible !== undefined ) {
  6325. mpars.visible = m.visible;
  6326. }
  6327. if ( m.flipSided !== undefined ) {
  6328. mpars.side = THREE.BackSide;
  6329. }
  6330. if ( m.doubleSided !== undefined ) {
  6331. mpars.side = THREE.DoubleSide;
  6332. }
  6333. if ( m.wireframe !== undefined ) {
  6334. mpars.wireframe = m.wireframe;
  6335. }
  6336. if ( m.vertexColors !== undefined ) {
  6337. if ( m.vertexColors === "face" ) {
  6338. mpars.vertexColors = THREE.FaceColors;
  6339. } else if ( m.vertexColors ) {
  6340. mpars.vertexColors = THREE.VertexColors;
  6341. }
  6342. }
  6343. // colors
  6344. if ( m.colorDiffuse ) {
  6345. mpars.color = rgb2hex( m.colorDiffuse );
  6346. } else if ( m.DbgColor ) {
  6347. mpars.color = m.DbgColor;
  6348. }
  6349. if ( m.colorSpecular ) {
  6350. mpars.specular = rgb2hex( m.colorSpecular );
  6351. }
  6352. if ( m.colorAmbient ) {
  6353. mpars.ambient = rgb2hex( m.colorAmbient );
  6354. }
  6355. // modifiers
  6356. if ( m.transparency ) {
  6357. mpars.opacity = m.transparency;
  6358. }
  6359. if ( m.specularCoef ) {
  6360. mpars.shininess = m.specularCoef;
  6361. }
  6362. // textures
  6363. if ( m.mapDiffuse && texturePath ) {
  6364. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  6365. }
  6366. if ( m.mapLight && texturePath ) {
  6367. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  6368. }
  6369. if ( m.mapBump && texturePath ) {
  6370. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  6371. }
  6372. if ( m.mapNormal && texturePath ) {
  6373. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  6374. }
  6375. if ( m.mapSpecular && texturePath ) {
  6376. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  6377. }
  6378. //
  6379. if ( m.mapBumpScale ) {
  6380. mpars.bumpScale = m.mapBumpScale;
  6381. }
  6382. // special case for normal mapped material
  6383. if ( m.mapNormal ) {
  6384. var shader = THREE.ShaderLib[ "normalmap" ];
  6385. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6386. uniforms[ "tNormal" ].value = mpars.normalMap;
  6387. if ( m.mapNormalFactor ) {
  6388. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  6389. }
  6390. if ( mpars.map ) {
  6391. uniforms[ "tDiffuse" ].value = mpars.map;
  6392. uniforms[ "enableDiffuse" ].value = true;
  6393. }
  6394. if ( mpars.specularMap ) {
  6395. uniforms[ "tSpecular" ].value = mpars.specularMap;
  6396. uniforms[ "enableSpecular" ].value = true;
  6397. }
  6398. if ( mpars.lightMap ) {
  6399. uniforms[ "tAO" ].value = mpars.lightMap;
  6400. uniforms[ "enableAO" ].value = true;
  6401. }
  6402. // for the moment don't handle displacement texture
  6403. uniforms[ "diffuse" ].value.setHex( mpars.color );
  6404. uniforms[ "specular" ].value.setHex( mpars.specular );
  6405. uniforms[ "ambient" ].value.setHex( mpars.ambient );
  6406. uniforms[ "shininess" ].value = mpars.shininess;
  6407. if ( mpars.opacity !== undefined ) {
  6408. uniforms[ "opacity" ].value = mpars.opacity;
  6409. }
  6410. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6411. var material = new THREE.ShaderMaterial( parameters );
  6412. if ( mpars.transparent ) {
  6413. material.transparent = true;
  6414. }
  6415. } else {
  6416. var material = new THREE[ mtype ]( mpars );
  6417. }
  6418. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  6419. return material;
  6420. }
  6421. };
  6422. /**
  6423. * @author mrdoob / http://mrdoob.com/
  6424. */
  6425. THREE.XHRLoader = function ( manager ) {
  6426. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6427. };
  6428. THREE.XHRLoader.prototype = {
  6429. constructor: THREE.XHRLoader,
  6430. load: function ( url, onLoad, onProgress, onError ) {
  6431. var scope = this;
  6432. var request = new XMLHttpRequest();
  6433. if ( onLoad !== undefined ) {
  6434. request.addEventListener( 'load', function ( event ) {
  6435. onLoad( event.target.responseText );
  6436. scope.manager.itemEnd( url );
  6437. }, false );
  6438. }
  6439. if ( onProgress !== undefined ) {
  6440. request.addEventListener( 'progress', function ( event ) {
  6441. onProgress( event );
  6442. }, false );
  6443. }
  6444. if ( onError !== undefined ) {
  6445. request.addEventListener( 'error', function ( event ) {
  6446. onError( event );
  6447. }, false );
  6448. }
  6449. if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
  6450. request.open( 'GET', url, true );
  6451. request.send( null );
  6452. scope.manager.itemStart( url );
  6453. },
  6454. setCrossOrigin: function ( value ) {
  6455. this.crossOrigin = value;
  6456. }
  6457. };
  6458. /**
  6459. * @author mrdoob / http://mrdoob.com/
  6460. */
  6461. THREE.ImageLoader = function ( manager ) {
  6462. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6463. };
  6464. THREE.ImageLoader.prototype = {
  6465. constructor: THREE.ImageLoader,
  6466. load: function ( url, onLoad, onProgress, onError ) {
  6467. var scope = this;
  6468. var image = document.createElement( 'img' );
  6469. if ( onLoad !== undefined ) {
  6470. image.addEventListener( 'load', function ( event ) {
  6471. scope.manager.itemEnd( url );
  6472. onLoad( this );
  6473. }, false );
  6474. }
  6475. if ( onProgress !== undefined ) {
  6476. image.addEventListener( 'progress', function ( event ) {
  6477. onProgress( event );
  6478. }, false );
  6479. }
  6480. if ( onError !== undefined ) {
  6481. image.addEventListener( 'error', function ( event ) {
  6482. onError( event );
  6483. }, false );
  6484. }
  6485. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  6486. image.src = url;
  6487. scope.manager.itemStart( url );
  6488. return image;
  6489. },
  6490. setCrossOrigin: function ( value ) {
  6491. this.crossOrigin = value;
  6492. }
  6493. }
  6494. /**
  6495. * @author mrdoob / http://mrdoob.com/
  6496. * @author alteredq / http://alteredqualia.com/
  6497. */
  6498. THREE.JSONLoader = function ( showStatus ) {
  6499. THREE.Loader.call( this, showStatus );
  6500. this.withCredentials = false;
  6501. };
  6502. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  6503. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  6504. var scope = this;
  6505. // todo: unify load API to for easier SceneLoader use
  6506. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  6507. this.onLoadStart();
  6508. this.loadAjaxJSON( this, url, callback, texturePath );
  6509. };
  6510. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  6511. var xhr = new XMLHttpRequest();
  6512. var length = 0;
  6513. xhr.onreadystatechange = function () {
  6514. if ( xhr.readyState === xhr.DONE ) {
  6515. if ( xhr.status === 200 || xhr.status === 0 ) {
  6516. if ( xhr.responseText ) {
  6517. var json = JSON.parse( xhr.responseText );
  6518. var result = context.parse( json, texturePath );
  6519. callback( result.geometry, result.materials );
  6520. } else {
  6521. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  6522. }
  6523. // in context of more complex asset initialization
  6524. // do not block on single failed file
  6525. // maybe should go even one more level up
  6526. context.onLoadComplete();
  6527. } else {
  6528. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  6529. }
  6530. } else if ( xhr.readyState === xhr.LOADING ) {
  6531. if ( callbackProgress ) {
  6532. if ( length === 0 ) {
  6533. length = xhr.getResponseHeader( "Content-Length" );
  6534. }
  6535. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  6536. }
  6537. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  6538. if ( callbackProgress !== undefined ) {
  6539. length = xhr.getResponseHeader( "Content-Length" );
  6540. }
  6541. }
  6542. };
  6543. xhr.open( "GET", url, true );
  6544. xhr.withCredentials = this.withCredentials;
  6545. xhr.send( null );
  6546. };
  6547. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  6548. var scope = this,
  6549. geometry = new THREE.Geometry(),
  6550. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  6551. parseModel( scale );
  6552. parseSkin();
  6553. parseMorphing( scale );
  6554. geometry.computeCentroids();
  6555. geometry.computeFaceNormals();
  6556. geometry.computeBoundingSphere();
  6557. function parseModel( scale ) {
  6558. function isBitSet( value, position ) {
  6559. return value & ( 1 << position );
  6560. }
  6561. var i, j, fi,
  6562. offset, zLength,
  6563. colorIndex, normalIndex, uvIndex, materialIndex,
  6564. type,
  6565. isQuad,
  6566. hasMaterial,
  6567. hasFaceVertexUv,
  6568. hasFaceNormal, hasFaceVertexNormal,
  6569. hasFaceColor, hasFaceVertexColor,
  6570. vertex, face, faceA, faceB, color, hex, normal,
  6571. uvLayer, uv, u, v,
  6572. faces = json.faces,
  6573. vertices = json.vertices,
  6574. normals = json.normals,
  6575. colors = json.colors,
  6576. nUvLayers = 0;
  6577. if ( json.uvs !== undefined ) {
  6578. // disregard empty arrays
  6579. for ( i = 0; i < json.uvs.length; i++ ) {
  6580. if ( json.uvs[ i ].length ) nUvLayers ++;
  6581. }
  6582. for ( i = 0; i < nUvLayers; i++ ) {
  6583. geometry.faceVertexUvs[ i ] = [];
  6584. }
  6585. }
  6586. offset = 0;
  6587. zLength = vertices.length;
  6588. while ( offset < zLength ) {
  6589. vertex = new THREE.Vector3();
  6590. vertex.x = vertices[ offset ++ ] * scale;
  6591. vertex.y = vertices[ offset ++ ] * scale;
  6592. vertex.z = vertices[ offset ++ ] * scale;
  6593. geometry.vertices.push( vertex );
  6594. }
  6595. offset = 0;
  6596. zLength = faces.length;
  6597. while ( offset < zLength ) {
  6598. type = faces[ offset ++ ];
  6599. isQuad = isBitSet( type, 0 );
  6600. hasMaterial = isBitSet( type, 1 );
  6601. hasFaceVertexUv = isBitSet( type, 3 );
  6602. hasFaceNormal = isBitSet( type, 4 );
  6603. hasFaceVertexNormal = isBitSet( type, 5 );
  6604. hasFaceColor = isBitSet( type, 6 );
  6605. hasFaceVertexColor = isBitSet( type, 7 );
  6606. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  6607. if ( isQuad ) {
  6608. faceA = new THREE.Face3();
  6609. faceA.a = faces[ offset ];
  6610. faceA.b = faces[ offset + 1 ];
  6611. faceA.c = faces[ offset + 3 ];
  6612. faceB = new THREE.Face3();
  6613. faceB.a = faces[ offset + 1 ];
  6614. faceB.b = faces[ offset + 2 ];
  6615. faceB.c = faces[ offset + 3 ];
  6616. offset += 4;
  6617. if ( hasMaterial ) {
  6618. materialIndex = faces[ offset ++ ];
  6619. faceA.materialIndex = materialIndex;
  6620. faceB.materialIndex = materialIndex;
  6621. }
  6622. // to get face <=> uv index correspondence
  6623. fi = geometry.faces.length;
  6624. if ( hasFaceVertexUv ) {
  6625. for ( i = 0; i < nUvLayers; i++ ) {
  6626. uvLayer = json.uvs[ i ];
  6627. geometry.faceVertexUvs[ i ][ fi ] = [];
  6628. geometry.faceVertexUvs[ i ][ fi + 1 ] = []
  6629. for ( j = 0; j < 4; j ++ ) {
  6630. uvIndex = faces[ offset ++ ];
  6631. u = uvLayer[ uvIndex * 2 ];
  6632. v = uvLayer[ uvIndex * 2 + 1 ];
  6633. uv = new THREE.Vector2( u, v );
  6634. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  6635. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  6636. }
  6637. }
  6638. }
  6639. if ( hasFaceNormal ) {
  6640. normalIndex = faces[ offset ++ ] * 3;
  6641. faceA.normal.set(
  6642. normals[ normalIndex ++ ],
  6643. normals[ normalIndex ++ ],
  6644. normals[ normalIndex ]
  6645. );
  6646. faceB.normal.copy( faceA.normal );
  6647. }
  6648. if ( hasFaceVertexNormal ) {
  6649. for ( i = 0; i < 4; i++ ) {
  6650. normalIndex = faces[ offset ++ ] * 3;
  6651. normal = new THREE.Vector3(
  6652. normals[ normalIndex ++ ],
  6653. normals[ normalIndex ++ ],
  6654. normals[ normalIndex ]
  6655. );
  6656. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  6657. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  6658. }
  6659. }
  6660. if ( hasFaceColor ) {
  6661. colorIndex = faces[ offset ++ ];
  6662. hex = colors[ colorIndex ];
  6663. faceA.color.setHex( hex );
  6664. faceB.color.setHex( hex );
  6665. }
  6666. if ( hasFaceVertexColor ) {
  6667. for ( i = 0; i < 4; i++ ) {
  6668. colorIndex = faces[ offset ++ ];
  6669. hex = colors[ colorIndex ];
  6670. if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) );
  6671. if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) );
  6672. }
  6673. }
  6674. geometry.faces.push( faceA );
  6675. geometry.faces.push( faceB );
  6676. } else {
  6677. face = new THREE.Face3();
  6678. face.a = faces[ offset ++ ];
  6679. face.b = faces[ offset ++ ];
  6680. face.c = faces[ offset ++ ];
  6681. if ( hasMaterial ) {
  6682. materialIndex = faces[ offset ++ ];
  6683. face.materialIndex = materialIndex;
  6684. }
  6685. // to get face <=> uv index correspondence
  6686. fi = geometry.faces.length;
  6687. if ( hasFaceVertexUv ) {
  6688. for ( i = 0; i < nUvLayers; i++ ) {
  6689. uvLayer = json.uvs[ i ];
  6690. geometry.faceVertexUvs[ i ][ fi ] = [];
  6691. for ( j = 0; j < 3; j ++ ) {
  6692. uvIndex = faces[ offset ++ ];
  6693. u = uvLayer[ uvIndex * 2 ];
  6694. v = uvLayer[ uvIndex * 2 + 1 ];
  6695. uv = new THREE.Vector2( u, v );
  6696. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  6697. }
  6698. }
  6699. }
  6700. if ( hasFaceNormal ) {
  6701. normalIndex = faces[ offset ++ ] * 3;
  6702. face.normal.set(
  6703. normals[ normalIndex ++ ],
  6704. normals[ normalIndex ++ ],
  6705. normals[ normalIndex ]
  6706. );
  6707. }
  6708. if ( hasFaceVertexNormal ) {
  6709. for ( i = 0; i < 3; i++ ) {
  6710. normalIndex = faces[ offset ++ ] * 3;
  6711. normal = new THREE.Vector3(
  6712. normals[ normalIndex ++ ],
  6713. normals[ normalIndex ++ ],
  6714. normals[ normalIndex ]
  6715. );
  6716. face.vertexNormals.push( normal );
  6717. }
  6718. }
  6719. if ( hasFaceColor ) {
  6720. colorIndex = faces[ offset ++ ];
  6721. face.color.setHex( colors[ colorIndex ] );
  6722. }
  6723. if ( hasFaceVertexColor ) {
  6724. for ( i = 0; i < 3; i++ ) {
  6725. colorIndex = faces[ offset ++ ];
  6726. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  6727. }
  6728. }
  6729. geometry.faces.push( face );
  6730. }
  6731. }
  6732. };
  6733. function parseSkin() {
  6734. var i, l, x, y, z, w, a, b, c, d;
  6735. if ( json.skinWeights ) {
  6736. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  6737. x = json.skinWeights[ i ];
  6738. y = json.skinWeights[ i + 1 ];
  6739. z = 0;
  6740. w = 0;
  6741. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  6742. }
  6743. }
  6744. if ( json.skinIndices ) {
  6745. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  6746. a = json.skinIndices[ i ];
  6747. b = json.skinIndices[ i + 1 ];
  6748. c = 0;
  6749. d = 0;
  6750. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  6751. }
  6752. }
  6753. geometry.bones = json.bones;
  6754. // could change this to json.animations[0] or remove completely
  6755. geometry.animation = json.animation;
  6756. geometry.animations = json.animations;
  6757. };
  6758. function parseMorphing( scale ) {
  6759. if ( json.morphTargets !== undefined ) {
  6760. var i, l, v, vl, dstVertices, srcVertices;
  6761. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  6762. geometry.morphTargets[ i ] = {};
  6763. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  6764. geometry.morphTargets[ i ].vertices = [];
  6765. dstVertices = geometry.morphTargets[ i ].vertices;
  6766. srcVertices = json.morphTargets [ i ].vertices;
  6767. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  6768. var vertex = new THREE.Vector3();
  6769. vertex.x = srcVertices[ v ] * scale;
  6770. vertex.y = srcVertices[ v + 1 ] * scale;
  6771. vertex.z = srcVertices[ v + 2 ] * scale;
  6772. dstVertices.push( vertex );
  6773. }
  6774. }
  6775. }
  6776. if ( json.morphColors !== undefined ) {
  6777. var i, l, c, cl, dstColors, srcColors, color;
  6778. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  6779. geometry.morphColors[ i ] = {};
  6780. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  6781. geometry.morphColors[ i ].colors = [];
  6782. dstColors = geometry.morphColors[ i ].colors;
  6783. srcColors = json.morphColors [ i ].colors;
  6784. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  6785. color = new THREE.Color( 0xffaa00 );
  6786. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  6787. dstColors.push( color );
  6788. }
  6789. }
  6790. }
  6791. };
  6792. if ( json.materials === undefined ) {
  6793. return { geometry: geometry };
  6794. } else {
  6795. var materials = this.initMaterials( json.materials, texturePath );
  6796. if ( this.needsTangents( materials ) ) {
  6797. geometry.computeTangents();
  6798. }
  6799. return { geometry: geometry, materials: materials };
  6800. }
  6801. };
  6802. /**
  6803. * @author mrdoob / http://mrdoob.com/
  6804. */
  6805. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  6806. var scope = this;
  6807. var loaded = 0, total = 0;
  6808. this.onLoad = onLoad;
  6809. this.onProgress = onProgress;
  6810. this.onError = onError;
  6811. this.itemStart = function ( url ) {
  6812. total ++;
  6813. };
  6814. this.itemEnd = function ( url ) {
  6815. loaded ++;
  6816. if ( scope.onProgress !== undefined ) {
  6817. scope.onProgress( url, loaded, total );
  6818. }
  6819. if ( loaded === total && scope.onLoad !== undefined ) {
  6820. scope.onLoad();
  6821. }
  6822. };
  6823. };
  6824. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  6825. /**
  6826. * @author mrdoob / http://mrdoob.com/
  6827. */
  6828. THREE.BufferGeometryLoader = function ( manager ) {
  6829. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6830. };
  6831. THREE.BufferGeometryLoader.prototype = {
  6832. constructor: THREE.BufferGeometryLoader,
  6833. load: function ( url, onLoad, onProgress, onError ) {
  6834. var scope = this;
  6835. var loader = new THREE.XHRLoader();
  6836. loader.setCrossOrigin( this.crossOrigin );
  6837. loader.load( url, function ( text ) {
  6838. onLoad( scope.parse( JSON.parse( text ) ) );
  6839. } );
  6840. },
  6841. setCrossOrigin: function ( value ) {
  6842. this.crossOrigin = value;
  6843. },
  6844. parse: function ( json ) {
  6845. var geometry = new THREE.BufferGeometry();
  6846. var attributes = json.attributes;
  6847. var offsets = json.offsets;
  6848. var boundingSphere = json.boundingSphere;
  6849. for ( var key in attributes ) {
  6850. var attribute = attributes[ key ];
  6851. geometry.attributes[ key ] = {
  6852. itemSize: attribute.itemSize,
  6853. array: new self[ attribute.type ]( attribute.array )
  6854. }
  6855. }
  6856. if ( offsets !== undefined ) {
  6857. geometry.offsets = JSON.parse( JSON.stringify( offsets ) );
  6858. }
  6859. if ( boundingSphere !== undefined ) {
  6860. geometry.boundingSphere = new THREE.Sphere(
  6861. new THREE.Vector3().fromArray( boundingSphere.center !== undefined ? boundingSphere.center : [ 0, 0, 0 ] ),
  6862. boundingSphere.radius
  6863. );
  6864. }
  6865. return geometry;
  6866. }
  6867. };
  6868. /**
  6869. * @author mrdoob / http://mrdoob.com/
  6870. */
  6871. THREE.GeometryLoader = function ( manager ) {
  6872. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6873. };
  6874. THREE.GeometryLoader.prototype = {
  6875. constructor: THREE.GeometryLoader,
  6876. load: function ( url, onLoad, onProgress, onError ) {
  6877. var scope = this;
  6878. var loader = new THREE.XHRLoader();
  6879. loader.setCrossOrigin( this.crossOrigin );
  6880. loader.load( url, function ( text ) {
  6881. onLoad( scope.parse( JSON.parse( text ) ) );
  6882. } );
  6883. },
  6884. setCrossOrigin: function ( value ) {
  6885. this.crossOrigin = value;
  6886. },
  6887. parse: function ( json ) {
  6888. }
  6889. };
  6890. /**
  6891. * @author mrdoob / http://mrdoob.com/
  6892. */
  6893. THREE.MaterialLoader = function ( manager ) {
  6894. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6895. };
  6896. THREE.MaterialLoader.prototype = {
  6897. constructor: THREE.MaterialLoader,
  6898. load: function ( url, onLoad, onProgress, onError ) {
  6899. var scope = this;
  6900. var loader = new THREE.XHRLoader();
  6901. loader.setCrossOrigin( this.crossOrigin );
  6902. loader.load( url, function ( text ) {
  6903. onLoad( scope.parse( JSON.parse( text ) ) );
  6904. } );
  6905. },
  6906. setCrossOrigin: function ( value ) {
  6907. this.crossOrigin = value;
  6908. },
  6909. parse: function ( json ) {
  6910. var material = new THREE[ json.type ];
  6911. if ( json.color !== undefined ) material.color.setHex( json.color );
  6912. if ( json.ambient !== undefined ) material.ambient.setHex( json.ambient );
  6913. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  6914. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  6915. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  6916. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  6917. if ( json.blending !== undefined ) material.blending = json.blending;
  6918. if ( json.side !== undefined ) material.side = json.side;
  6919. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  6920. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  6921. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  6922. if ( json.materials !== undefined ) {
  6923. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  6924. material.materials.push( this.parse( json.materials[ i ] ) );
  6925. }
  6926. }
  6927. return material;
  6928. }
  6929. };
  6930. /**
  6931. * @author mrdoob / http://mrdoob.com/
  6932. */
  6933. THREE.ObjectLoader = function ( manager ) {
  6934. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6935. };
  6936. THREE.ObjectLoader.prototype = {
  6937. constructor: THREE.ObjectLoader,
  6938. load: function ( url, onLoad, onProgress, onError ) {
  6939. var scope = this;
  6940. var loader = new THREE.XHRLoader( scope.manager );
  6941. loader.setCrossOrigin( this.crossOrigin );
  6942. loader.load( url, function ( text ) {
  6943. onLoad( scope.parse( JSON.parse( text ) ) );
  6944. } );
  6945. },
  6946. setCrossOrigin: function ( value ) {
  6947. this.crossOrigin = value;
  6948. },
  6949. parse: function ( json ) {
  6950. var geometries = this.parseGeometries( json.geometries );
  6951. var materials = this.parseMaterials( json.materials );
  6952. var object = this.parseObject( json.object, geometries, materials );
  6953. return object;
  6954. },
  6955. parseGeometries: function ( json ) {
  6956. var geometries = {};
  6957. if ( json !== undefined ) {
  6958. var geometryLoader = new THREE.JSONLoader();
  6959. var bufferGeometryLoader = new THREE.BufferGeometryLoader();
  6960. for ( var i = 0, l = json.length; i < l; i ++ ) {
  6961. var geometry;
  6962. var data = json[ i ];
  6963. switch ( data.type ) {
  6964. case 'PlaneGeometry':
  6965. geometry = new THREE.PlaneGeometry(
  6966. data.width,
  6967. data.height,
  6968. data.widthSegments,
  6969. data.heightSegments
  6970. );
  6971. break;
  6972. case 'CircleGeometry':
  6973. geometry = new THREE.CircleGeometry(
  6974. data.radius,
  6975. data.segments
  6976. );
  6977. break;
  6978. case 'CubeGeometry':
  6979. geometry = new THREE.CubeGeometry(
  6980. data.width,
  6981. data.height,
  6982. data.depth,
  6983. data.widthSegments,
  6984. data.heightSegments,
  6985. data.depthSegments
  6986. );
  6987. break;
  6988. case 'CylinderGeometry':
  6989. geometry = new THREE.CylinderGeometry(
  6990. data.radiusTop,
  6991. data.radiusBottom,
  6992. data.height,
  6993. data.radialSegments,
  6994. data.heightSegments,
  6995. data.openEnded
  6996. );
  6997. break;
  6998. case 'SphereGeometry':
  6999. geometry = new THREE.SphereGeometry(
  7000. data.radius,
  7001. data.widthSegments,
  7002. data.heightSegments,
  7003. data.phiStart,
  7004. data.phiLength,
  7005. data.thetaStart,
  7006. data.thetaLength
  7007. );
  7008. break;
  7009. case 'IcosahedronGeometry':
  7010. geometry = new THREE.IcosahedronGeometry(
  7011. data.radius,
  7012. data.detail
  7013. );
  7014. break;
  7015. case 'TorusGeometry':
  7016. geometry = new THREE.TorusGeometry(
  7017. data.radius,
  7018. data.tube,
  7019. data.radialSegments,
  7020. data.tubularSegments,
  7021. data.arc
  7022. );
  7023. break;
  7024. case 'TorusKnotGeometry':
  7025. geometry = new THREE.TorusKnotGeometry(
  7026. data.radius,
  7027. data.tube,
  7028. data.radialSegments,
  7029. data.tubularSegments,
  7030. data.p,
  7031. data.q,
  7032. data.heightScale
  7033. );
  7034. break;
  7035. case 'BufferGeometry':
  7036. geometry = bufferGeometryLoader.parse( data.data );
  7037. break;
  7038. case 'Geometry':
  7039. geometry = geometryLoader.parse( data.data ).geometry;
  7040. break;
  7041. }
  7042. geometry.uuid = data.uuid;
  7043. if ( data.name !== undefined ) geometry.name = data.name;
  7044. geometries[ data.uuid ] = geometry;
  7045. }
  7046. }
  7047. return geometries;
  7048. },
  7049. parseMaterials: function ( json ) {
  7050. var materials = {};
  7051. if ( json !== undefined ) {
  7052. var loader = new THREE.MaterialLoader();
  7053. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7054. var data = json[ i ];
  7055. var material = loader.parse( data );
  7056. material.uuid = data.uuid;
  7057. if ( data.name !== undefined ) material.name = data.name;
  7058. materials[ data.uuid ] = material;
  7059. }
  7060. }
  7061. return materials;
  7062. },
  7063. parseObject: function () {
  7064. var matrix = new THREE.Matrix4();
  7065. return function ( data, geometries, materials ) {
  7066. var object;
  7067. switch ( data.type ) {
  7068. case 'Scene':
  7069. object = new THREE.Scene();
  7070. break;
  7071. case 'PerspectiveCamera':
  7072. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  7073. break;
  7074. case 'OrthographicCamera':
  7075. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  7076. break;
  7077. case 'AmbientLight':
  7078. object = new THREE.AmbientLight( data.color );
  7079. break;
  7080. case 'DirectionalLight':
  7081. object = new THREE.DirectionalLight( data.color, data.intensity );
  7082. break;
  7083. case 'PointLight':
  7084. object = new THREE.PointLight( data.color, data.intensity, data.distance );
  7085. break;
  7086. case 'SpotLight':
  7087. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent );
  7088. break;
  7089. case 'HemisphereLight':
  7090. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  7091. break;
  7092. case 'Mesh':
  7093. var geometry = geometries[ data.geometry ];
  7094. var material = materials[ data.material ];
  7095. if ( geometry === undefined ) {
  7096. console.error( 'THREE.ObjectLoader: Undefined geometry ' + data.geometry );
  7097. }
  7098. if ( material === undefined ) {
  7099. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  7100. }
  7101. object = new THREE.Mesh( geometry, material );
  7102. break;
  7103. case 'Sprite':
  7104. var material = materials[ data.material ];
  7105. if ( material === undefined ) {
  7106. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  7107. }
  7108. object = new THREE.Sprite( material );
  7109. break;
  7110. default:
  7111. object = new THREE.Object3D();
  7112. }
  7113. object.uuid = data.uuid;
  7114. if ( data.name !== undefined ) object.name = data.name;
  7115. if ( data.matrix !== undefined ) {
  7116. matrix.fromArray( data.matrix );
  7117. matrix.decompose( object.position, object.quaternion, object.scale );
  7118. } else {
  7119. if ( data.position !== undefined ) object.position.fromArray( data.position );
  7120. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  7121. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  7122. }
  7123. if ( data.visible !== undefined ) object.visible = data.visible;
  7124. if ( data.userData !== undefined ) object.userData = data.userData;
  7125. if ( data.children !== undefined ) {
  7126. for ( var child in data.children ) {
  7127. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  7128. }
  7129. }
  7130. return object;
  7131. }
  7132. }()
  7133. };
  7134. /**
  7135. * @author alteredq / http://alteredqualia.com/
  7136. */
  7137. THREE.SceneLoader = function () {
  7138. this.onLoadStart = function () {};
  7139. this.onLoadProgress = function() {};
  7140. this.onLoadComplete = function () {};
  7141. this.callbackSync = function () {};
  7142. this.callbackProgress = function () {};
  7143. this.geometryHandlers = {};
  7144. this.hierarchyHandlers = {};
  7145. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  7146. };
  7147. THREE.SceneLoader.prototype = {
  7148. constructor: THREE.SceneLoader,
  7149. load: function ( url, onLoad, onProgress, onError ) {
  7150. var scope = this;
  7151. var loader = new THREE.XHRLoader( scope.manager );
  7152. loader.setCrossOrigin( this.crossOrigin );
  7153. loader.load( url, function ( text ) {
  7154. scope.parse( JSON.parse( text ), onLoad, url );
  7155. } );
  7156. },
  7157. setCrossOrigin: function ( value ) {
  7158. this.crossOrigin = value;
  7159. },
  7160. addGeometryHandler: function ( typeID, loaderClass ) {
  7161. this.geometryHandlers[ typeID ] = { "loaderClass": loaderClass };
  7162. },
  7163. addHierarchyHandler: function ( typeID, loaderClass ) {
  7164. this.hierarchyHandlers[ typeID ] = { "loaderClass": loaderClass };
  7165. },
  7166. parse: function ( json, callbackFinished, url ) {
  7167. var scope = this;
  7168. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  7169. var geometry, material, camera, fog,
  7170. texture, images, color,
  7171. light, hex, intensity,
  7172. counter_models, counter_textures,
  7173. total_models, total_textures,
  7174. result;
  7175. var target_array = [];
  7176. var data = json;
  7177. // async geometry loaders
  7178. for ( var typeID in this.geometryHandlers ) {
  7179. var loaderClass = this.geometryHandlers[ typeID ][ "loaderClass" ];
  7180. this.geometryHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  7181. }
  7182. // async hierachy loaders
  7183. for ( var typeID in this.hierarchyHandlers ) {
  7184. var loaderClass = this.hierarchyHandlers[ typeID ][ "loaderClass" ];
  7185. this.hierarchyHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  7186. }
  7187. counter_models = 0;
  7188. counter_textures = 0;
  7189. result = {
  7190. scene: new THREE.Scene(),
  7191. geometries: {},
  7192. face_materials: {},
  7193. materials: {},
  7194. textures: {},
  7195. objects: {},
  7196. cameras: {},
  7197. lights: {},
  7198. fogs: {},
  7199. empties: {},
  7200. groups: {}
  7201. };
  7202. if ( data.transform ) {
  7203. var position = data.transform.position,
  7204. rotation = data.transform.rotation,
  7205. scale = data.transform.scale;
  7206. if ( position ) {
  7207. result.scene.position.fromArray( position );
  7208. }
  7209. if ( rotation ) {
  7210. result.scene.rotation.fromArray( rotation );
  7211. }
  7212. if ( scale ) {
  7213. result.scene.scale.fromArray( scale );
  7214. }
  7215. if ( position || rotation || scale ) {
  7216. result.scene.updateMatrix();
  7217. result.scene.updateMatrixWorld();
  7218. }
  7219. }
  7220. function get_url( source_url, url_type ) {
  7221. if ( url_type == "relativeToHTML" ) {
  7222. return source_url;
  7223. } else {
  7224. return urlBase + "/" + source_url;
  7225. }
  7226. };
  7227. // toplevel loader function, delegates to handle_children
  7228. function handle_objects() {
  7229. handle_children( result.scene, data.objects );
  7230. }
  7231. // handle all the children from the loaded json and attach them to given parent
  7232. function handle_children( parent, children ) {
  7233. var mat, dst, pos, rot, scl, quat;
  7234. for ( var objID in children ) {
  7235. // check by id if child has already been handled,
  7236. // if not, create new object
  7237. var object = result.objects[ objID ];
  7238. var objJSON = children[ objID ];
  7239. if ( object === undefined ) {
  7240. // meshes
  7241. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  7242. if ( objJSON.loading === undefined ) {
  7243. var reservedTypes = {
  7244. "type": 1, "url": 1, "material": 1,
  7245. "position": 1, "rotation": 1, "scale" : 1,
  7246. "visible": 1, "children": 1, "userData": 1,
  7247. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1
  7248. };
  7249. var loaderParameters = {};
  7250. for ( var parType in objJSON ) {
  7251. if ( ! ( parType in reservedTypes ) ) {
  7252. loaderParameters[ parType ] = objJSON[ parType ];
  7253. }
  7254. }
  7255. material = result.materials[ objJSON.material ];
  7256. objJSON.loading = true;
  7257. var loader = scope.hierarchyHandlers[ objJSON.type ][ "loaderObject" ];
  7258. // ColladaLoader
  7259. if ( loader.options ) {
  7260. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  7261. // UTF8Loader
  7262. // OBJLoader
  7263. } else {
  7264. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  7265. }
  7266. }
  7267. } else if ( objJSON.geometry !== undefined ) {
  7268. geometry = result.geometries[ objJSON.geometry ];
  7269. // geometry already loaded
  7270. if ( geometry ) {
  7271. var needsTangents = false;
  7272. material = result.materials[ objJSON.material ];
  7273. needsTangents = material instanceof THREE.ShaderMaterial;
  7274. pos = objJSON.position;
  7275. rot = objJSON.rotation;
  7276. scl = objJSON.scale;
  7277. mat = objJSON.matrix;
  7278. quat = objJSON.quaternion;
  7279. // use materials from the model file
  7280. // if there is no material specified in the object
  7281. if ( ! objJSON.material ) {
  7282. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  7283. }
  7284. // use materials from the model file
  7285. // if there is just empty face material
  7286. // (must create new material as each model has its own face material)
  7287. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  7288. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  7289. }
  7290. if ( material instanceof THREE.MeshFaceMaterial ) {
  7291. for ( var i = 0; i < material.materials.length; i ++ ) {
  7292. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  7293. }
  7294. }
  7295. if ( needsTangents ) {
  7296. geometry.computeTangents();
  7297. }
  7298. if ( objJSON.skin ) {
  7299. object = new THREE.SkinnedMesh( geometry, material );
  7300. } else if ( objJSON.morph ) {
  7301. object = new THREE.MorphAnimMesh( geometry, material );
  7302. if ( objJSON.duration !== undefined ) {
  7303. object.duration = objJSON.duration;
  7304. }
  7305. if ( objJSON.time !== undefined ) {
  7306. object.time = objJSON.time;
  7307. }
  7308. if ( objJSON.mirroredLoop !== undefined ) {
  7309. object.mirroredLoop = objJSON.mirroredLoop;
  7310. }
  7311. if ( material.morphNormals ) {
  7312. geometry.computeMorphNormals();
  7313. }
  7314. } else {
  7315. object = new THREE.Mesh( geometry, material );
  7316. }
  7317. object.name = objID;
  7318. if ( mat ) {
  7319. object.matrixAutoUpdate = false;
  7320. object.matrix.set(
  7321. mat[0], mat[1], mat[2], mat[3],
  7322. mat[4], mat[5], mat[6], mat[7],
  7323. mat[8], mat[9], mat[10], mat[11],
  7324. mat[12], mat[13], mat[14], mat[15]
  7325. );
  7326. } else {
  7327. object.position.fromArray( pos );
  7328. if ( quat ) {
  7329. object.quaternion.fromArray( quat );
  7330. } else {
  7331. object.rotation.fromArray( rot );
  7332. }
  7333. object.scale.fromArray( scl );
  7334. }
  7335. object.visible = objJSON.visible;
  7336. object.castShadow = objJSON.castShadow;
  7337. object.receiveShadow = objJSON.receiveShadow;
  7338. parent.add( object );
  7339. result.objects[ objID ] = object;
  7340. }
  7341. // lights
  7342. } else if ( objJSON.type === "AmbientLight" || objJSON.type === "PointLight" ||
  7343. objJSON.type === "DirectionalLight" || objJSON.type === "SpotLight" ||
  7344. objJSON.type === "HemisphereLight" || objJSON.type === "AreaLight" ) {
  7345. var color = objJSON.color;
  7346. var intensity = objJSON.intensity;
  7347. var distance = objJSON.distance;
  7348. var position = objJSON.position;
  7349. var rotation = objJSON.rotation;
  7350. switch ( objJSON.type ) {
  7351. case 'AmbientLight':
  7352. light = new THREE.AmbientLight( color );
  7353. break;
  7354. case 'PointLight':
  7355. light = new THREE.PointLight( color, intensity, distance );
  7356. light.position.fromArray( position );
  7357. break;
  7358. case 'DirectionalLight':
  7359. light = new THREE.DirectionalLight( color, intensity );
  7360. light.position.fromArray( objJSON.direction );
  7361. break;
  7362. case 'SpotLight':
  7363. light = new THREE.SpotLight( color, intensity, distance, 1 );
  7364. light.angle = objJSON.angle;
  7365. light.position.fromArray( position );
  7366. light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] );
  7367. light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) );
  7368. break;
  7369. case 'HemisphereLight':
  7370. light = new THREE.DirectionalLight( color, intensity, distance );
  7371. light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] );
  7372. light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) );
  7373. break;
  7374. case 'AreaLight':
  7375. light = new THREE.AreaLight(color, intensity);
  7376. light.position.fromArray( position );
  7377. light.width = objJSON.size;
  7378. light.height = objJSON.size_y;
  7379. break;
  7380. }
  7381. parent.add( light );
  7382. light.name = objID;
  7383. result.lights[ objID ] = light;
  7384. result.objects[ objID ] = light;
  7385. // cameras
  7386. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  7387. pos = objJSON.position;
  7388. rot = objJSON.rotation;
  7389. quat = objJSON.quaternion;
  7390. if ( objJSON.type === "PerspectiveCamera" ) {
  7391. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  7392. } else if ( objJSON.type === "OrthographicCamera" ) {
  7393. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  7394. }
  7395. camera.name = objID;
  7396. camera.position.fromArray( pos );
  7397. if ( quat !== undefined ) {
  7398. camera.quaternion.fromArray( quat );
  7399. } else if ( rot !== undefined ) {
  7400. camera.rotation.fromArray( rot );
  7401. }
  7402. parent.add( camera );
  7403. result.cameras[ objID ] = camera;
  7404. result.objects[ objID ] = camera;
  7405. // pure Object3D
  7406. } else {
  7407. pos = objJSON.position;
  7408. rot = objJSON.rotation;
  7409. scl = objJSON.scale;
  7410. quat = objJSON.quaternion;
  7411. object = new THREE.Object3D();
  7412. object.name = objID;
  7413. object.position.fromArray( pos );
  7414. if ( quat ) {
  7415. object.quaternion.fromArray( quat );
  7416. } else {
  7417. object.rotation.fromArray( rot );
  7418. }
  7419. object.scale.fromArray( scl );
  7420. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  7421. parent.add( object );
  7422. result.objects[ objID ] = object;
  7423. result.empties[ objID ] = object;
  7424. }
  7425. if ( object ) {
  7426. if ( objJSON.userData !== undefined ) {
  7427. for ( var key in objJSON.userData ) {
  7428. var value = objJSON.userData[ key ];
  7429. object.userData[ key ] = value;
  7430. }
  7431. }
  7432. if ( objJSON.groups !== undefined ) {
  7433. for ( var i = 0; i < objJSON.groups.length; i ++ ) {
  7434. var groupID = objJSON.groups[ i ];
  7435. if ( result.groups[ groupID ] === undefined ) {
  7436. result.groups[ groupID ] = [];
  7437. }
  7438. result.groups[ groupID ].push( objID );
  7439. }
  7440. }
  7441. }
  7442. }
  7443. if ( object !== undefined && objJSON.children !== undefined ) {
  7444. handle_children( object, objJSON.children );
  7445. }
  7446. }
  7447. };
  7448. function handle_mesh( geo, mat, id ) {
  7449. result.geometries[ id ] = geo;
  7450. result.face_materials[ id ] = mat;
  7451. handle_objects();
  7452. };
  7453. function handle_hierarchy( node, id, parent, material, obj ) {
  7454. var p = obj.position;
  7455. var r = obj.rotation;
  7456. var q = obj.quaternion;
  7457. var s = obj.scale;
  7458. node.position.fromArray( p );
  7459. if ( q ) {
  7460. node.quaternion.fromArray( q );
  7461. } else {
  7462. node.rotation.fromArray( r );
  7463. }
  7464. node.scale.fromArray( s );
  7465. // override children materials
  7466. // if object material was specified in JSON explicitly
  7467. if ( material ) {
  7468. node.traverse( function ( child ) {
  7469. child.material = material;
  7470. } );
  7471. }
  7472. // override children visibility
  7473. // with root node visibility as specified in JSON
  7474. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  7475. node.traverse( function ( child ) {
  7476. child.visible = visible;
  7477. } );
  7478. parent.add( node );
  7479. node.name = id;
  7480. result.objects[ id ] = node;
  7481. handle_objects();
  7482. };
  7483. function create_callback_geometry( id ) {
  7484. return function ( geo, mat ) {
  7485. geo.name = id;
  7486. handle_mesh( geo, mat, id );
  7487. counter_models -= 1;
  7488. scope.onLoadComplete();
  7489. async_callback_gate();
  7490. }
  7491. };
  7492. function create_callback_hierachy( id, parent, material, obj ) {
  7493. return function ( event ) {
  7494. var result;
  7495. // loaders which use EventDispatcher
  7496. if ( event.content ) {
  7497. result = event.content;
  7498. // ColladaLoader
  7499. } else if ( event.dae ) {
  7500. result = event.scene;
  7501. // UTF8Loader
  7502. } else {
  7503. result = event;
  7504. }
  7505. handle_hierarchy( result, id, parent, material, obj );
  7506. counter_models -= 1;
  7507. scope.onLoadComplete();
  7508. async_callback_gate();
  7509. }
  7510. };
  7511. function create_callback_embed( id ) {
  7512. return function ( geo, mat ) {
  7513. geo.name = id;
  7514. result.geometries[ id ] = geo;
  7515. result.face_materials[ id ] = mat;
  7516. }
  7517. };
  7518. function async_callback_gate() {
  7519. var progress = {
  7520. totalModels : total_models,
  7521. totalTextures : total_textures,
  7522. loadedModels : total_models - counter_models,
  7523. loadedTextures : total_textures - counter_textures
  7524. };
  7525. scope.callbackProgress( progress, result );
  7526. scope.onLoadProgress();
  7527. if ( counter_models === 0 && counter_textures === 0 ) {
  7528. finalize();
  7529. callbackFinished( result );
  7530. }
  7531. };
  7532. function finalize() {
  7533. // take care of targets which could be asynchronously loaded objects
  7534. for ( var i = 0; i < target_array.length; i ++ ) {
  7535. var ta = target_array[ i ];
  7536. var target = result.objects[ ta.targetName ];
  7537. if ( target ) {
  7538. ta.object.target = target;
  7539. } else {
  7540. // if there was error and target of specified name doesn't exist in the scene file
  7541. // create instead dummy target
  7542. // (target must be added to scene explicitly as parent is already added)
  7543. ta.object.target = new THREE.Object3D();
  7544. result.scene.add( ta.object.target );
  7545. }
  7546. ta.object.target.userData.targetInverse = ta.object;
  7547. }
  7548. };
  7549. var callbackTexture = function ( count ) {
  7550. counter_textures -= count;
  7551. async_callback_gate();
  7552. scope.onLoadComplete();
  7553. };
  7554. // must use this instead of just directly calling callbackTexture
  7555. // because of closure in the calling context loop
  7556. var generateTextureCallback = function ( count ) {
  7557. return function () {
  7558. callbackTexture( count );
  7559. };
  7560. };
  7561. function traverse_json_hierarchy( objJSON, callback ) {
  7562. callback( objJSON );
  7563. if ( objJSON.children !== undefined ) {
  7564. for ( var objChildID in objJSON.children ) {
  7565. traverse_json_hierarchy( objJSON.children[ objChildID ], callback );
  7566. }
  7567. }
  7568. };
  7569. // first go synchronous elements
  7570. // fogs
  7571. var fogID, fogJSON;
  7572. for ( fogID in data.fogs ) {
  7573. fogJSON = data.fogs[ fogID ];
  7574. if ( fogJSON.type === "linear" ) {
  7575. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  7576. } else if ( fogJSON.type === "exp2" ) {
  7577. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  7578. }
  7579. color = fogJSON.color;
  7580. fog.color.setRGB( color[0], color[1], color[2] );
  7581. result.fogs[ fogID ] = fog;
  7582. }
  7583. // now come potentially asynchronous elements
  7584. // geometries
  7585. // count how many geometries will be loaded asynchronously
  7586. var geoID, geoJSON;
  7587. for ( geoID in data.geometries ) {
  7588. geoJSON = data.geometries[ geoID ];
  7589. if ( geoJSON.type in this.geometryHandlers ) {
  7590. counter_models += 1;
  7591. scope.onLoadStart();
  7592. }
  7593. }
  7594. // count how many hierarchies will be loaded asynchronously
  7595. for ( var objID in data.objects ) {
  7596. traverse_json_hierarchy( data.objects[ objID ], function ( objJSON ) {
  7597. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  7598. counter_models += 1;
  7599. scope.onLoadStart();
  7600. }
  7601. });
  7602. }
  7603. total_models = counter_models;
  7604. for ( geoID in data.geometries ) {
  7605. geoJSON = data.geometries[ geoID ];
  7606. if ( geoJSON.type === "cube" ) {
  7607. geometry = new THREE.CubeGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  7608. geometry.name = geoID;
  7609. result.geometries[ geoID ] = geometry;
  7610. } else if ( geoJSON.type === "plane" ) {
  7611. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  7612. geometry.name = geoID;
  7613. result.geometries[ geoID ] = geometry;
  7614. } else if ( geoJSON.type === "sphere" ) {
  7615. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  7616. geometry.name = geoID;
  7617. result.geometries[ geoID ] = geometry;
  7618. } else if ( geoJSON.type === "cylinder" ) {
  7619. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  7620. geometry.name = geoID;
  7621. result.geometries[ geoID ] = geometry;
  7622. } else if ( geoJSON.type === "torus" ) {
  7623. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  7624. geometry.name = geoID;
  7625. result.geometries[ geoID ] = geometry;
  7626. } else if ( geoJSON.type === "icosahedron" ) {
  7627. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  7628. geometry.name = geoID;
  7629. result.geometries[ geoID ] = geometry;
  7630. } else if ( geoJSON.type in this.geometryHandlers ) {
  7631. var loaderParameters = {};
  7632. for ( var parType in geoJSON ) {
  7633. if ( parType !== "type" && parType !== "url" ) {
  7634. loaderParameters[ parType ] = geoJSON[ parType ];
  7635. }
  7636. }
  7637. var loader = this.geometryHandlers[ geoJSON.type ][ "loaderObject" ];
  7638. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  7639. } else if ( geoJSON.type === "embedded" ) {
  7640. var modelJson = data.embeds[ geoJSON.id ],
  7641. texture_path = "";
  7642. // pass metadata along to jsonLoader so it knows the format version
  7643. modelJson.metadata = data.metadata;
  7644. if ( modelJson ) {
  7645. var jsonLoader = this.geometryHandlers[ "ascii" ][ "loaderObject" ];
  7646. var model = jsonLoader.parse( modelJson, texture_path );
  7647. create_callback_embed( geoID )( model.geometry, model.materials );
  7648. }
  7649. }
  7650. }
  7651. // textures
  7652. // count how many textures will be loaded asynchronously
  7653. var textureID, textureJSON;
  7654. for ( textureID in data.textures ) {
  7655. textureJSON = data.textures[ textureID ];
  7656. if ( textureJSON.url instanceof Array ) {
  7657. counter_textures += textureJSON.url.length;
  7658. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  7659. scope.onLoadStart();
  7660. }
  7661. } else {
  7662. counter_textures += 1;
  7663. scope.onLoadStart();
  7664. }
  7665. }
  7666. total_textures = counter_textures;
  7667. for ( textureID in data.textures ) {
  7668. textureJSON = data.textures[ textureID ];
  7669. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  7670. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  7671. }
  7672. if ( textureJSON.url instanceof Array ) {
  7673. var count = textureJSON.url.length;
  7674. var url_array = [];
  7675. for( var i = 0; i < count; i ++ ) {
  7676. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  7677. }
  7678. var isCompressed = /\.dds$/i.test( url_array[ 0 ] );
  7679. if ( isCompressed ) {
  7680. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  7681. } else {
  7682. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  7683. }
  7684. } else {
  7685. var isCompressed = /\.dds$/i.test( textureJSON.url );
  7686. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  7687. var textureCallback = generateTextureCallback( 1 );
  7688. if ( isCompressed ) {
  7689. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  7690. } else {
  7691. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  7692. }
  7693. if ( THREE[ textureJSON.minFilter ] !== undefined )
  7694. texture.minFilter = THREE[ textureJSON.minFilter ];
  7695. if ( THREE[ textureJSON.magFilter ] !== undefined )
  7696. texture.magFilter = THREE[ textureJSON.magFilter ];
  7697. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  7698. if ( textureJSON.repeat ) {
  7699. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  7700. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  7701. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  7702. }
  7703. if ( textureJSON.offset ) {
  7704. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  7705. }
  7706. // handle wrap after repeat so that default repeat can be overriden
  7707. if ( textureJSON.wrap ) {
  7708. var wrapMap = {
  7709. "repeat": THREE.RepeatWrapping,
  7710. "mirror": THREE.MirroredRepeatWrapping
  7711. }
  7712. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  7713. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  7714. }
  7715. }
  7716. result.textures[ textureID ] = texture;
  7717. }
  7718. // materials
  7719. var matID, matJSON;
  7720. var parID;
  7721. for ( matID in data.materials ) {
  7722. matJSON = data.materials[ matID ];
  7723. for ( parID in matJSON.parameters ) {
  7724. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  7725. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  7726. } else if ( parID === "shading" ) {
  7727. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  7728. } else if ( parID === "side" ) {
  7729. if ( matJSON.parameters[ parID ] == "double" ) {
  7730. matJSON.parameters[ parID ] = THREE.DoubleSide;
  7731. } else if ( matJSON.parameters[ parID ] == "back" ) {
  7732. matJSON.parameters[ parID ] = THREE.BackSide;
  7733. } else {
  7734. matJSON.parameters[ parID ] = THREE.FrontSide;
  7735. }
  7736. } else if ( parID === "blending" ) {
  7737. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  7738. } else if ( parID === "combine" ) {
  7739. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  7740. } else if ( parID === "vertexColors" ) {
  7741. if ( matJSON.parameters[ parID ] == "face" ) {
  7742. matJSON.parameters[ parID ] = THREE.FaceColors;
  7743. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  7744. } else if ( matJSON.parameters[ parID ] ) {
  7745. matJSON.parameters[ parID ] = THREE.VertexColors;
  7746. }
  7747. } else if ( parID === "wrapRGB" ) {
  7748. var v3 = matJSON.parameters[ parID ];
  7749. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  7750. }
  7751. }
  7752. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  7753. matJSON.parameters.transparent = true;
  7754. }
  7755. if ( matJSON.parameters.normalMap ) {
  7756. var shader = THREE.ShaderLib[ "normalmap" ];
  7757. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  7758. var diffuse = matJSON.parameters.color;
  7759. var specular = matJSON.parameters.specular;
  7760. var ambient = matJSON.parameters.ambient;
  7761. var shininess = matJSON.parameters.shininess;
  7762. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  7763. if ( matJSON.parameters.normalScale ) {
  7764. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  7765. }
  7766. if ( matJSON.parameters.map ) {
  7767. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  7768. uniforms[ "enableDiffuse" ].value = true;
  7769. }
  7770. if ( matJSON.parameters.envMap ) {
  7771. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  7772. uniforms[ "enableReflection" ].value = true;
  7773. uniforms[ "reflectivity" ].value = matJSON.parameters.reflectivity;
  7774. }
  7775. if ( matJSON.parameters.lightMap ) {
  7776. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  7777. uniforms[ "enableAO" ].value = true;
  7778. }
  7779. if ( matJSON.parameters.specularMap ) {
  7780. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  7781. uniforms[ "enableSpecular" ].value = true;
  7782. }
  7783. if ( matJSON.parameters.displacementMap ) {
  7784. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  7785. uniforms[ "enableDisplacement" ].value = true;
  7786. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  7787. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  7788. }
  7789. uniforms[ "diffuse" ].value.setHex( diffuse );
  7790. uniforms[ "specular" ].value.setHex( specular );
  7791. uniforms[ "ambient" ].value.setHex( ambient );
  7792. uniforms[ "shininess" ].value = shininess;
  7793. if ( matJSON.parameters.opacity ) {
  7794. uniforms[ "opacity" ].value = matJSON.parameters.opacity;
  7795. }
  7796. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  7797. material = new THREE.ShaderMaterial( parameters );
  7798. } else {
  7799. material = new THREE[ matJSON.type ]( matJSON.parameters );
  7800. }
  7801. material.name = matID;
  7802. result.materials[ matID ] = material;
  7803. }
  7804. // second pass through all materials to initialize MeshFaceMaterials
  7805. // that could be referring to other materials out of order
  7806. for ( matID in data.materials ) {
  7807. matJSON = data.materials[ matID ];
  7808. if ( matJSON.parameters.materials ) {
  7809. var materialArray = [];
  7810. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  7811. var label = matJSON.parameters.materials[ i ];
  7812. materialArray.push( result.materials[ label ] );
  7813. }
  7814. result.materials[ matID ].materials = materialArray;
  7815. }
  7816. }
  7817. // objects ( synchronous init of procedural primitives )
  7818. handle_objects();
  7819. // defaults
  7820. if ( result.cameras && data.defaults.camera ) {
  7821. result.currentCamera = result.cameras[ data.defaults.camera ];
  7822. }
  7823. if ( result.fogs && data.defaults.fog ) {
  7824. result.scene.fog = result.fogs[ data.defaults.fog ];
  7825. }
  7826. // synchronous callback
  7827. scope.callbackSync( result );
  7828. // just in case there are no async elements
  7829. async_callback_gate();
  7830. }
  7831. }
  7832. /**
  7833. * @author mrdoob / http://mrdoob.com/
  7834. */
  7835. THREE.TextureLoader = function ( manager ) {
  7836. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7837. };
  7838. THREE.TextureLoader.prototype = {
  7839. constructor: THREE.TextureLoader,
  7840. load: function ( url, onLoad, onProgress, onError ) {
  7841. var scope = this;
  7842. var loader = new THREE.ImageLoader( scope.manager );
  7843. loader.setCrossOrigin( this.crossOrigin );
  7844. loader.load( url, function ( image ) {
  7845. var texture = new THREE.Texture( image );
  7846. texture.needsUpdate = true;
  7847. if ( onLoad !== undefined ) {
  7848. onLoad( texture );
  7849. }
  7850. } );
  7851. },
  7852. setCrossOrigin: function ( value ) {
  7853. this.crossOrigin = value;
  7854. }
  7855. };
  7856. /**
  7857. * @author mrdoob / http://mrdoob.com/
  7858. * @author alteredq / http://alteredqualia.com/
  7859. */
  7860. THREE.Material = function () {
  7861. this.id = THREE.MaterialIdCount ++;
  7862. this.uuid = THREE.Math.generateUUID();
  7863. this.name = '';
  7864. this.side = THREE.FrontSide;
  7865. this.opacity = 1;
  7866. this.transparent = false;
  7867. this.blending = THREE.NormalBlending;
  7868. this.blendSrc = THREE.SrcAlphaFactor;
  7869. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  7870. this.blendEquation = THREE.AddEquation;
  7871. this.depthTest = true;
  7872. this.depthWrite = true;
  7873. this.polygonOffset = false;
  7874. this.polygonOffsetFactor = 0;
  7875. this.polygonOffsetUnits = 0;
  7876. this.alphaTest = 0;
  7877. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  7878. this.visible = true;
  7879. this.needsUpdate = true;
  7880. };
  7881. THREE.Material.prototype = {
  7882. constructor: THREE.Material,
  7883. setValues: function ( values ) {
  7884. if ( values === undefined ) return;
  7885. for ( var key in values ) {
  7886. var newValue = values[ key ];
  7887. if ( newValue === undefined ) {
  7888. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  7889. continue;
  7890. }
  7891. if ( key in this ) {
  7892. var currentValue = this[ key ];
  7893. if ( currentValue instanceof THREE.Color ) {
  7894. currentValue.set( newValue );
  7895. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  7896. currentValue.copy( newValue );
  7897. } else if ( key == 'overdraw') {
  7898. // ensure overdraw is backwards-compatable with legacy boolean type
  7899. this[ key ] = Number(newValue);
  7900. } else {
  7901. this[ key ] = newValue;
  7902. }
  7903. }
  7904. }
  7905. },
  7906. clone: function ( material ) {
  7907. if ( material === undefined ) material = new THREE.Material();
  7908. material.name = this.name;
  7909. material.side = this.side;
  7910. material.opacity = this.opacity;
  7911. material.transparent = this.transparent;
  7912. material.blending = this.blending;
  7913. material.blendSrc = this.blendSrc;
  7914. material.blendDst = this.blendDst;
  7915. material.blendEquation = this.blendEquation;
  7916. material.depthTest = this.depthTest;
  7917. material.depthWrite = this.depthWrite;
  7918. material.polygonOffset = this.polygonOffset;
  7919. material.polygonOffsetFactor = this.polygonOffsetFactor;
  7920. material.polygonOffsetUnits = this.polygonOffsetUnits;
  7921. material.alphaTest = this.alphaTest;
  7922. material.overdraw = this.overdraw;
  7923. material.visible = this.visible;
  7924. return material;
  7925. },
  7926. dispose: function () {
  7927. this.dispatchEvent( { type: 'dispose' } );
  7928. }
  7929. };
  7930. THREE.EventDispatcher.prototype.apply( THREE.Material.prototype );
  7931. THREE.MaterialIdCount = 0;
  7932. /**
  7933. * @author mrdoob / http://mrdoob.com/
  7934. * @author alteredq / http://alteredqualia.com/
  7935. *
  7936. * parameters = {
  7937. * color: <hex>,
  7938. * opacity: <float>,
  7939. *
  7940. * blending: THREE.NormalBlending,
  7941. * depthTest: <bool>,
  7942. * depthWrite: <bool>,
  7943. *
  7944. * linewidth: <float>,
  7945. * linecap: "round",
  7946. * linejoin: "round",
  7947. *
  7948. * vertexColors: <bool>
  7949. *
  7950. * fog: <bool>
  7951. * }
  7952. */
  7953. THREE.LineBasicMaterial = function ( parameters ) {
  7954. THREE.Material.call( this );
  7955. this.color = new THREE.Color( 0xffffff );
  7956. this.linewidth = 1;
  7957. this.linecap = 'round';
  7958. this.linejoin = 'round';
  7959. this.vertexColors = false;
  7960. this.fog = true;
  7961. this.setValues( parameters );
  7962. };
  7963. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7964. THREE.LineBasicMaterial.prototype.clone = function () {
  7965. var material = new THREE.LineBasicMaterial();
  7966. THREE.Material.prototype.clone.call( this, material );
  7967. material.color.copy( this.color );
  7968. material.linewidth = this.linewidth;
  7969. material.linecap = this.linecap;
  7970. material.linejoin = this.linejoin;
  7971. material.vertexColors = this.vertexColors;
  7972. material.fog = this.fog;
  7973. return material;
  7974. };
  7975. /**
  7976. * @author alteredq / http://alteredqualia.com/
  7977. *
  7978. * parameters = {
  7979. * color: <hex>,
  7980. * opacity: <float>,
  7981. *
  7982. * blending: THREE.NormalBlending,
  7983. * depthTest: <bool>,
  7984. * depthWrite: <bool>,
  7985. *
  7986. * linewidth: <float>,
  7987. *
  7988. * scale: <float>,
  7989. * dashSize: <float>,
  7990. * gapSize: <float>,
  7991. *
  7992. * vertexColors: <bool>
  7993. *
  7994. * fog: <bool>
  7995. * }
  7996. */
  7997. THREE.LineDashedMaterial = function ( parameters ) {
  7998. THREE.Material.call( this );
  7999. this.color = new THREE.Color( 0xffffff );
  8000. this.linewidth = 1;
  8001. this.scale = 1;
  8002. this.dashSize = 3;
  8003. this.gapSize = 1;
  8004. this.vertexColors = false;
  8005. this.fog = true;
  8006. this.setValues( parameters );
  8007. };
  8008. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  8009. THREE.LineDashedMaterial.prototype.clone = function () {
  8010. var material = new THREE.LineDashedMaterial();
  8011. THREE.Material.prototype.clone.call( this, material );
  8012. material.color.copy( this.color );
  8013. material.linewidth = this.linewidth;
  8014. material.scale = this.scale;
  8015. material.dashSize = this.dashSize;
  8016. material.gapSize = this.gapSize;
  8017. material.vertexColors = this.vertexColors;
  8018. material.fog = this.fog;
  8019. return material;
  8020. };
  8021. /**
  8022. * @author mrdoob / http://mrdoob.com/
  8023. * @author alteredq / http://alteredqualia.com/
  8024. *
  8025. * parameters = {
  8026. * color: <hex>,
  8027. * opacity: <float>,
  8028. * map: new THREE.Texture( <Image> ),
  8029. *
  8030. * lightMap: new THREE.Texture( <Image> ),
  8031. *
  8032. * specularMap: new THREE.Texture( <Image> ),
  8033. *
  8034. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8035. * combine: THREE.Multiply,
  8036. * reflectivity: <float>,
  8037. * refractionRatio: <float>,
  8038. *
  8039. * shading: THREE.SmoothShading,
  8040. * blending: THREE.NormalBlending,
  8041. * depthTest: <bool>,
  8042. * depthWrite: <bool>,
  8043. *
  8044. * wireframe: <boolean>,
  8045. * wireframeLinewidth: <float>,
  8046. *
  8047. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8048. *
  8049. * skinning: <bool>,
  8050. * morphTargets: <bool>,
  8051. *
  8052. * fog: <bool>
  8053. * }
  8054. */
  8055. THREE.MeshBasicMaterial = function ( parameters ) {
  8056. THREE.Material.call( this );
  8057. this.color = new THREE.Color( 0xffffff ); // emissive
  8058. this.map = null;
  8059. this.lightMap = null;
  8060. this.specularMap = null;
  8061. this.envMap = null;
  8062. this.combine = THREE.MultiplyOperation;
  8063. this.reflectivity = 1;
  8064. this.refractionRatio = 0.98;
  8065. this.fog = true;
  8066. this.shading = THREE.SmoothShading;
  8067. this.wireframe = false;
  8068. this.wireframeLinewidth = 1;
  8069. this.wireframeLinecap = 'round';
  8070. this.wireframeLinejoin = 'round';
  8071. this.vertexColors = THREE.NoColors;
  8072. this.skinning = false;
  8073. this.morphTargets = false;
  8074. this.setValues( parameters );
  8075. };
  8076. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  8077. THREE.MeshBasicMaterial.prototype.clone = function () {
  8078. var material = new THREE.MeshBasicMaterial();
  8079. THREE.Material.prototype.clone.call( this, material );
  8080. material.color.copy( this.color );
  8081. material.map = this.map;
  8082. material.lightMap = this.lightMap;
  8083. material.specularMap = this.specularMap;
  8084. material.envMap = this.envMap;
  8085. material.combine = this.combine;
  8086. material.reflectivity = this.reflectivity;
  8087. material.refractionRatio = this.refractionRatio;
  8088. material.fog = this.fog;
  8089. material.shading = this.shading;
  8090. material.wireframe = this.wireframe;
  8091. material.wireframeLinewidth = this.wireframeLinewidth;
  8092. material.wireframeLinecap = this.wireframeLinecap;
  8093. material.wireframeLinejoin = this.wireframeLinejoin;
  8094. material.vertexColors = this.vertexColors;
  8095. material.skinning = this.skinning;
  8096. material.morphTargets = this.morphTargets;
  8097. return material;
  8098. };
  8099. /**
  8100. * @author mrdoob / http://mrdoob.com/
  8101. * @author alteredq / http://alteredqualia.com/
  8102. *
  8103. * parameters = {
  8104. * color: <hex>,
  8105. * ambient: <hex>,
  8106. * emissive: <hex>,
  8107. * opacity: <float>,
  8108. *
  8109. * map: new THREE.Texture( <Image> ),
  8110. *
  8111. * lightMap: new THREE.Texture( <Image> ),
  8112. *
  8113. * specularMap: new THREE.Texture( <Image> ),
  8114. *
  8115. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8116. * combine: THREE.Multiply,
  8117. * reflectivity: <float>,
  8118. * refractionRatio: <float>,
  8119. *
  8120. * shading: THREE.SmoothShading,
  8121. * blending: THREE.NormalBlending,
  8122. * depthTest: <bool>,
  8123. * depthWrite: <bool>,
  8124. *
  8125. * wireframe: <boolean>,
  8126. * wireframeLinewidth: <float>,
  8127. *
  8128. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8129. *
  8130. * skinning: <bool>,
  8131. * morphTargets: <bool>,
  8132. * morphNormals: <bool>,
  8133. *
  8134. * fog: <bool>
  8135. * }
  8136. */
  8137. THREE.MeshLambertMaterial = function ( parameters ) {
  8138. THREE.Material.call( this );
  8139. this.color = new THREE.Color( 0xffffff ); // diffuse
  8140. this.ambient = new THREE.Color( 0xffffff );
  8141. this.emissive = new THREE.Color( 0x000000 );
  8142. this.wrapAround = false;
  8143. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  8144. this.map = null;
  8145. this.lightMap = null;
  8146. this.specularMap = null;
  8147. this.envMap = null;
  8148. this.combine = THREE.MultiplyOperation;
  8149. this.reflectivity = 1;
  8150. this.refractionRatio = 0.98;
  8151. this.fog = true;
  8152. this.shading = THREE.SmoothShading;
  8153. this.wireframe = false;
  8154. this.wireframeLinewidth = 1;
  8155. this.wireframeLinecap = 'round';
  8156. this.wireframeLinejoin = 'round';
  8157. this.vertexColors = THREE.NoColors;
  8158. this.skinning = false;
  8159. this.morphTargets = false;
  8160. this.morphNormals = false;
  8161. this.setValues( parameters );
  8162. };
  8163. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  8164. THREE.MeshLambertMaterial.prototype.clone = function () {
  8165. var material = new THREE.MeshLambertMaterial();
  8166. THREE.Material.prototype.clone.call( this, material );
  8167. material.color.copy( this.color );
  8168. material.ambient.copy( this.ambient );
  8169. material.emissive.copy( this.emissive );
  8170. material.wrapAround = this.wrapAround;
  8171. material.wrapRGB.copy( this.wrapRGB );
  8172. material.map = this.map;
  8173. material.lightMap = this.lightMap;
  8174. material.specularMap = this.specularMap;
  8175. material.envMap = this.envMap;
  8176. material.combine = this.combine;
  8177. material.reflectivity = this.reflectivity;
  8178. material.refractionRatio = this.refractionRatio;
  8179. material.fog = this.fog;
  8180. material.shading = this.shading;
  8181. material.wireframe = this.wireframe;
  8182. material.wireframeLinewidth = this.wireframeLinewidth;
  8183. material.wireframeLinecap = this.wireframeLinecap;
  8184. material.wireframeLinejoin = this.wireframeLinejoin;
  8185. material.vertexColors = this.vertexColors;
  8186. material.skinning = this.skinning;
  8187. material.morphTargets = this.morphTargets;
  8188. material.morphNormals = this.morphNormals;
  8189. return material;
  8190. };
  8191. /**
  8192. * @author mrdoob / http://mrdoob.com/
  8193. * @author alteredq / http://alteredqualia.com/
  8194. *
  8195. * parameters = {
  8196. * color: <hex>,
  8197. * ambient: <hex>,
  8198. * emissive: <hex>,
  8199. * specular: <hex>,
  8200. * shininess: <float>,
  8201. * opacity: <float>,
  8202. *
  8203. * map: new THREE.Texture( <Image> ),
  8204. *
  8205. * lightMap: new THREE.Texture( <Image> ),
  8206. *
  8207. * bumpMap: new THREE.Texture( <Image> ),
  8208. * bumpScale: <float>,
  8209. *
  8210. * normalMap: new THREE.Texture( <Image> ),
  8211. * normalScale: <Vector2>,
  8212. *
  8213. * specularMap: new THREE.Texture( <Image> ),
  8214. *
  8215. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8216. * combine: THREE.Multiply,
  8217. * reflectivity: <float>,
  8218. * refractionRatio: <float>,
  8219. *
  8220. * shading: THREE.SmoothShading,
  8221. * blending: THREE.NormalBlending,
  8222. * depthTest: <bool>,
  8223. * depthWrite: <bool>,
  8224. *
  8225. * wireframe: <boolean>,
  8226. * wireframeLinewidth: <float>,
  8227. *
  8228. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8229. *
  8230. * skinning: <bool>,
  8231. * morphTargets: <bool>,
  8232. * morphNormals: <bool>,
  8233. *
  8234. * fog: <bool>
  8235. * }
  8236. */
  8237. THREE.MeshPhongMaterial = function ( parameters ) {
  8238. THREE.Material.call( this );
  8239. this.color = new THREE.Color( 0xffffff ); // diffuse
  8240. this.ambient = new THREE.Color( 0xffffff );
  8241. this.emissive = new THREE.Color( 0x000000 );
  8242. this.specular = new THREE.Color( 0x111111 );
  8243. this.shininess = 30;
  8244. this.metal = false;
  8245. this.perPixel = true;
  8246. this.wrapAround = false;
  8247. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  8248. this.map = null;
  8249. this.lightMap = null;
  8250. this.bumpMap = null;
  8251. this.bumpScale = 1;
  8252. this.normalMap = null;
  8253. this.normalScale = new THREE.Vector2( 1, 1 );
  8254. this.specularMap = null;
  8255. this.envMap = null;
  8256. this.combine = THREE.MultiplyOperation;
  8257. this.reflectivity = 1;
  8258. this.refractionRatio = 0.98;
  8259. this.fog = true;
  8260. this.shading = THREE.SmoothShading;
  8261. this.wireframe = false;
  8262. this.wireframeLinewidth = 1;
  8263. this.wireframeLinecap = 'round';
  8264. this.wireframeLinejoin = 'round';
  8265. this.vertexColors = THREE.NoColors;
  8266. this.skinning = false;
  8267. this.morphTargets = false;
  8268. this.morphNormals = false;
  8269. this.setValues( parameters );
  8270. };
  8271. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  8272. THREE.MeshPhongMaterial.prototype.clone = function () {
  8273. var material = new THREE.MeshPhongMaterial();
  8274. THREE.Material.prototype.clone.call( this, material );
  8275. material.color.copy( this.color );
  8276. material.ambient.copy( this.ambient );
  8277. material.emissive.copy( this.emissive );
  8278. material.specular.copy( this.specular );
  8279. material.shininess = this.shininess;
  8280. material.metal = this.metal;
  8281. material.perPixel = this.perPixel;
  8282. material.wrapAround = this.wrapAround;
  8283. material.wrapRGB.copy( this.wrapRGB );
  8284. material.map = this.map;
  8285. material.lightMap = this.lightMap;
  8286. material.bumpMap = this.bumpMap;
  8287. material.bumpScale = this.bumpScale;
  8288. material.normalMap = this.normalMap;
  8289. material.normalScale.copy( this.normalScale );
  8290. material.specularMap = this.specularMap;
  8291. material.envMap = this.envMap;
  8292. material.combine = this.combine;
  8293. material.reflectivity = this.reflectivity;
  8294. material.refractionRatio = this.refractionRatio;
  8295. material.fog = this.fog;
  8296. material.shading = this.shading;
  8297. material.wireframe = this.wireframe;
  8298. material.wireframeLinewidth = this.wireframeLinewidth;
  8299. material.wireframeLinecap = this.wireframeLinecap;
  8300. material.wireframeLinejoin = this.wireframeLinejoin;
  8301. material.vertexColors = this.vertexColors;
  8302. material.skinning = this.skinning;
  8303. material.morphTargets = this.morphTargets;
  8304. material.morphNormals = this.morphNormals;
  8305. return material;
  8306. };
  8307. /**
  8308. * @author mrdoob / http://mrdoob.com/
  8309. * @author alteredq / http://alteredqualia.com/
  8310. *
  8311. * parameters = {
  8312. * opacity: <float>,
  8313. *
  8314. * blending: THREE.NormalBlending,
  8315. * depthTest: <bool>,
  8316. * depthWrite: <bool>,
  8317. *
  8318. * wireframe: <boolean>,
  8319. * wireframeLinewidth: <float>
  8320. * }
  8321. */
  8322. THREE.MeshDepthMaterial = function ( parameters ) {
  8323. THREE.Material.call( this );
  8324. this.wireframe = false;
  8325. this.wireframeLinewidth = 1;
  8326. this.setValues( parameters );
  8327. };
  8328. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  8329. THREE.MeshDepthMaterial.prototype.clone = function () {
  8330. var material = new THREE.MeshDepthMaterial();
  8331. THREE.Material.prototype.clone.call( this, material );
  8332. material.wireframe = this.wireframe;
  8333. material.wireframeLinewidth = this.wireframeLinewidth;
  8334. return material;
  8335. };
  8336. /**
  8337. * @author mrdoob / http://mrdoob.com/
  8338. *
  8339. * parameters = {
  8340. * opacity: <float>,
  8341. *
  8342. * shading: THREE.FlatShading,
  8343. * blending: THREE.NormalBlending,
  8344. * depthTest: <bool>,
  8345. * depthWrite: <bool>,
  8346. *
  8347. * wireframe: <boolean>,
  8348. * wireframeLinewidth: <float>
  8349. * }
  8350. */
  8351. THREE.MeshNormalMaterial = function ( parameters ) {
  8352. THREE.Material.call( this, parameters );
  8353. this.shading = THREE.FlatShading;
  8354. this.wireframe = false;
  8355. this.wireframeLinewidth = 1;
  8356. this.morphTargets = false;
  8357. this.setValues( parameters );
  8358. };
  8359. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  8360. THREE.MeshNormalMaterial.prototype.clone = function () {
  8361. var material = new THREE.MeshNormalMaterial();
  8362. THREE.Material.prototype.clone.call( this, material );
  8363. material.shading = this.shading;
  8364. material.wireframe = this.wireframe;
  8365. material.wireframeLinewidth = this.wireframeLinewidth;
  8366. return material;
  8367. };
  8368. /**
  8369. * @author mrdoob / http://mrdoob.com/
  8370. */
  8371. THREE.MeshFaceMaterial = function ( materials ) {
  8372. this.materials = materials instanceof Array ? materials : [];
  8373. };
  8374. THREE.MeshFaceMaterial.prototype.clone = function () {
  8375. var material = new THREE.MeshFaceMaterial();
  8376. for ( var i = 0; i < this.materials.length; i ++ ) {
  8377. material.materials.push( this.materials[ i ].clone() );
  8378. }
  8379. return material;
  8380. };
  8381. /**
  8382. * @author mrdoob / http://mrdoob.com/
  8383. * @author alteredq / http://alteredqualia.com/
  8384. *
  8385. * parameters = {
  8386. * color: <hex>,
  8387. * opacity: <float>,
  8388. * map: new THREE.Texture( <Image> ),
  8389. *
  8390. * size: <float>,
  8391. *
  8392. * blending: THREE.NormalBlending,
  8393. * depthTest: <bool>,
  8394. * depthWrite: <bool>,
  8395. *
  8396. * vertexColors: <bool>,
  8397. *
  8398. * fog: <bool>
  8399. * }
  8400. */
  8401. THREE.ParticleSystemMaterial = function ( parameters ) {
  8402. THREE.Material.call( this );
  8403. this.color = new THREE.Color( 0xffffff );
  8404. this.map = null;
  8405. this.size = 1;
  8406. this.sizeAttenuation = true;
  8407. this.vertexColors = false;
  8408. this.fog = true;
  8409. this.setValues( parameters );
  8410. };
  8411. THREE.ParticleSystemMaterial.prototype = Object.create( THREE.Material.prototype );
  8412. THREE.ParticleSystemMaterial.prototype.clone = function () {
  8413. var material = new THREE.ParticleSystemMaterial();
  8414. THREE.Material.prototype.clone.call( this, material );
  8415. material.color.copy( this.color );
  8416. material.map = this.map;
  8417. material.size = this.size;
  8418. material.sizeAttenuation = this.sizeAttenuation;
  8419. material.vertexColors = this.vertexColors;
  8420. material.fog = this.fog;
  8421. return material;
  8422. };
  8423. // backwards compatibility
  8424. THREE.ParticleBasicMaterial = THREE.ParticleSystemMaterial;
  8425. /**
  8426. * @author alteredq / http://alteredqualia.com/
  8427. *
  8428. * parameters = {
  8429. * fragmentShader: <string>,
  8430. * vertexShader: <string>,
  8431. *
  8432. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  8433. *
  8434. * defines: { "label" : "value" },
  8435. *
  8436. * shading: THREE.SmoothShading,
  8437. * blending: THREE.NormalBlending,
  8438. * depthTest: <bool>,
  8439. * depthWrite: <bool>,
  8440. *
  8441. * wireframe: <boolean>,
  8442. * wireframeLinewidth: <float>,
  8443. *
  8444. * lights: <bool>,
  8445. *
  8446. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8447. *
  8448. * skinning: <bool>,
  8449. * morphTargets: <bool>,
  8450. * morphNormals: <bool>,
  8451. *
  8452. * fog: <bool>
  8453. * }
  8454. */
  8455. THREE.ShaderMaterial = function ( parameters ) {
  8456. THREE.Material.call( this );
  8457. this.fragmentShader = "void main() {}";
  8458. this.vertexShader = "void main() {}";
  8459. this.uniforms = {};
  8460. this.defines = {};
  8461. this.attributes = null;
  8462. this.shading = THREE.SmoothShading;
  8463. this.linewidth = 1;
  8464. this.wireframe = false;
  8465. this.wireframeLinewidth = 1;
  8466. this.fog = false; // set to use scene fog
  8467. this.lights = false; // set to use scene lights
  8468. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  8469. this.skinning = false; // set to use skinning attribute streams
  8470. this.morphTargets = false; // set to use morph targets
  8471. this.morphNormals = false; // set to use morph normals
  8472. // When rendered geometry doesn't include these attributes but the material does,
  8473. // use these default values in WebGL. This avoids errors when buffer data is missing.
  8474. this.defaultAttributeValues = {
  8475. "color" : [ 1, 1, 1],
  8476. "uv" : [ 0, 0 ],
  8477. "uv2" : [ 0, 0 ]
  8478. };
  8479. // By default, bind position to attribute index 0. In WebGL, attribute 0
  8480. // should always be used to avoid potentially expensive emulation.
  8481. this.index0AttributeName = "position";
  8482. this.setValues( parameters );
  8483. };
  8484. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  8485. THREE.ShaderMaterial.prototype.clone = function () {
  8486. var material = new THREE.ShaderMaterial();
  8487. THREE.Material.prototype.clone.call( this, material );
  8488. material.fragmentShader = this.fragmentShader;
  8489. material.vertexShader = this.vertexShader;
  8490. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  8491. material.attributes = this.attributes;
  8492. material.defines = this.defines;
  8493. material.shading = this.shading;
  8494. material.wireframe = this.wireframe;
  8495. material.wireframeLinewidth = this.wireframeLinewidth;
  8496. material.fog = this.fog;
  8497. material.lights = this.lights;
  8498. material.vertexColors = this.vertexColors;
  8499. material.skinning = this.skinning;
  8500. material.morphTargets = this.morphTargets;
  8501. material.morphNormals = this.morphNormals;
  8502. return material;
  8503. };
  8504. /**
  8505. * @author alteredq / http://alteredqualia.com/
  8506. *
  8507. * parameters = {
  8508. * color: <hex>,
  8509. * opacity: <float>,
  8510. * map: new THREE.Texture( <Image> ),
  8511. *
  8512. * blending: THREE.NormalBlending,
  8513. * depthTest: <bool>,
  8514. * depthWrite: <bool>,
  8515. *
  8516. * uvOffset: new THREE.Vector2(),
  8517. * uvScale: new THREE.Vector2(),
  8518. *
  8519. * fog: <bool>
  8520. * }
  8521. */
  8522. THREE.SpriteMaterial = function ( parameters ) {
  8523. THREE.Material.call( this );
  8524. // defaults
  8525. this.color = new THREE.Color( 0xffffff );
  8526. this.map = null;
  8527. this.rotation = 0;
  8528. this.fog = false;
  8529. // set parameters
  8530. this.setValues( parameters );
  8531. };
  8532. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  8533. THREE.SpriteMaterial.prototype.clone = function () {
  8534. var material = new THREE.SpriteMaterial();
  8535. THREE.Material.prototype.clone.call( this, material );
  8536. material.color.copy( this.color );
  8537. material.map = this.map;
  8538. material.rotation = this.rotation;
  8539. material.fog = this.fog;
  8540. return material;
  8541. };
  8542. /**
  8543. * @author mrdoob / http://mrdoob.com/
  8544. *
  8545. * parameters = {
  8546. * color: <hex>,
  8547. * program: <function>,
  8548. * opacity: <float>,
  8549. * blending: THREE.NormalBlending
  8550. * }
  8551. */
  8552. THREE.SpriteCanvasMaterial = function ( parameters ) {
  8553. THREE.Material.call( this );
  8554. this.color = new THREE.Color( 0xffffff );
  8555. this.program = function ( context, color ) {};
  8556. this.setValues( parameters );
  8557. };
  8558. THREE.SpriteCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  8559. THREE.SpriteCanvasMaterial.prototype.clone = function () {
  8560. var material = new THREE.SpriteCanvasMaterial();
  8561. THREE.Material.prototype.clone.call( this, material );
  8562. material.color.copy( this.color );
  8563. material.program = this.program;
  8564. return material;
  8565. };
  8566. // backwards compatibility
  8567. THREE.ParticleCanvasMaterial = THREE.SpriteCanvasMaterial;
  8568. /**
  8569. * @author mrdoob / http://mrdoob.com/
  8570. * @author alteredq / http://alteredqualia.com/
  8571. * @author szimek / https://github.com/szimek/
  8572. */
  8573. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8574. this.id = THREE.TextureIdCount ++;
  8575. this.uuid = THREE.Math.generateUUID();
  8576. this.name = '';
  8577. this.image = image;
  8578. this.mipmaps = [];
  8579. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  8580. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  8581. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  8582. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  8583. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  8584. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  8585. this.format = format !== undefined ? format : THREE.RGBAFormat;
  8586. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  8587. this.offset = new THREE.Vector2( 0, 0 );
  8588. this.repeat = new THREE.Vector2( 1, 1 );
  8589. this.generateMipmaps = true;
  8590. this.premultiplyAlpha = false;
  8591. this.flipY = true;
  8592. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  8593. this._needsUpdate = false;
  8594. this.onUpdate = null;
  8595. };
  8596. THREE.Texture.prototype = {
  8597. constructor: THREE.Texture,
  8598. get needsUpdate () {
  8599. return this._needsUpdate;
  8600. },
  8601. set needsUpdate ( value ) {
  8602. if ( value === true ) this.update();
  8603. this._needsUpdate = value;
  8604. },
  8605. clone: function ( texture ) {
  8606. if ( texture === undefined ) texture = new THREE.Texture();
  8607. texture.image = this.image;
  8608. texture.mipmaps = this.mipmaps.slice(0);
  8609. texture.mapping = this.mapping;
  8610. texture.wrapS = this.wrapS;
  8611. texture.wrapT = this.wrapT;
  8612. texture.magFilter = this.magFilter;
  8613. texture.minFilter = this.minFilter;
  8614. texture.anisotropy = this.anisotropy;
  8615. texture.format = this.format;
  8616. texture.type = this.type;
  8617. texture.offset.copy( this.offset );
  8618. texture.repeat.copy( this.repeat );
  8619. texture.generateMipmaps = this.generateMipmaps;
  8620. texture.premultiplyAlpha = this.premultiplyAlpha;
  8621. texture.flipY = this.flipY;
  8622. texture.unpackAlignment = this.unpackAlignment;
  8623. return texture;
  8624. },
  8625. update: function () {
  8626. this.dispatchEvent( { type: 'update' } );
  8627. },
  8628. dispose: function () {
  8629. this.dispatchEvent( { type: 'dispose' } );
  8630. }
  8631. };
  8632. THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype );
  8633. THREE.TextureIdCount = 0;
  8634. /**
  8635. * @author alteredq / http://alteredqualia.com/
  8636. */
  8637. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8638. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8639. this.image = { width: width, height: height };
  8640. this.mipmaps = mipmaps;
  8641. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  8642. };
  8643. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  8644. THREE.CompressedTexture.prototype.clone = function () {
  8645. var texture = new THREE.CompressedTexture();
  8646. THREE.Texture.prototype.clone.call( this, texture );
  8647. return texture;
  8648. };
  8649. /**
  8650. * @author alteredq / http://alteredqualia.com/
  8651. */
  8652. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8653. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8654. this.image = { data: data, width: width, height: height };
  8655. };
  8656. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  8657. THREE.DataTexture.prototype.clone = function () {
  8658. var texture = new THREE.DataTexture();
  8659. THREE.Texture.prototype.clone.call( this, texture );
  8660. return texture;
  8661. };
  8662. /**
  8663. * @author alteredq / http://alteredqualia.com/
  8664. */
  8665. THREE.ParticleSystem = function ( geometry, material ) {
  8666. THREE.Object3D.call( this );
  8667. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8668. this.material = material !== undefined ? material : new THREE.ParticleSystemMaterial( { color: Math.random() * 0xffffff } );
  8669. this.sortParticles = false;
  8670. this.frustumCulled = false;
  8671. };
  8672. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  8673. THREE.ParticleSystem.prototype.clone = function ( object ) {
  8674. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  8675. object.sortParticles = this.sortParticles;
  8676. THREE.Object3D.prototype.clone.call( this, object );
  8677. return object;
  8678. };
  8679. /**
  8680. * @author mrdoob / http://mrdoob.com/
  8681. */
  8682. THREE.Line = function ( geometry, material, type ) {
  8683. THREE.Object3D.call( this );
  8684. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8685. this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  8686. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  8687. };
  8688. THREE.LineStrip = 0;
  8689. THREE.LinePieces = 1;
  8690. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  8691. THREE.Line.prototype.clone = function ( object ) {
  8692. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  8693. THREE.Object3D.prototype.clone.call( this, object );
  8694. return object;
  8695. };
  8696. /**
  8697. * @author mrdoob / http://mrdoob.com/
  8698. * @author alteredq / http://alteredqualia.com/
  8699. * @author mikael emtinger / http://gomo.se/
  8700. * @author jonobr1 / http://jonobr1.com/
  8701. */
  8702. THREE.Mesh = function ( geometry, material ) {
  8703. THREE.Object3D.call( this );
  8704. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  8705. this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  8706. this.updateMorphTargets();
  8707. };
  8708. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  8709. THREE.Mesh.prototype.updateMorphTargets = function () {
  8710. if ( this.geometry.morphTargets.length > 0 ) {
  8711. this.morphTargetBase = -1;
  8712. this.morphTargetForcedOrder = [];
  8713. this.morphTargetInfluences = [];
  8714. this.morphTargetDictionary = {};
  8715. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  8716. this.morphTargetInfluences.push( 0 );
  8717. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  8718. }
  8719. }
  8720. };
  8721. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  8722. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  8723. return this.morphTargetDictionary[ name ];
  8724. }
  8725. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  8726. return 0;
  8727. };
  8728. THREE.Mesh.prototype.clone = function ( object ) {
  8729. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  8730. THREE.Object3D.prototype.clone.call( this, object );
  8731. return object;
  8732. };
  8733. /**
  8734. * @author mikael emtinger / http://gomo.se/
  8735. * @author alteredq / http://alteredqualia.com/
  8736. */
  8737. THREE.Bone = function( belongsToSkin ) {
  8738. THREE.Object3D.call( this );
  8739. this.skin = belongsToSkin;
  8740. this.skinMatrix = new THREE.Matrix4();
  8741. };
  8742. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  8743. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  8744. // update local
  8745. if ( this.matrixAutoUpdate ) {
  8746. forceUpdate |= this.updateMatrix();
  8747. }
  8748. // update skin matrix
  8749. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  8750. if( parentSkinMatrix ) {
  8751. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  8752. } else {
  8753. this.skinMatrix.copy( this.matrix );
  8754. }
  8755. this.matrixWorldNeedsUpdate = false;
  8756. forceUpdate = true;
  8757. }
  8758. // update children
  8759. var child, i, l = this.children.length;
  8760. for ( i = 0; i < l; i ++ ) {
  8761. this.children[ i ].update( this.skinMatrix, forceUpdate );
  8762. }
  8763. };
  8764. /**
  8765. * @author mikael emtinger / http://gomo.se/
  8766. * @author alteredq / http://alteredqualia.com/
  8767. */
  8768. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  8769. THREE.Mesh.call( this, geometry, material );
  8770. //
  8771. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  8772. // init bones
  8773. this.identityMatrix = new THREE.Matrix4();
  8774. this.bones = [];
  8775. this.boneMatrices = [];
  8776. var b, bone, gbone, p, q, s;
  8777. if ( this.geometry && this.geometry.bones !== undefined ) {
  8778. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  8779. gbone = this.geometry.bones[ b ];
  8780. p = gbone.pos;
  8781. q = gbone.rotq;
  8782. s = gbone.scl;
  8783. bone = this.addBone();
  8784. bone.name = gbone.name;
  8785. bone.position.set( p[0], p[1], p[2] );
  8786. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  8787. if ( s !== undefined ) {
  8788. bone.scale.set( s[0], s[1], s[2] );
  8789. } else {
  8790. bone.scale.set( 1, 1, 1 );
  8791. }
  8792. }
  8793. for ( b = 0; b < this.bones.length; b ++ ) {
  8794. gbone = this.geometry.bones[ b ];
  8795. bone = this.bones[ b ];
  8796. if ( gbone.parent === -1 ) {
  8797. this.add( bone );
  8798. } else {
  8799. this.bones[ gbone.parent ].add( bone );
  8800. }
  8801. }
  8802. //
  8803. var nBones = this.bones.length;
  8804. if ( this.useVertexTexture ) {
  8805. // layout (1 matrix = 4 pixels)
  8806. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  8807. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  8808. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  8809. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  8810. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  8811. var size;
  8812. if ( nBones > 256 )
  8813. size = 64;
  8814. else if ( nBones > 64 )
  8815. size = 32;
  8816. else if ( nBones > 16 )
  8817. size = 16;
  8818. else
  8819. size = 8;
  8820. this.boneTextureWidth = size;
  8821. this.boneTextureHeight = size;
  8822. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  8823. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  8824. this.boneTexture.minFilter = THREE.NearestFilter;
  8825. this.boneTexture.magFilter = THREE.NearestFilter;
  8826. this.boneTexture.generateMipmaps = false;
  8827. this.boneTexture.flipY = false;
  8828. } else {
  8829. this.boneMatrices = new Float32Array( 16 * nBones );
  8830. }
  8831. this.pose();
  8832. }
  8833. };
  8834. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  8835. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  8836. if ( bone === undefined ) {
  8837. bone = new THREE.Bone( this );
  8838. }
  8839. this.bones.push( bone );
  8840. return bone;
  8841. };
  8842. THREE.SkinnedMesh.prototype.updateMatrixWorld = function () {
  8843. var offsetMatrix = new THREE.Matrix4();
  8844. return function ( force ) {
  8845. this.matrixAutoUpdate && this.updateMatrix();
  8846. // update matrixWorld
  8847. if ( this.matrixWorldNeedsUpdate || force ) {
  8848. if ( this.parent ) {
  8849. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  8850. } else {
  8851. this.matrixWorld.copy( this.matrix );
  8852. }
  8853. this.matrixWorldNeedsUpdate = false;
  8854. force = true;
  8855. }
  8856. // update children
  8857. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  8858. var child = this.children[ i ];
  8859. if ( child instanceof THREE.Bone ) {
  8860. child.update( this.identityMatrix, false );
  8861. } else {
  8862. child.updateMatrixWorld( true );
  8863. }
  8864. }
  8865. // make a snapshot of the bones' rest position
  8866. if ( this.boneInverses == undefined ) {
  8867. this.boneInverses = [];
  8868. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  8869. var inverse = new THREE.Matrix4();
  8870. inverse.getInverse( this.bones[ b ].skinMatrix );
  8871. this.boneInverses.push( inverse );
  8872. }
  8873. }
  8874. // flatten bone matrices to array
  8875. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  8876. // compute the offset between the current and the original transform;
  8877. // TODO: we could get rid of this multiplication step if the skinMatrix
  8878. // was already representing the offset; however, this requires some
  8879. // major changes to the animation system
  8880. offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  8881. offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  8882. }
  8883. if ( this.useVertexTexture ) {
  8884. this.boneTexture.needsUpdate = true;
  8885. }
  8886. };
  8887. }();
  8888. THREE.SkinnedMesh.prototype.pose = function () {
  8889. this.updateMatrixWorld( true );
  8890. this.normalizeSkinWeights();
  8891. };
  8892. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  8893. if ( this.geometry instanceof THREE.Geometry ) {
  8894. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  8895. var sw = this.geometry.skinWeights[ i ];
  8896. var scale = 1.0 / sw.lengthManhattan();
  8897. if ( scale !== Infinity ) {
  8898. sw.multiplyScalar( scale );
  8899. } else {
  8900. sw.set( 1 ); // this will be normalized by the shader anyway
  8901. }
  8902. }
  8903. } else {
  8904. // skinning weights assumed to be normalized for THREE.BufferGeometry
  8905. }
  8906. };
  8907. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  8908. if ( object === undefined ) {
  8909. object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  8910. }
  8911. THREE.Mesh.prototype.clone.call( this, object );
  8912. return object;
  8913. };
  8914. /**
  8915. * @author alteredq / http://alteredqualia.com/
  8916. */
  8917. THREE.MorphAnimMesh = function ( geometry, material ) {
  8918. THREE.Mesh.call( this, geometry, material );
  8919. // API
  8920. this.duration = 1000; // milliseconds
  8921. this.mirroredLoop = false;
  8922. this.time = 0;
  8923. // internals
  8924. this.lastKeyframe = 0;
  8925. this.currentKeyframe = 0;
  8926. this.direction = 1;
  8927. this.directionBackwards = false;
  8928. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  8929. };
  8930. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  8931. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  8932. this.startKeyframe = start;
  8933. this.endKeyframe = end;
  8934. this.length = this.endKeyframe - this.startKeyframe + 1;
  8935. };
  8936. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  8937. this.direction = 1;
  8938. this.directionBackwards = false;
  8939. };
  8940. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  8941. this.direction = -1;
  8942. this.directionBackwards = true;
  8943. };
  8944. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  8945. var geometry = this.geometry;
  8946. if ( ! geometry.animations ) geometry.animations = {};
  8947. var firstAnimation, animations = geometry.animations;
  8948. var pattern = /([a-z]+)(\d+)/;
  8949. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  8950. var morph = geometry.morphTargets[ i ];
  8951. var parts = morph.name.match( pattern );
  8952. if ( parts && parts.length > 1 ) {
  8953. var label = parts[ 1 ];
  8954. var num = parts[ 2 ];
  8955. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  8956. var animation = animations[ label ];
  8957. if ( i < animation.start ) animation.start = i;
  8958. if ( i > animation.end ) animation.end = i;
  8959. if ( ! firstAnimation ) firstAnimation = label;
  8960. }
  8961. }
  8962. geometry.firstAnimation = firstAnimation;
  8963. };
  8964. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  8965. if ( ! this.geometry.animations ) this.geometry.animations = {};
  8966. this.geometry.animations[ label ] = { start: start, end: end };
  8967. };
  8968. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  8969. var animation = this.geometry.animations[ label ];
  8970. if ( animation ) {
  8971. this.setFrameRange( animation.start, animation.end );
  8972. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  8973. this.time = 0;
  8974. } else {
  8975. console.warn( "animation[" + label + "] undefined" );
  8976. }
  8977. };
  8978. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  8979. var frameTime = this.duration / this.length;
  8980. this.time += this.direction * delta;
  8981. if ( this.mirroredLoop ) {
  8982. if ( this.time > this.duration || this.time < 0 ) {
  8983. this.direction *= -1;
  8984. if ( this.time > this.duration ) {
  8985. this.time = this.duration;
  8986. this.directionBackwards = true;
  8987. }
  8988. if ( this.time < 0 ) {
  8989. this.time = 0;
  8990. this.directionBackwards = false;
  8991. }
  8992. }
  8993. } else {
  8994. this.time = this.time % this.duration;
  8995. if ( this.time < 0 ) this.time += this.duration;
  8996. }
  8997. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  8998. if ( keyframe !== this.currentKeyframe ) {
  8999. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  9000. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  9001. this.morphTargetInfluences[ keyframe ] = 0;
  9002. this.lastKeyframe = this.currentKeyframe;
  9003. this.currentKeyframe = keyframe;
  9004. }
  9005. var mix = ( this.time % frameTime ) / frameTime;
  9006. if ( this.directionBackwards ) {
  9007. mix = 1 - mix;
  9008. }
  9009. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  9010. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  9011. };
  9012. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  9013. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  9014. object.duration = this.duration;
  9015. object.mirroredLoop = this.mirroredLoop;
  9016. object.time = this.time;
  9017. object.lastKeyframe = this.lastKeyframe;
  9018. object.currentKeyframe = this.currentKeyframe;
  9019. object.direction = this.direction;
  9020. object.directionBackwards = this.directionBackwards;
  9021. THREE.Mesh.prototype.clone.call( this, object );
  9022. return object;
  9023. };
  9024. /**
  9025. * @author mikael emtinger / http://gomo.se/
  9026. * @author alteredq / http://alteredqualia.com/
  9027. * @author mrdoob / http://mrdoob.com/
  9028. */
  9029. THREE.LOD = function () {
  9030. THREE.Object3D.call( this );
  9031. this.objects = [];
  9032. };
  9033. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  9034. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  9035. if ( distance === undefined ) distance = 0;
  9036. distance = Math.abs( distance );
  9037. for ( var l = 0; l < this.objects.length; l ++ ) {
  9038. if ( distance < this.objects[ l ].distance ) {
  9039. break;
  9040. }
  9041. }
  9042. this.objects.splice( l, 0, { distance: distance, object: object } );
  9043. this.add( object );
  9044. };
  9045. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  9046. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  9047. if ( distance < this.objects[ i ].distance ) {
  9048. break;
  9049. }
  9050. }
  9051. return this.objects[ i - 1 ].object;
  9052. };
  9053. THREE.LOD.prototype.update = function () {
  9054. var v1 = new THREE.Vector3();
  9055. var v2 = new THREE.Vector3();
  9056. return function ( camera ) {
  9057. if ( this.objects.length > 1 ) {
  9058. v1.setFromMatrixPosition( camera.matrixWorld );
  9059. v2.setFromMatrixPosition( this.matrixWorld );
  9060. var distance = v1.distanceTo( v2 );
  9061. this.objects[ 0 ].object.visible = true;
  9062. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  9063. if ( distance >= this.objects[ i ].distance ) {
  9064. this.objects[ i - 1 ].object.visible = false;
  9065. this.objects[ i ].object.visible = true;
  9066. } else {
  9067. break;
  9068. }
  9069. }
  9070. for( ; i < l; i ++ ) {
  9071. this.objects[ i ].object.visible = false;
  9072. }
  9073. }
  9074. };
  9075. }();
  9076. THREE.LOD.prototype.clone = function ( object ) {
  9077. if ( object === undefined ) object = new THREE.LOD();
  9078. THREE.Object3D.prototype.clone.call( this, object );
  9079. for ( var i = 0, l = this.objects.length; i < l; i ++ ) {
  9080. var x = this.objects[i].object.clone();
  9081. x.visible = i === 0;
  9082. object.addLevel( x, this.objects[i].distance );
  9083. }
  9084. return object;
  9085. };
  9086. /**
  9087. * @author mikael emtinger / http://gomo.se/
  9088. * @author alteredq / http://alteredqualia.com/
  9089. */
  9090. THREE.Sprite = function ( material ) {
  9091. THREE.Object3D.call( this );
  9092. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  9093. };
  9094. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  9095. /*
  9096. * Custom update matrix
  9097. */
  9098. THREE.Sprite.prototype.updateMatrix = function () {
  9099. this.matrix.compose( this.position, this.quaternion, this.scale );
  9100. this.matrixWorldNeedsUpdate = true;
  9101. };
  9102. THREE.Sprite.prototype.clone = function ( object ) {
  9103. if ( object === undefined ) object = new THREE.Sprite( this.material );
  9104. THREE.Object3D.prototype.clone.call( this, object );
  9105. return object;
  9106. };
  9107. // Backwards compatibility
  9108. THREE.Particle = THREE.Sprite;
  9109. /**
  9110. * @author mrdoob / http://mrdoob.com/
  9111. */
  9112. THREE.Scene = function () {
  9113. THREE.Object3D.call( this );
  9114. this.fog = null;
  9115. this.overrideMaterial = null;
  9116. this.autoUpdate = true; // checked by the renderer
  9117. this.matrixAutoUpdate = false;
  9118. this.__lights = [];
  9119. this.__objectsAdded = [];
  9120. this.__objectsRemoved = [];
  9121. };
  9122. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  9123. THREE.Scene.prototype.__addObject = function ( object ) {
  9124. if ( object instanceof THREE.Light ) {
  9125. if ( this.__lights.indexOf( object ) === - 1 ) {
  9126. this.__lights.push( object );
  9127. }
  9128. if ( object.target && object.target.parent === undefined ) {
  9129. this.add( object.target );
  9130. }
  9131. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  9132. this.__objectsAdded.push( object );
  9133. // check if previously removed
  9134. var i = this.__objectsRemoved.indexOf( object );
  9135. if ( i !== -1 ) {
  9136. this.__objectsRemoved.splice( i, 1 );
  9137. }
  9138. }
  9139. this.dispatchEvent( { type: 'objectAdded', object: object } );
  9140. object.dispatchEvent( { type: 'addedToScene', scene: this } );
  9141. for ( var c = 0; c < object.children.length; c ++ ) {
  9142. this.__addObject( object.children[ c ] );
  9143. }
  9144. };
  9145. THREE.Scene.prototype.__removeObject = function ( object ) {
  9146. if ( object instanceof THREE.Light ) {
  9147. var i = this.__lights.indexOf( object );
  9148. if ( i !== -1 ) {
  9149. this.__lights.splice( i, 1 );
  9150. }
  9151. if ( object.shadowCascadeArray ) {
  9152. for ( var x = 0; x < object.shadowCascadeArray.length; x ++ ) {
  9153. this.__removeObject( object.shadowCascadeArray[ x ] );
  9154. }
  9155. }
  9156. } else if ( !( object instanceof THREE.Camera ) ) {
  9157. this.__objectsRemoved.push( object );
  9158. // check if previously added
  9159. var i = this.__objectsAdded.indexOf( object );
  9160. if ( i !== -1 ) {
  9161. this.__objectsAdded.splice( i, 1 );
  9162. }
  9163. }
  9164. this.dispatchEvent( { type: 'objectRemoved', object: object } );
  9165. object.dispatchEvent( { type: 'removedFromScene', scene: this } );
  9166. for ( var c = 0; c < object.children.length; c ++ ) {
  9167. this.__removeObject( object.children[ c ] );
  9168. }
  9169. };
  9170. THREE.Scene.prototype.clone = function ( object ) {
  9171. if ( object === undefined ) object = new THREE.Scene();
  9172. THREE.Object3D.prototype.clone.call(this, object);
  9173. if ( this.fog !== null ) object.fog = this.fog.clone();
  9174. if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone();
  9175. object.autoUpdate = this.autoUpdate;
  9176. object.matrixAutoUpdate = this.matrixAutoUpdate;
  9177. return object;
  9178. };
  9179. /**
  9180. * @author mrdoob / http://mrdoob.com/
  9181. * @author alteredq / http://alteredqualia.com/
  9182. */
  9183. THREE.Fog = function ( color, near, far ) {
  9184. this.name = '';
  9185. this.color = new THREE.Color( color );
  9186. this.near = ( near !== undefined ) ? near : 1;
  9187. this.far = ( far !== undefined ) ? far : 1000;
  9188. };
  9189. THREE.Fog.prototype.clone = function () {
  9190. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  9191. };
  9192. /**
  9193. * @author mrdoob / http://mrdoob.com/
  9194. * @author alteredq / http://alteredqualia.com/
  9195. */
  9196. THREE.FogExp2 = function ( color, density ) {
  9197. this.name = '';
  9198. this.color = new THREE.Color( color );
  9199. this.density = ( density !== undefined ) ? density : 0.00025;
  9200. };
  9201. THREE.FogExp2.prototype.clone = function () {
  9202. return new THREE.FogExp2( this.color.getHex(), this.density );
  9203. };
  9204. /**
  9205. * @author mrdoob / http://mrdoob.com/
  9206. */
  9207. THREE.CanvasRenderer = function ( parameters ) {
  9208. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  9209. var smoothstep = THREE.Math.smoothstep;
  9210. parameters = parameters || {};
  9211. var _this = this,
  9212. _renderData, _elements, _lights,
  9213. _projector = new THREE.Projector(),
  9214. _canvas = parameters.canvas !== undefined
  9215. ? parameters.canvas
  9216. : document.createElement( 'canvas' ),
  9217. _canvasWidth = _canvas.width,
  9218. _canvasHeight = _canvas.height,
  9219. _canvasWidthHalf = Math.floor( _canvasWidth / 2 ),
  9220. _canvasHeightHalf = Math.floor( _canvasHeight / 2 ),
  9221. _context = _canvas.getContext( '2d' ),
  9222. _clearColor = new THREE.Color( 0x000000 ),
  9223. _clearAlpha = 0,
  9224. _contextGlobalAlpha = 1,
  9225. _contextGlobalCompositeOperation = 0,
  9226. _contextStrokeStyle = null,
  9227. _contextFillStyle = null,
  9228. _contextLineWidth = null,
  9229. _contextLineCap = null,
  9230. _contextLineJoin = null,
  9231. _contextDashSize = null,
  9232. _contextGapSize = 0,
  9233. _camera,
  9234. _v1, _v2, _v3, _v4,
  9235. _v5 = new THREE.RenderableVertex(),
  9236. _v6 = new THREE.RenderableVertex(),
  9237. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  9238. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  9239. _color = new THREE.Color(),
  9240. _color1 = new THREE.Color(),
  9241. _color2 = new THREE.Color(),
  9242. _color3 = new THREE.Color(),
  9243. _color4 = new THREE.Color(),
  9244. _diffuseColor = new THREE.Color(),
  9245. _emissiveColor = new THREE.Color(),
  9246. _lightColor = new THREE.Color(),
  9247. _patterns = {},
  9248. _near, _far,
  9249. _image, _uvs,
  9250. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  9251. _clipBox = new THREE.Box2(),
  9252. _clearBox = new THREE.Box2(),
  9253. _elemBox = new THREE.Box2(),
  9254. _ambientLight = new THREE.Color(),
  9255. _directionalLights = new THREE.Color(),
  9256. _pointLights = new THREE.Color(),
  9257. _vector3 = new THREE.Vector3(), // Needed for PointLight
  9258. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  9259. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  9260. _pixelMap = document.createElement( 'canvas' );
  9261. _pixelMap.width = _pixelMap.height = 2;
  9262. _pixelMapContext = _pixelMap.getContext( '2d' );
  9263. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  9264. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  9265. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  9266. _pixelMapData = _pixelMapImage.data;
  9267. _gradientMap = document.createElement( 'canvas' );
  9268. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  9269. _gradientMapContext = _gradientMap.getContext( '2d' );
  9270. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  9271. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  9272. _gradientMapQuality --; // Fix UVs
  9273. // dash+gap fallbacks for Firefox and everything else
  9274. if ( _context.setLineDash === undefined ) {
  9275. if ( _context.mozDash !== undefined ) {
  9276. _context.setLineDash = function ( values ) {
  9277. _context.mozDash = values[ 0 ] !== null ? values : null;
  9278. }
  9279. } else {
  9280. _context.setLineDash = function () {}
  9281. }
  9282. }
  9283. this.domElement = _canvas;
  9284. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  9285. ? parameters.devicePixelRatio
  9286. : self.devicePixelRatio !== undefined
  9287. ? self.devicePixelRatio
  9288. : 1;
  9289. this.autoClear = true;
  9290. this.sortObjects = true;
  9291. this.sortElements = true;
  9292. this.info = {
  9293. render: {
  9294. vertices: 0,
  9295. faces: 0
  9296. }
  9297. }
  9298. // WebGLRenderer compatibility
  9299. this.supportsVertexTextures = function () {};
  9300. this.setFaceCulling = function () {};
  9301. this.setSize = function ( width, height, updateStyle ) {
  9302. _canvasWidth = width * this.devicePixelRatio;
  9303. _canvasHeight = height * this.devicePixelRatio;
  9304. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  9305. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  9306. _canvas.width = _canvasWidth;
  9307. _canvas.height = _canvasHeight;
  9308. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  9309. _canvas.style.width = width + 'px';
  9310. _canvas.style.height = height + 'px';
  9311. }
  9312. _clipBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf ),
  9313. _clipBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9314. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  9315. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9316. _contextGlobalAlpha = 1;
  9317. _contextGlobalCompositeOperation = 0;
  9318. _contextStrokeStyle = null;
  9319. _contextFillStyle = null;
  9320. _contextLineWidth = null;
  9321. _contextLineCap = null;
  9322. _contextLineJoin = null;
  9323. };
  9324. this.setClearColor = function ( color, alpha ) {
  9325. _clearColor.set( color );
  9326. _clearAlpha = alpha !== undefined ? alpha : 1;
  9327. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  9328. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9329. };
  9330. this.setClearColorHex = function ( hex, alpha ) {
  9331. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  9332. this.setClearColor( hex, alpha );
  9333. };
  9334. this.getMaxAnisotropy = function () {
  9335. return 0;
  9336. };
  9337. this.clear = function () {
  9338. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  9339. if ( _clearBox.empty() === false ) {
  9340. _clearBox.intersect( _clipBox );
  9341. _clearBox.expandByScalar( 2 );
  9342. if ( _clearAlpha < 1 ) {
  9343. _context.clearRect(
  9344. _clearBox.min.x | 0,
  9345. _clearBox.min.y | 0,
  9346. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9347. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9348. );
  9349. }
  9350. if ( _clearAlpha > 0 ) {
  9351. setBlending( THREE.NormalBlending );
  9352. setOpacity( 1 );
  9353. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearAlpha + ')' );
  9354. _context.fillRect(
  9355. _clearBox.min.x | 0,
  9356. _clearBox.min.y | 0,
  9357. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  9358. ( _clearBox.max.y - _clearBox.min.y ) | 0
  9359. );
  9360. }
  9361. _clearBox.makeEmpty();
  9362. }
  9363. };
  9364. // compatibility
  9365. this.clearColor = function () {};
  9366. this.clearDepth = function () {};
  9367. this.clearStencil = function () {};
  9368. this.render = function ( scene, camera ) {
  9369. if ( camera instanceof THREE.Camera === false ) {
  9370. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  9371. return;
  9372. }
  9373. if ( this.autoClear === true ) this.clear();
  9374. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  9375. _this.info.render.vertices = 0;
  9376. _this.info.render.faces = 0;
  9377. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  9378. _elements = _renderData.elements;
  9379. _lights = _renderData.lights;
  9380. _camera = camera;
  9381. /* DEBUG
  9382. setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
  9383. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  9384. */
  9385. calculateLights();
  9386. for ( var e = 0, el = _elements.length; e < el; e++ ) {
  9387. var element = _elements[ e ];
  9388. var material = element.material;
  9389. if ( material === undefined || material.visible === false ) continue;
  9390. _elemBox.makeEmpty();
  9391. if ( element instanceof THREE.RenderableSprite ) {
  9392. _v1 = element;
  9393. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  9394. renderSprite( _v1, element, material );
  9395. } else if ( element instanceof THREE.RenderableLine ) {
  9396. _v1 = element.v1; _v2 = element.v2;
  9397. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9398. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9399. _elemBox.setFromPoints( [
  9400. _v1.positionScreen,
  9401. _v2.positionScreen
  9402. ] );
  9403. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9404. renderLine( _v1, _v2, element, material );
  9405. }
  9406. } else if ( element instanceof THREE.RenderableFace3 ) {
  9407. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  9408. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  9409. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  9410. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  9411. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  9412. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  9413. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  9414. if ( material.overdraw > 0 ) {
  9415. expand( _v1.positionScreen, _v2.positionScreen, material.overdraw );
  9416. expand( _v2.positionScreen, _v3.positionScreen, material.overdraw );
  9417. expand( _v3.positionScreen, _v1.positionScreen, material.overdraw );
  9418. }
  9419. _elemBox.setFromPoints( [
  9420. _v1.positionScreen,
  9421. _v2.positionScreen,
  9422. _v3.positionScreen
  9423. ] );
  9424. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9425. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material );
  9426. }
  9427. }
  9428. /* DEBUG
  9429. setLineWidth( 1 );
  9430. setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
  9431. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  9432. */
  9433. _clearBox.union( _elemBox );
  9434. }
  9435. /* DEBUG
  9436. setLineWidth( 1 );
  9437. setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
  9438. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  9439. */
  9440. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  9441. };
  9442. //
  9443. function calculateLights() {
  9444. _ambientLight.setRGB( 0, 0, 0 );
  9445. _directionalLights.setRGB( 0, 0, 0 );
  9446. _pointLights.setRGB( 0, 0, 0 );
  9447. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9448. var light = _lights[ l ];
  9449. var lightColor = light.color;
  9450. if ( light instanceof THREE.AmbientLight ) {
  9451. _ambientLight.add( lightColor );
  9452. } else if ( light instanceof THREE.DirectionalLight ) {
  9453. // for sprites
  9454. _directionalLights.add( lightColor );
  9455. } else if ( light instanceof THREE.PointLight ) {
  9456. // for sprites
  9457. _pointLights.add( lightColor );
  9458. }
  9459. }
  9460. }
  9461. function calculateLight( position, normal, color ) {
  9462. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9463. var light = _lights[ l ];
  9464. _lightColor.copy( light.color );
  9465. if ( light instanceof THREE.DirectionalLight ) {
  9466. var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld ).normalize();
  9467. var amount = normal.dot( lightPosition );
  9468. if ( amount <= 0 ) continue;
  9469. amount *= light.intensity;
  9470. color.add( _lightColor.multiplyScalar( amount ) );
  9471. } else if ( light instanceof THREE.PointLight ) {
  9472. var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld );
  9473. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  9474. if ( amount <= 0 ) continue;
  9475. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  9476. if ( amount == 0 ) continue;
  9477. amount *= light.intensity;
  9478. color.add( _lightColor.multiplyScalar( amount ) );
  9479. }
  9480. }
  9481. }
  9482. function renderSprite( v1, element, material ) {
  9483. setOpacity( material.opacity );
  9484. setBlending( material.blending );
  9485. var scaleX = element.scale.x * _canvasWidthHalf;
  9486. var scaleY = element.scale.y * _canvasHeightHalf;
  9487. var dist = 0.5 * Math.sqrt( scaleX * scaleX + scaleY * scaleY ); // allow for rotated sprite
  9488. _elemBox.min.set( v1.x - dist, v1.y - dist );
  9489. _elemBox.max.set( v1.x + dist, v1.y + dist );
  9490. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  9491. _elemBox.makeEmpty();
  9492. return;
  9493. }
  9494. if ( material instanceof THREE.SpriteMaterial ||
  9495. material instanceof THREE.ParticleSystemMaterial ) { // Backwards compatibility
  9496. var texture = material.map;
  9497. if ( texture !== null ) {
  9498. if ( texture.hasEventListener( 'update', onTextureUpdate ) === false ) {
  9499. if ( texture.image !== undefined && texture.image.width > 0 ) {
  9500. textureToPattern( texture );
  9501. }
  9502. texture.addEventListener( 'update', onTextureUpdate );
  9503. }
  9504. var pattern = _patterns[ texture.id ];
  9505. if ( pattern !== undefined ) {
  9506. setFillStyle( pattern );
  9507. } else {
  9508. setFillStyle( 'rgba( 0, 0, 0, 1 )' );
  9509. }
  9510. //
  9511. var bitmap = texture.image;
  9512. var ox = bitmap.width * texture.offset.x;
  9513. var oy = bitmap.height * texture.offset.y;
  9514. var sx = bitmap.width * texture.repeat.x;
  9515. var sy = bitmap.height * texture.repeat.y;
  9516. var cx = scaleX / sx;
  9517. var cy = scaleY / sy;
  9518. _context.save();
  9519. _context.translate( v1.x, v1.y );
  9520. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  9521. _context.translate( - scaleX / 2, - scaleY / 2 );
  9522. _context.scale( cx, cy );
  9523. _context.translate( - ox, - oy );
  9524. _context.fillRect( ox, oy, sx, sy );
  9525. _context.restore();
  9526. } else { // no texture
  9527. setFillStyle( material.color.getStyle() );
  9528. _context.save();
  9529. _context.translate( v1.x, v1.y );
  9530. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  9531. _context.scale( scaleX, - scaleY );
  9532. _context.fillRect( - 0.5, - 0.5, 1, 1 );
  9533. _context.restore();
  9534. }
  9535. } else if ( material instanceof THREE.SpriteCanvasMaterial ) {
  9536. setStrokeStyle( material.color.getStyle() );
  9537. setFillStyle( material.color.getStyle() );
  9538. _context.save();
  9539. _context.translate( v1.x, v1.y );
  9540. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  9541. _context.scale( scaleX, scaleY );
  9542. material.program( _context );
  9543. _context.restore();
  9544. }
  9545. /* DEBUG
  9546. setStrokeStyle( 'rgb(255,255,0)' );
  9547. _context.beginPath();
  9548. _context.moveTo( v1.x - 10, v1.y );
  9549. _context.lineTo( v1.x + 10, v1.y );
  9550. _context.moveTo( v1.x, v1.y - 10 );
  9551. _context.lineTo( v1.x, v1.y + 10 );
  9552. _context.stroke();
  9553. */
  9554. }
  9555. function renderLine( v1, v2, element, material ) {
  9556. setOpacity( material.opacity );
  9557. setBlending( material.blending );
  9558. _context.beginPath();
  9559. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  9560. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  9561. if ( material instanceof THREE.LineBasicMaterial ) {
  9562. setLineWidth( material.linewidth );
  9563. setLineCap( material.linecap );
  9564. setLineJoin( material.linejoin );
  9565. if ( material.vertexColors !== THREE.VertexColors ) {
  9566. setStrokeStyle( material.color.getStyle() );
  9567. } else {
  9568. var colorStyle1 = element.vertexColors[0].getStyle();
  9569. var colorStyle2 = element.vertexColors[1].getStyle();
  9570. if ( colorStyle1 === colorStyle2 ) {
  9571. setStrokeStyle( colorStyle1 );
  9572. } else {
  9573. try {
  9574. var grad = _context.createLinearGradient(
  9575. v1.positionScreen.x,
  9576. v1.positionScreen.y,
  9577. v2.positionScreen.x,
  9578. v2.positionScreen.y
  9579. );
  9580. grad.addColorStop( 0, colorStyle1 );
  9581. grad.addColorStop( 1, colorStyle2 );
  9582. } catch ( exception ) {
  9583. grad = colorStyle1;
  9584. }
  9585. setStrokeStyle( grad );
  9586. }
  9587. }
  9588. _context.stroke();
  9589. _elemBox.expandByScalar( material.linewidth * 2 );
  9590. } else if ( material instanceof THREE.LineDashedMaterial ) {
  9591. setLineWidth( material.linewidth );
  9592. setLineCap( material.linecap );
  9593. setLineJoin( material.linejoin );
  9594. setStrokeStyle( material.color.getStyle() );
  9595. setDashAndGap( material.dashSize, material.gapSize );
  9596. _context.stroke();
  9597. _elemBox.expandByScalar( material.linewidth * 2 );
  9598. setDashAndGap( null, null );
  9599. }
  9600. }
  9601. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material ) {
  9602. _this.info.render.vertices += 3;
  9603. _this.info.render.faces ++;
  9604. setOpacity( material.opacity );
  9605. setBlending( material.blending );
  9606. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  9607. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  9608. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  9609. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  9610. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) {
  9611. _diffuseColor.copy( material.color );
  9612. _emissiveColor.copy( material.emissive );
  9613. if ( material.vertexColors === THREE.FaceColors ) {
  9614. _diffuseColor.multiply( element.color );
  9615. }
  9616. if ( material.wireframe === false && material.shading === THREE.SmoothShading && element.vertexNormalsLength === 3 ) {
  9617. _color1.copy( _ambientLight );
  9618. _color2.copy( _ambientLight );
  9619. _color3.copy( _ambientLight );
  9620. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  9621. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  9622. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color3 );
  9623. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  9624. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  9625. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  9626. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9627. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9628. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9629. } else {
  9630. _color.copy( _ambientLight );
  9631. calculateLight( element.centroidModel, element.normalModel, _color );
  9632. _color.multiply( _diffuseColor ).add( _emissiveColor );
  9633. material.wireframe === true
  9634. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9635. : fillPath( _color );
  9636. }
  9637. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  9638. if ( material.map !== null ) {
  9639. if ( material.map.mapping instanceof THREE.UVMapping ) {
  9640. _uvs = element.uvs[ 0 ];
  9641. 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 );
  9642. }
  9643. } else if ( material.envMap !== null ) {
  9644. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  9645. _vector3.copy( element.vertexNormalsModelView[ uv1 ] );
  9646. _uv1x = 0.5 * _vector3.x + 0.5;
  9647. _uv1y = 0.5 * _vector3.y + 0.5;
  9648. _vector3.copy( element.vertexNormalsModelView[ uv2 ] );
  9649. _uv2x = 0.5 * _vector3.x + 0.5;
  9650. _uv2y = 0.5 * _vector3.y + 0.5;
  9651. _vector3.copy( element.vertexNormalsModelView[ uv3 ] );
  9652. _uv3x = 0.5 * _vector3.x + 0.5;
  9653. _uv3y = 0.5 * _vector3.y + 0.5;
  9654. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  9655. }/* else if ( material.envMap.mapping === THREE.SphericalRefractionMapping ) {
  9656. }*/
  9657. } else {
  9658. _color.copy( material.color );
  9659. if ( material.vertexColors === THREE.FaceColors ) {
  9660. _color.multiply( element.color );
  9661. }
  9662. material.wireframe === true
  9663. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9664. : fillPath( _color );
  9665. }
  9666. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  9667. _near = _camera.near;
  9668. _far = _camera.far;
  9669. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  9670. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  9671. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  9672. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9673. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9674. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9675. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  9676. var normal;
  9677. if ( material.shading === THREE.FlatShading ) {
  9678. normal = element.normalModelView;
  9679. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9680. material.wireframe === true
  9681. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9682. : fillPath( _color );
  9683. } else if ( material.shading === THREE.SmoothShading ) {
  9684. normal = element.vertexNormalsModelView[ uv1 ];
  9685. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9686. normal = element.vertexNormalsModelView[ uv2 ];
  9687. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9688. normal = element.vertexNormalsModelView[ uv3 ];
  9689. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9690. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9691. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9692. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9693. }
  9694. }
  9695. }
  9696. //
  9697. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  9698. _context.beginPath();
  9699. _context.moveTo( x0, y0 );
  9700. _context.lineTo( x1, y1 );
  9701. _context.lineTo( x2, y2 );
  9702. _context.closePath();
  9703. }
  9704. function strokePath( color, linewidth, linecap, linejoin ) {
  9705. setLineWidth( linewidth );
  9706. setLineCap( linecap );
  9707. setLineJoin( linejoin );
  9708. setStrokeStyle( color.getStyle() );
  9709. _context.stroke();
  9710. _elemBox.expandByScalar( linewidth * 2 );
  9711. }
  9712. function fillPath( color ) {
  9713. setFillStyle( color.getStyle() );
  9714. _context.fill();
  9715. }
  9716. function onTextureUpdate ( event ) {
  9717. textureToPattern( event.target );
  9718. }
  9719. function textureToPattern( texture ) {
  9720. var repeatX = texture.wrapS === THREE.RepeatWrapping;
  9721. var repeatY = texture.wrapT === THREE.RepeatWrapping;
  9722. var image = texture.image;
  9723. var canvas = document.createElement( 'canvas' );
  9724. canvas.width = image.width;
  9725. canvas.height = image.height;
  9726. var context = canvas.getContext( '2d' );
  9727. context.setTransform( 1, 0, 0, - 1, 0, image.height );
  9728. context.drawImage( image, 0, 0 );
  9729. _patterns[ texture.id ] = _context.createPattern(
  9730. canvas, repeatX === true && repeatY === true
  9731. ? 'repeat'
  9732. : repeatX === true && repeatY === false
  9733. ? 'repeat-x'
  9734. : repeatX === false && repeatY === true
  9735. ? 'repeat-y'
  9736. : 'no-repeat'
  9737. );
  9738. }
  9739. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  9740. if ( texture instanceof THREE.DataTexture ) return;
  9741. if ( texture.hasEventListener( 'update', onTextureUpdate ) === false ) {
  9742. if ( texture.image !== undefined && texture.image.width > 0 ) {
  9743. textureToPattern( texture );
  9744. }
  9745. texture.addEventListener( 'update', onTextureUpdate );
  9746. }
  9747. var pattern = _patterns[ texture.id ];
  9748. if ( pattern !== undefined ) {
  9749. setFillStyle( pattern );
  9750. } else {
  9751. setFillStyle( 'rgba(0,0,0,1)' );
  9752. _context.fill();
  9753. return;
  9754. }
  9755. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9756. var a, b, c, d, e, f, det, idet,
  9757. offsetX = texture.offset.x / texture.repeat.x,
  9758. offsetY = texture.offset.y / texture.repeat.y,
  9759. width = texture.image.width * texture.repeat.x,
  9760. height = texture.image.height * texture.repeat.y;
  9761. u0 = ( u0 + offsetX ) * width;
  9762. v0 = ( v0 + offsetY ) * height;
  9763. u1 = ( u1 + offsetX ) * width;
  9764. v1 = ( v1 + offsetY ) * height;
  9765. u2 = ( u2 + offsetX ) * width;
  9766. v2 = ( v2 + offsetY ) * height;
  9767. x1 -= x0; y1 -= y0;
  9768. x2 -= x0; y2 -= y0;
  9769. u1 -= u0; v1 -= v0;
  9770. u2 -= u0; v2 -= v0;
  9771. det = u1 * v2 - u2 * v1;
  9772. if ( det === 0 ) return;
  9773. idet = 1 / det;
  9774. a = ( v2 * x1 - v1 * x2 ) * idet;
  9775. b = ( v2 * y1 - v1 * y2 ) * idet;
  9776. c = ( u1 * x2 - u2 * x1 ) * idet;
  9777. d = ( u1 * y2 - u2 * y1 ) * idet;
  9778. e = x0 - a * u0 - c * v0;
  9779. f = y0 - b * u0 - d * v0;
  9780. _context.save();
  9781. _context.transform( a, b, c, d, e, f );
  9782. _context.fill();
  9783. _context.restore();
  9784. }
  9785. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  9786. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9787. var a, b, c, d, e, f, det, idet,
  9788. width = image.width - 1,
  9789. height = image.height - 1;
  9790. u0 *= width; v0 *= height;
  9791. u1 *= width; v1 *= height;
  9792. u2 *= width; v2 *= height;
  9793. x1 -= x0; y1 -= y0;
  9794. x2 -= x0; y2 -= y0;
  9795. u1 -= u0; v1 -= v0;
  9796. u2 -= u0; v2 -= v0;
  9797. det = u1 * v2 - u2 * v1;
  9798. idet = 1 / det;
  9799. a = ( v2 * x1 - v1 * x2 ) * idet;
  9800. b = ( v2 * y1 - v1 * y2 ) * idet;
  9801. c = ( u1 * x2 - u2 * x1 ) * idet;
  9802. d = ( u1 * y2 - u2 * y1 ) * idet;
  9803. e = x0 - a * u0 - c * v0;
  9804. f = y0 - b * u0 - d * v0;
  9805. _context.save();
  9806. _context.transform( a, b, c, d, e, f );
  9807. _context.clip();
  9808. _context.drawImage( image, 0, 0 );
  9809. _context.restore();
  9810. }
  9811. function getGradientTexture( color1, color2, color3, color4 ) {
  9812. // http://mrdoob.com/blog/post/710
  9813. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  9814. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  9815. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  9816. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  9817. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  9818. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  9819. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  9820. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  9821. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  9822. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  9823. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  9824. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  9825. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  9826. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  9827. return _gradientMap;
  9828. }
  9829. // Hide anti-alias gaps
  9830. function expand( v1, v2, pixels ) {
  9831. var x = v2.x - v1.x, y = v2.y - v1.y,
  9832. det = x * x + y * y, idet;
  9833. if ( det === 0 ) return;
  9834. idet = pixels / Math.sqrt( det );
  9835. x *= idet; y *= idet;
  9836. v2.x += x; v2.y += y;
  9837. v1.x -= x; v1.y -= y;
  9838. }
  9839. // Context cached methods.
  9840. function setOpacity( value ) {
  9841. if ( _contextGlobalAlpha !== value ) {
  9842. _context.globalAlpha = value;
  9843. _contextGlobalAlpha = value;
  9844. }
  9845. }
  9846. function setBlending( value ) {
  9847. if ( _contextGlobalCompositeOperation !== value ) {
  9848. if ( value === THREE.NormalBlending ) {
  9849. _context.globalCompositeOperation = 'source-over';
  9850. } else if ( value === THREE.AdditiveBlending ) {
  9851. _context.globalCompositeOperation = 'lighter';
  9852. } else if ( value === THREE.SubtractiveBlending ) {
  9853. _context.globalCompositeOperation = 'darker';
  9854. }
  9855. _contextGlobalCompositeOperation = value;
  9856. }
  9857. }
  9858. function setLineWidth( value ) {
  9859. if ( _contextLineWidth !== value ) {
  9860. _context.lineWidth = value;
  9861. _contextLineWidth = value;
  9862. }
  9863. }
  9864. function setLineCap( value ) {
  9865. // "butt", "round", "square"
  9866. if ( _contextLineCap !== value ) {
  9867. _context.lineCap = value;
  9868. _contextLineCap = value;
  9869. }
  9870. }
  9871. function setLineJoin( value ) {
  9872. // "round", "bevel", "miter"
  9873. if ( _contextLineJoin !== value ) {
  9874. _context.lineJoin = value;
  9875. _contextLineJoin = value;
  9876. }
  9877. }
  9878. function setStrokeStyle( value ) {
  9879. if ( _contextStrokeStyle !== value ) {
  9880. _context.strokeStyle = value;
  9881. _contextStrokeStyle = value;
  9882. }
  9883. }
  9884. function setFillStyle( value ) {
  9885. if ( _contextFillStyle !== value ) {
  9886. _context.fillStyle = value;
  9887. _contextFillStyle = value;
  9888. }
  9889. }
  9890. function setDashAndGap( dashSizeValue, gapSizeValue ) {
  9891. if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) {
  9892. _context.setLineDash( [ dashSizeValue, gapSizeValue ] );
  9893. _contextDashSize = dashSizeValue;
  9894. _contextGapSize = gapSizeValue;
  9895. }
  9896. }
  9897. };
  9898. /**
  9899. * Shader chunks for WebLG Shader library
  9900. *
  9901. * @author alteredq / http://alteredqualia.com/
  9902. * @author mrdoob / http://mrdoob.com/
  9903. * @author mikael emtinger / http://gomo.se/
  9904. */
  9905. THREE.ShaderChunk = {
  9906. // FOG
  9907. fog_pars_fragment: [
  9908. "#ifdef USE_FOG",
  9909. "uniform vec3 fogColor;",
  9910. "#ifdef FOG_EXP2",
  9911. "uniform float fogDensity;",
  9912. "#else",
  9913. "uniform float fogNear;",
  9914. "uniform float fogFar;",
  9915. "#endif",
  9916. "#endif"
  9917. ].join("\n"),
  9918. fog_fragment: [
  9919. "#ifdef USE_FOG",
  9920. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  9921. "#ifdef FOG_EXP2",
  9922. "const float LOG2 = 1.442695;",
  9923. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  9924. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  9925. "#else",
  9926. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  9927. "#endif",
  9928. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  9929. "#endif"
  9930. ].join("\n"),
  9931. // ENVIRONMENT MAP
  9932. envmap_pars_fragment: [
  9933. "#ifdef USE_ENVMAP",
  9934. "uniform float reflectivity;",
  9935. "uniform samplerCube envMap;",
  9936. "uniform float flipEnvMap;",
  9937. "uniform int combine;",
  9938. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9939. "uniform bool useRefract;",
  9940. "uniform float refractionRatio;",
  9941. "#else",
  9942. "varying vec3 vReflect;",
  9943. "#endif",
  9944. "#endif"
  9945. ].join("\n"),
  9946. envmap_fragment: [
  9947. "#ifdef USE_ENVMAP",
  9948. "vec3 reflectVec;",
  9949. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9950. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  9951. "if ( useRefract ) {",
  9952. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  9953. "} else { ",
  9954. "reflectVec = reflect( cameraToVertex, normal );",
  9955. "}",
  9956. "#else",
  9957. "reflectVec = vReflect;",
  9958. "#endif",
  9959. "#ifdef DOUBLE_SIDED",
  9960. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9961. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9962. "#else",
  9963. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9964. "#endif",
  9965. "#ifdef GAMMA_INPUT",
  9966. "cubeColor.xyz *= cubeColor.xyz;",
  9967. "#endif",
  9968. "if ( combine == 1 ) {",
  9969. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  9970. "} else if ( combine == 2 ) {",
  9971. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  9972. "} else {",
  9973. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  9974. "}",
  9975. "#endif"
  9976. ].join("\n"),
  9977. envmap_pars_vertex: [
  9978. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9979. "varying vec3 vReflect;",
  9980. "uniform float refractionRatio;",
  9981. "uniform bool useRefract;",
  9982. "#endif"
  9983. ].join("\n"),
  9984. worldpos_vertex : [
  9985. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  9986. "#ifdef USE_SKINNING",
  9987. "vec4 worldPosition = modelMatrix * skinned;",
  9988. "#endif",
  9989. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9990. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  9991. "#endif",
  9992. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9993. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  9994. "#endif",
  9995. "#endif"
  9996. ].join("\n"),
  9997. envmap_vertex : [
  9998. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9999. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  10000. "worldNormal = normalize( worldNormal );",
  10001. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  10002. "if ( useRefract ) {",
  10003. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  10004. "} else {",
  10005. "vReflect = reflect( cameraToVertex, worldNormal );",
  10006. "}",
  10007. "#endif"
  10008. ].join("\n"),
  10009. // COLOR MAP (particles)
  10010. map_particle_pars_fragment: [
  10011. "#ifdef USE_MAP",
  10012. "uniform sampler2D map;",
  10013. "#endif"
  10014. ].join("\n"),
  10015. map_particle_fragment: [
  10016. "#ifdef USE_MAP",
  10017. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  10018. "#endif"
  10019. ].join("\n"),
  10020. // COLOR MAP (triangles)
  10021. map_pars_vertex: [
  10022. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10023. "varying vec2 vUv;",
  10024. "uniform vec4 offsetRepeat;",
  10025. "#endif"
  10026. ].join("\n"),
  10027. map_pars_fragment: [
  10028. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10029. "varying vec2 vUv;",
  10030. "#endif",
  10031. "#ifdef USE_MAP",
  10032. "uniform sampler2D map;",
  10033. "#endif"
  10034. ].join("\n"),
  10035. map_vertex: [
  10036. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10037. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  10038. "#endif"
  10039. ].join("\n"),
  10040. map_fragment: [
  10041. "#ifdef USE_MAP",
  10042. "vec4 texelColor = texture2D( map, vUv );",
  10043. "#ifdef GAMMA_INPUT",
  10044. "texelColor.xyz *= texelColor.xyz;",
  10045. "#endif",
  10046. "gl_FragColor = gl_FragColor * texelColor;",
  10047. "#endif"
  10048. ].join("\n"),
  10049. // LIGHT MAP
  10050. lightmap_pars_fragment: [
  10051. "#ifdef USE_LIGHTMAP",
  10052. "varying vec2 vUv2;",
  10053. "uniform sampler2D lightMap;",
  10054. "#endif"
  10055. ].join("\n"),
  10056. lightmap_pars_vertex: [
  10057. "#ifdef USE_LIGHTMAP",
  10058. "varying vec2 vUv2;",
  10059. "#endif"
  10060. ].join("\n"),
  10061. lightmap_fragment: [
  10062. "#ifdef USE_LIGHTMAP",
  10063. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  10064. "#endif"
  10065. ].join("\n"),
  10066. lightmap_vertex: [
  10067. "#ifdef USE_LIGHTMAP",
  10068. "vUv2 = uv2;",
  10069. "#endif"
  10070. ].join("\n"),
  10071. // BUMP MAP
  10072. bumpmap_pars_fragment: [
  10073. "#ifdef USE_BUMPMAP",
  10074. "uniform sampler2D bumpMap;",
  10075. "uniform float bumpScale;",
  10076. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  10077. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  10078. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  10079. "vec2 dHdxy_fwd() {",
  10080. "vec2 dSTdx = dFdx( vUv );",
  10081. "vec2 dSTdy = dFdy( vUv );",
  10082. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  10083. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  10084. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  10085. "return vec2( dBx, dBy );",
  10086. "}",
  10087. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  10088. "vec3 vSigmaX = dFdx( surf_pos );",
  10089. "vec3 vSigmaY = dFdy( surf_pos );",
  10090. "vec3 vN = surf_norm;", // normalized
  10091. "vec3 R1 = cross( vSigmaY, vN );",
  10092. "vec3 R2 = cross( vN, vSigmaX );",
  10093. "float fDet = dot( vSigmaX, R1 );",
  10094. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  10095. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  10096. "}",
  10097. "#endif"
  10098. ].join("\n"),
  10099. // NORMAL MAP
  10100. normalmap_pars_fragment: [
  10101. "#ifdef USE_NORMALMAP",
  10102. "uniform sampler2D normalMap;",
  10103. "uniform vec2 normalScale;",
  10104. // Per-Pixel Tangent Space Normal Mapping
  10105. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  10106. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  10107. "vec3 q0 = dFdx( eye_pos.xyz );",
  10108. "vec3 q1 = dFdy( eye_pos.xyz );",
  10109. "vec2 st0 = dFdx( vUv.st );",
  10110. "vec2 st1 = dFdy( vUv.st );",
  10111. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  10112. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  10113. "vec3 N = normalize( surf_norm );",
  10114. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  10115. "mapN.xy = normalScale * mapN.xy;",
  10116. "mat3 tsn = mat3( S, T, N );",
  10117. "return normalize( tsn * mapN );",
  10118. "}",
  10119. "#endif"
  10120. ].join("\n"),
  10121. // SPECULAR MAP
  10122. specularmap_pars_fragment: [
  10123. "#ifdef USE_SPECULARMAP",
  10124. "uniform sampler2D specularMap;",
  10125. "#endif"
  10126. ].join("\n"),
  10127. specularmap_fragment: [
  10128. "float specularStrength;",
  10129. "#ifdef USE_SPECULARMAP",
  10130. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  10131. "specularStrength = texelSpecular.r;",
  10132. "#else",
  10133. "specularStrength = 1.0;",
  10134. "#endif"
  10135. ].join("\n"),
  10136. // LIGHTS LAMBERT
  10137. lights_lambert_pars_vertex: [
  10138. "uniform vec3 ambient;",
  10139. "uniform vec3 diffuse;",
  10140. "uniform vec3 emissive;",
  10141. "uniform vec3 ambientLightColor;",
  10142. "#if MAX_DIR_LIGHTS > 0",
  10143. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10144. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10145. "#endif",
  10146. "#if MAX_HEMI_LIGHTS > 0",
  10147. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10148. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10149. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10150. "#endif",
  10151. "#if MAX_POINT_LIGHTS > 0",
  10152. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10153. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10154. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10155. "#endif",
  10156. "#if MAX_SPOT_LIGHTS > 0",
  10157. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10158. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10159. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10160. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10161. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10162. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10163. "#endif",
  10164. "#ifdef WRAP_AROUND",
  10165. "uniform vec3 wrapRGB;",
  10166. "#endif"
  10167. ].join("\n"),
  10168. lights_lambert_vertex: [
  10169. "vLightFront = vec3( 0.0 );",
  10170. "#ifdef DOUBLE_SIDED",
  10171. "vLightBack = vec3( 0.0 );",
  10172. "#endif",
  10173. "transformedNormal = normalize( transformedNormal );",
  10174. "#if MAX_DIR_LIGHTS > 0",
  10175. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10176. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10177. "vec3 dirVector = normalize( lDirection.xyz );",
  10178. "float dotProduct = dot( transformedNormal, dirVector );",
  10179. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10180. "#ifdef DOUBLE_SIDED",
  10181. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10182. "#ifdef WRAP_AROUND",
  10183. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10184. "#endif",
  10185. "#endif",
  10186. "#ifdef WRAP_AROUND",
  10187. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10188. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  10189. "#ifdef DOUBLE_SIDED",
  10190. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  10191. "#endif",
  10192. "#endif",
  10193. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  10194. "#ifdef DOUBLE_SIDED",
  10195. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  10196. "#endif",
  10197. "}",
  10198. "#endif",
  10199. "#if MAX_POINT_LIGHTS > 0",
  10200. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10201. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10202. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10203. "float lDistance = 1.0;",
  10204. "if ( pointLightDistance[ i ] > 0.0 )",
  10205. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10206. "lVector = normalize( lVector );",
  10207. "float dotProduct = dot( transformedNormal, lVector );",
  10208. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10209. "#ifdef DOUBLE_SIDED",
  10210. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10211. "#ifdef WRAP_AROUND",
  10212. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10213. "#endif",
  10214. "#endif",
  10215. "#ifdef WRAP_AROUND",
  10216. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10217. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  10218. "#ifdef DOUBLE_SIDED",
  10219. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  10220. "#endif",
  10221. "#endif",
  10222. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  10223. "#ifdef DOUBLE_SIDED",
  10224. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  10225. "#endif",
  10226. "}",
  10227. "#endif",
  10228. "#if MAX_SPOT_LIGHTS > 0",
  10229. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10230. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10231. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10232. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  10233. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10234. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10235. "float lDistance = 1.0;",
  10236. "if ( spotLightDistance[ i ] > 0.0 )",
  10237. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10238. "lVector = normalize( lVector );",
  10239. "float dotProduct = dot( transformedNormal, lVector );",
  10240. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10241. "#ifdef DOUBLE_SIDED",
  10242. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10243. "#ifdef WRAP_AROUND",
  10244. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10245. "#endif",
  10246. "#endif",
  10247. "#ifdef WRAP_AROUND",
  10248. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10249. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  10250. "#ifdef DOUBLE_SIDED",
  10251. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  10252. "#endif",
  10253. "#endif",
  10254. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  10255. "#ifdef DOUBLE_SIDED",
  10256. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  10257. "#endif",
  10258. "}",
  10259. "}",
  10260. "#endif",
  10261. "#if MAX_HEMI_LIGHTS > 0",
  10262. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10263. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10264. "vec3 lVector = normalize( lDirection.xyz );",
  10265. "float dotProduct = dot( transformedNormal, lVector );",
  10266. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10267. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  10268. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10269. "#ifdef DOUBLE_SIDED",
  10270. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  10271. "#endif",
  10272. "}",
  10273. "#endif",
  10274. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  10275. "#ifdef DOUBLE_SIDED",
  10276. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  10277. "#endif"
  10278. ].join("\n"),
  10279. // LIGHTS PHONG
  10280. lights_phong_pars_vertex: [
  10281. "#ifndef PHONG_PER_PIXEL",
  10282. "#if MAX_POINT_LIGHTS > 0",
  10283. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10284. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10285. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  10286. "#endif",
  10287. "#if MAX_SPOT_LIGHTS > 0",
  10288. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10289. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10290. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  10291. "#endif",
  10292. "#endif",
  10293. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10294. "varying vec3 vWorldPosition;",
  10295. "#endif"
  10296. ].join("\n"),
  10297. lights_phong_vertex: [
  10298. "#ifndef PHONG_PER_PIXEL",
  10299. "#if MAX_POINT_LIGHTS > 0",
  10300. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10301. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10302. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10303. "float lDistance = 1.0;",
  10304. "if ( pointLightDistance[ i ] > 0.0 )",
  10305. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10306. "vPointLight[ i ] = vec4( lVector, lDistance );",
  10307. "}",
  10308. "#endif",
  10309. "#if MAX_SPOT_LIGHTS > 0",
  10310. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10311. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10312. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10313. "float lDistance = 1.0;",
  10314. "if ( spotLightDistance[ i ] > 0.0 )",
  10315. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10316. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  10317. "}",
  10318. "#endif",
  10319. "#endif",
  10320. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10321. "vWorldPosition = worldPosition.xyz;",
  10322. "#endif"
  10323. ].join("\n"),
  10324. lights_phong_pars_fragment: [
  10325. "uniform vec3 ambientLightColor;",
  10326. "#if MAX_DIR_LIGHTS > 0",
  10327. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10328. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10329. "#endif",
  10330. "#if MAX_HEMI_LIGHTS > 0",
  10331. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10332. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10333. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10334. "#endif",
  10335. "#if MAX_POINT_LIGHTS > 0",
  10336. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10337. "#ifdef PHONG_PER_PIXEL",
  10338. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10339. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10340. "#else",
  10341. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  10342. "#endif",
  10343. "#endif",
  10344. "#if MAX_SPOT_LIGHTS > 0",
  10345. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10346. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10347. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10348. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10349. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10350. "#ifdef PHONG_PER_PIXEL",
  10351. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10352. "#else",
  10353. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  10354. "#endif",
  10355. "#endif",
  10356. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10357. "varying vec3 vWorldPosition;",
  10358. "#endif",
  10359. "#ifdef WRAP_AROUND",
  10360. "uniform vec3 wrapRGB;",
  10361. "#endif",
  10362. "varying vec3 vViewPosition;",
  10363. "varying vec3 vNormal;"
  10364. ].join("\n"),
  10365. lights_phong_fragment: [
  10366. "vec3 normal = normalize( vNormal );",
  10367. "vec3 viewPosition = normalize( vViewPosition );",
  10368. "#ifdef DOUBLE_SIDED",
  10369. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  10370. "#endif",
  10371. "#ifdef USE_NORMALMAP",
  10372. "normal = perturbNormal2Arb( -vViewPosition, normal );",
  10373. "#elif defined( USE_BUMPMAP )",
  10374. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  10375. "#endif",
  10376. "#if MAX_POINT_LIGHTS > 0",
  10377. "vec3 pointDiffuse = vec3( 0.0 );",
  10378. "vec3 pointSpecular = vec3( 0.0 );",
  10379. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10380. "#ifdef PHONG_PER_PIXEL",
  10381. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10382. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10383. "float lDistance = 1.0;",
  10384. "if ( pointLightDistance[ i ] > 0.0 )",
  10385. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10386. "lVector = normalize( lVector );",
  10387. "#else",
  10388. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  10389. "float lDistance = vPointLight[ i ].w;",
  10390. "#endif",
  10391. // diffuse
  10392. "float dotProduct = dot( normal, lVector );",
  10393. "#ifdef WRAP_AROUND",
  10394. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  10395. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10396. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  10397. "#else",
  10398. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  10399. "#endif",
  10400. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  10401. // specular
  10402. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  10403. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  10404. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  10405. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10406. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10407. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  10408. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  10409. "}",
  10410. "#endif",
  10411. "#if MAX_SPOT_LIGHTS > 0",
  10412. "vec3 spotDiffuse = vec3( 0.0 );",
  10413. "vec3 spotSpecular = vec3( 0.0 );",
  10414. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10415. "#ifdef PHONG_PER_PIXEL",
  10416. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10417. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10418. "float lDistance = 1.0;",
  10419. "if ( spotLightDistance[ i ] > 0.0 )",
  10420. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10421. "lVector = normalize( lVector );",
  10422. "#else",
  10423. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  10424. "float lDistance = vSpotLight[ i ].w;",
  10425. "#endif",
  10426. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  10427. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10428. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10429. // diffuse
  10430. "float dotProduct = dot( normal, lVector );",
  10431. "#ifdef WRAP_AROUND",
  10432. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  10433. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10434. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  10435. "#else",
  10436. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  10437. "#endif",
  10438. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  10439. // specular
  10440. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  10441. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  10442. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  10443. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10444. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10445. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  10446. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  10447. "}",
  10448. "}",
  10449. "#endif",
  10450. "#if MAX_DIR_LIGHTS > 0",
  10451. "vec3 dirDiffuse = vec3( 0.0 );",
  10452. "vec3 dirSpecular = vec3( 0.0 );" ,
  10453. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10454. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10455. "vec3 dirVector = normalize( lDirection.xyz );",
  10456. // diffuse
  10457. "float dotProduct = dot( normal, dirVector );",
  10458. "#ifdef WRAP_AROUND",
  10459. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  10460. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10461. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  10462. "#else",
  10463. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  10464. "#endif",
  10465. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  10466. // specular
  10467. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  10468. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  10469. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  10470. /*
  10471. // fresnel term from skin shader
  10472. "const float F0 = 0.128;",
  10473. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  10474. "float exponential = pow( base, 5.0 );",
  10475. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  10476. */
  10477. /*
  10478. // fresnel term from fresnel shader
  10479. "const float mFresnelBias = 0.08;",
  10480. "const float mFresnelScale = 0.3;",
  10481. "const float mFresnelPower = 5.0;",
  10482. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  10483. */
  10484. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10485. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10486. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  10487. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  10488. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  10489. "}",
  10490. "#endif",
  10491. "#if MAX_HEMI_LIGHTS > 0",
  10492. "vec3 hemiDiffuse = vec3( 0.0 );",
  10493. "vec3 hemiSpecular = vec3( 0.0 );" ,
  10494. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10495. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10496. "vec3 lVector = normalize( lDirection.xyz );",
  10497. // diffuse
  10498. "float dotProduct = dot( normal, lVector );",
  10499. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10500. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10501. "hemiDiffuse += diffuse * hemiColor;",
  10502. // specular (sky light)
  10503. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  10504. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  10505. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  10506. // specular (ground light)
  10507. "vec3 lVectorGround = -lVector;",
  10508. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  10509. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  10510. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  10511. "float dotProductGround = dot( normal, lVectorGround );",
  10512. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10513. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10514. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  10515. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  10516. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  10517. "}",
  10518. "#endif",
  10519. "vec3 totalDiffuse = vec3( 0.0 );",
  10520. "vec3 totalSpecular = vec3( 0.0 );",
  10521. "#if MAX_DIR_LIGHTS > 0",
  10522. "totalDiffuse += dirDiffuse;",
  10523. "totalSpecular += dirSpecular;",
  10524. "#endif",
  10525. "#if MAX_HEMI_LIGHTS > 0",
  10526. "totalDiffuse += hemiDiffuse;",
  10527. "totalSpecular += hemiSpecular;",
  10528. "#endif",
  10529. "#if MAX_POINT_LIGHTS > 0",
  10530. "totalDiffuse += pointDiffuse;",
  10531. "totalSpecular += pointSpecular;",
  10532. "#endif",
  10533. "#if MAX_SPOT_LIGHTS > 0",
  10534. "totalDiffuse += spotDiffuse;",
  10535. "totalSpecular += spotSpecular;",
  10536. "#endif",
  10537. "#ifdef METAL",
  10538. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  10539. "#else",
  10540. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  10541. "#endif"
  10542. ].join("\n"),
  10543. // VERTEX COLORS
  10544. color_pars_fragment: [
  10545. "#ifdef USE_COLOR",
  10546. "varying vec3 vColor;",
  10547. "#endif"
  10548. ].join("\n"),
  10549. color_fragment: [
  10550. "#ifdef USE_COLOR",
  10551. "gl_FragColor = gl_FragColor * vec4( vColor, 1.0 );",
  10552. "#endif"
  10553. ].join("\n"),
  10554. color_pars_vertex: [
  10555. "#ifdef USE_COLOR",
  10556. "varying vec3 vColor;",
  10557. "#endif"
  10558. ].join("\n"),
  10559. color_vertex: [
  10560. "#ifdef USE_COLOR",
  10561. "#ifdef GAMMA_INPUT",
  10562. "vColor = color * color;",
  10563. "#else",
  10564. "vColor = color;",
  10565. "#endif",
  10566. "#endif"
  10567. ].join("\n"),
  10568. // SKINNING
  10569. skinning_pars_vertex: [
  10570. "#ifdef USE_SKINNING",
  10571. "#ifdef BONE_TEXTURE",
  10572. "uniform sampler2D boneTexture;",
  10573. "uniform int boneTextureWidth;",
  10574. "uniform int boneTextureHeight;",
  10575. "mat4 getBoneMatrix( const in float i ) {",
  10576. "float j = i * 4.0;",
  10577. "float x = mod( j, float( boneTextureWidth ) );",
  10578. "float y = floor( j / float( boneTextureWidth ) );",
  10579. "float dx = 1.0 / float( boneTextureWidth );",
  10580. "float dy = 1.0 / float( boneTextureHeight );",
  10581. "y = dy * ( y + 0.5 );",
  10582. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  10583. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  10584. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  10585. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  10586. "mat4 bone = mat4( v1, v2, v3, v4 );",
  10587. "return bone;",
  10588. "}",
  10589. "#else",
  10590. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  10591. "mat4 getBoneMatrix( const in float i ) {",
  10592. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  10593. "return bone;",
  10594. "}",
  10595. "#endif",
  10596. "#endif"
  10597. ].join("\n"),
  10598. skinbase_vertex: [
  10599. "#ifdef USE_SKINNING",
  10600. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  10601. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  10602. "mat4 boneMatZ = getBoneMatrix( skinIndex.z );",
  10603. "mat4 boneMatW = getBoneMatrix( skinIndex.w );",
  10604. "#endif"
  10605. ].join("\n"),
  10606. skinning_vertex: [
  10607. "#ifdef USE_SKINNING",
  10608. "#ifdef USE_MORPHTARGETS",
  10609. "vec4 skinVertex = vec4( morphed, 1.0 );",
  10610. "#else",
  10611. "vec4 skinVertex = vec4( position, 1.0 );",
  10612. "#endif",
  10613. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10614. "skinned += boneMatY * skinVertex * skinWeight.y;",
  10615. "skinned += boneMatZ * skinVertex * skinWeight.z;",
  10616. "skinned += boneMatW * skinVertex * skinWeight.w;",
  10617. "#endif"
  10618. ].join("\n"),
  10619. // MORPHING
  10620. morphtarget_pars_vertex: [
  10621. "#ifdef USE_MORPHTARGETS",
  10622. "#ifndef USE_MORPHNORMALS",
  10623. "uniform float morphTargetInfluences[ 8 ];",
  10624. "#else",
  10625. "uniform float morphTargetInfluences[ 4 ];",
  10626. "#endif",
  10627. "#endif"
  10628. ].join("\n"),
  10629. morphtarget_vertex: [
  10630. "#ifdef USE_MORPHTARGETS",
  10631. "vec3 morphed = vec3( 0.0 );",
  10632. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  10633. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  10634. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  10635. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  10636. "#ifndef USE_MORPHNORMALS",
  10637. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  10638. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  10639. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  10640. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  10641. "#endif",
  10642. "morphed += position;",
  10643. "#endif"
  10644. ].join("\n"),
  10645. default_vertex : [
  10646. "vec4 mvPosition;",
  10647. "#ifdef USE_SKINNING",
  10648. "mvPosition = modelViewMatrix * skinned;",
  10649. "#endif",
  10650. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  10651. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  10652. "#endif",
  10653. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  10654. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10655. "#endif",
  10656. "gl_Position = projectionMatrix * mvPosition;"
  10657. ].join("\n"),
  10658. morphnormal_vertex: [
  10659. "#ifdef USE_MORPHNORMALS",
  10660. "vec3 morphedNormal = vec3( 0.0 );",
  10661. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  10662. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  10663. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  10664. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  10665. "morphedNormal += normal;",
  10666. "#endif"
  10667. ].join("\n"),
  10668. skinnormal_vertex: [
  10669. "#ifdef USE_SKINNING",
  10670. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  10671. "skinMatrix += skinWeight.y * boneMatY;",
  10672. "#ifdef USE_MORPHNORMALS",
  10673. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  10674. "#else",
  10675. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  10676. "#endif",
  10677. "#endif"
  10678. ].join("\n"),
  10679. defaultnormal_vertex: [
  10680. "vec3 objectNormal;",
  10681. "#ifdef USE_SKINNING",
  10682. "objectNormal = skinnedNormal.xyz;",
  10683. "#endif",
  10684. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  10685. "objectNormal = morphedNormal;",
  10686. "#endif",
  10687. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  10688. "objectNormal = normal;",
  10689. "#endif",
  10690. "#ifdef FLIP_SIDED",
  10691. "objectNormal = -objectNormal;",
  10692. "#endif",
  10693. "vec3 transformedNormal = normalMatrix * objectNormal;"
  10694. ].join("\n"),
  10695. // SHADOW MAP
  10696. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  10697. // http://spidergl.org/example.php?id=6
  10698. // http://fabiensanglard.net/shadowmapping
  10699. shadowmap_pars_fragment: [
  10700. "#ifdef USE_SHADOWMAP",
  10701. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  10702. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  10703. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  10704. "uniform float shadowBias[ MAX_SHADOWS ];",
  10705. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10706. "float unpackDepth( const in vec4 rgba_depth ) {",
  10707. "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 );",
  10708. "float depth = dot( rgba_depth, bit_shift );",
  10709. "return depth;",
  10710. "}",
  10711. "#endif"
  10712. ].join("\n"),
  10713. shadowmap_fragment: [
  10714. "#ifdef USE_SHADOWMAP",
  10715. "#ifdef SHADOWMAP_DEBUG",
  10716. "vec3 frustumColors[3];",
  10717. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  10718. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  10719. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  10720. "#endif",
  10721. "#ifdef SHADOWMAP_CASCADE",
  10722. "int inFrustumCount = 0;",
  10723. "#endif",
  10724. "float fDepth;",
  10725. "vec3 shadowColor = vec3( 1.0 );",
  10726. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10727. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  10728. // "if ( something && something )" breaks ATI OpenGL shader compiler
  10729. // "if ( all( something, something ) )" using this instead
  10730. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  10731. "bool inFrustum = all( inFrustumVec );",
  10732. // don't shadow pixels outside of light frustum
  10733. // use just first frustum (for cascades)
  10734. // don't shadow pixels behind far plane of light frustum
  10735. "#ifdef SHADOWMAP_CASCADE",
  10736. "inFrustumCount += int( inFrustum );",
  10737. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  10738. "#else",
  10739. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  10740. "#endif",
  10741. "bool frustumTest = all( frustumTestVec );",
  10742. "if ( frustumTest ) {",
  10743. "shadowCoord.z += shadowBias[ i ];",
  10744. "#if defined( SHADOWMAP_TYPE_PCF )",
  10745. // Percentage-close filtering
  10746. // (9 pixel kernel)
  10747. // http://fabiensanglard.net/shadowmappingPCF/
  10748. "float shadow = 0.0;",
  10749. /*
  10750. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  10751. // must enroll loop manually
  10752. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  10753. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  10754. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  10755. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  10756. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  10757. "float fDepth = unpackDepth( rgbaDepth );",
  10758. "if ( fDepth < shadowCoord.z )",
  10759. "shadow += 1.0;",
  10760. "}",
  10761. "shadow /= 9.0;",
  10762. */
  10763. "const float shadowDelta = 1.0 / 9.0;",
  10764. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10765. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10766. "float dx0 = -1.25 * xPixelOffset;",
  10767. "float dy0 = -1.25 * yPixelOffset;",
  10768. "float dx1 = 1.25 * xPixelOffset;",
  10769. "float dy1 = 1.25 * yPixelOffset;",
  10770. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10771. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10772. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10773. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10774. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10775. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10776. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10777. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10778. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10779. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10780. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10781. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10782. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10783. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10784. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10785. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10786. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10787. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10788. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10789. "#elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  10790. // Percentage-close filtering
  10791. // (9 pixel kernel)
  10792. // http://fabiensanglard.net/shadowmappingPCF/
  10793. "float shadow = 0.0;",
  10794. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10795. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10796. "float dx0 = -1.0 * xPixelOffset;",
  10797. "float dy0 = -1.0 * yPixelOffset;",
  10798. "float dx1 = 1.0 * xPixelOffset;",
  10799. "float dy1 = 1.0 * yPixelOffset;",
  10800. "mat3 shadowKernel;",
  10801. "mat3 depthKernel;",
  10802. "depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10803. "depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10804. "depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10805. "depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10806. "depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10807. "depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10808. "depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10809. "depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10810. "depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10811. "vec3 shadowZ = vec3( shadowCoord.z );",
  10812. "shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));",
  10813. "shadowKernel[0] *= vec3(0.25);",
  10814. "shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));",
  10815. "shadowKernel[1] *= vec3(0.25);",
  10816. "shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));",
  10817. "shadowKernel[2] *= vec3(0.25);",
  10818. "vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  10819. "shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  10820. "shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  10821. "vec4 shadowValues;",
  10822. "shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  10823. "shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  10824. "shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  10825. "shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  10826. "shadow = dot( shadowValues, vec4( 1.0 ) );",
  10827. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10828. "#else",
  10829. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  10830. "float fDepth = unpackDepth( rgbaDepth );",
  10831. "if ( fDepth < shadowCoord.z )",
  10832. // spot with multiple shadows is darker
  10833. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  10834. // spot with multiple shadows has the same color as single shadow spot
  10835. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  10836. "#endif",
  10837. "}",
  10838. "#ifdef SHADOWMAP_DEBUG",
  10839. "#ifdef SHADOWMAP_CASCADE",
  10840. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  10841. "#else",
  10842. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  10843. "#endif",
  10844. "#endif",
  10845. "}",
  10846. "#ifdef GAMMA_OUTPUT",
  10847. "shadowColor *= shadowColor;",
  10848. "#endif",
  10849. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  10850. "#endif"
  10851. ].join("\n"),
  10852. shadowmap_pars_vertex: [
  10853. "#ifdef USE_SHADOWMAP",
  10854. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10855. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  10856. "#endif"
  10857. ].join("\n"),
  10858. shadowmap_vertex: [
  10859. "#ifdef USE_SHADOWMAP",
  10860. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10861. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  10862. "}",
  10863. "#endif"
  10864. ].join("\n"),
  10865. // ALPHATEST
  10866. alphatest_fragment: [
  10867. "#ifdef ALPHATEST",
  10868. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  10869. "#endif"
  10870. ].join("\n"),
  10871. // LINEAR SPACE
  10872. linear_to_gamma_fragment: [
  10873. "#ifdef GAMMA_OUTPUT",
  10874. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  10875. "#endif"
  10876. ].join("\n")
  10877. };
  10878. /**
  10879. * Uniform Utilities
  10880. */
  10881. THREE.UniformsUtils = {
  10882. merge: function ( uniforms ) {
  10883. var u, p, tmp, merged = {};
  10884. for ( u = 0; u < uniforms.length; u ++ ) {
  10885. tmp = this.clone( uniforms[ u ] );
  10886. for ( p in tmp ) {
  10887. merged[ p ] = tmp[ p ];
  10888. }
  10889. }
  10890. return merged;
  10891. },
  10892. clone: function ( uniforms_src ) {
  10893. var u, p, parameter, parameter_src, uniforms_dst = {};
  10894. for ( u in uniforms_src ) {
  10895. uniforms_dst[ u ] = {};
  10896. for ( p in uniforms_src[ u ] ) {
  10897. parameter_src = uniforms_src[ u ][ p ];
  10898. if ( parameter_src instanceof THREE.Color ||
  10899. parameter_src instanceof THREE.Vector2 ||
  10900. parameter_src instanceof THREE.Vector3 ||
  10901. parameter_src instanceof THREE.Vector4 ||
  10902. parameter_src instanceof THREE.Matrix4 ||
  10903. parameter_src instanceof THREE.Texture ) {
  10904. uniforms_dst[ u ][ p ] = parameter_src.clone();
  10905. } else if ( parameter_src instanceof Array ) {
  10906. uniforms_dst[ u ][ p ] = parameter_src.slice();
  10907. } else {
  10908. uniforms_dst[ u ][ p ] = parameter_src;
  10909. }
  10910. }
  10911. }
  10912. return uniforms_dst;
  10913. }
  10914. };
  10915. /**
  10916. * Uniforms library for shared webgl shaders
  10917. */
  10918. THREE.UniformsLib = {
  10919. common: {
  10920. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10921. "opacity" : { type: "f", value: 1.0 },
  10922. "map" : { type: "t", value: null },
  10923. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  10924. "lightMap" : { type: "t", value: null },
  10925. "specularMap" : { type: "t", value: null },
  10926. "envMap" : { type: "t", value: null },
  10927. "flipEnvMap" : { type: "f", value: -1 },
  10928. "useRefract" : { type: "i", value: 0 },
  10929. "reflectivity" : { type: "f", value: 1.0 },
  10930. "refractionRatio" : { type: "f", value: 0.98 },
  10931. "combine" : { type: "i", value: 0 },
  10932. "morphTargetInfluences" : { type: "f", value: 0 }
  10933. },
  10934. bump: {
  10935. "bumpMap" : { type: "t", value: null },
  10936. "bumpScale" : { type: "f", value: 1 }
  10937. },
  10938. normalmap: {
  10939. "normalMap" : { type: "t", value: null },
  10940. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  10941. },
  10942. fog : {
  10943. "fogDensity" : { type: "f", value: 0.00025 },
  10944. "fogNear" : { type: "f", value: 1 },
  10945. "fogFar" : { type: "f", value: 2000 },
  10946. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10947. },
  10948. lights: {
  10949. "ambientLightColor" : { type: "fv", value: [] },
  10950. "directionalLightDirection" : { type: "fv", value: [] },
  10951. "directionalLightColor" : { type: "fv", value: [] },
  10952. "hemisphereLightDirection" : { type: "fv", value: [] },
  10953. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  10954. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  10955. "pointLightColor" : { type: "fv", value: [] },
  10956. "pointLightPosition" : { type: "fv", value: [] },
  10957. "pointLightDistance" : { type: "fv1", value: [] },
  10958. "spotLightColor" : { type: "fv", value: [] },
  10959. "spotLightPosition" : { type: "fv", value: [] },
  10960. "spotLightDirection" : { type: "fv", value: [] },
  10961. "spotLightDistance" : { type: "fv1", value: [] },
  10962. "spotLightAngleCos" : { type: "fv1", value: [] },
  10963. "spotLightExponent" : { type: "fv1", value: [] }
  10964. },
  10965. particle: {
  10966. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10967. "opacity" : { type: "f", value: 1.0 },
  10968. "size" : { type: "f", value: 1.0 },
  10969. "scale" : { type: "f", value: 1.0 },
  10970. "map" : { type: "t", value: null },
  10971. "fogDensity" : { type: "f", value: 0.00025 },
  10972. "fogNear" : { type: "f", value: 1 },
  10973. "fogFar" : { type: "f", value: 2000 },
  10974. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10975. },
  10976. shadowmap: {
  10977. "shadowMap": { type: "tv", value: [] },
  10978. "shadowMapSize": { type: "v2v", value: [] },
  10979. "shadowBias" : { type: "fv1", value: [] },
  10980. "shadowDarkness": { type: "fv1", value: [] },
  10981. "shadowMatrix" : { type: "m4v", value: [] }
  10982. }
  10983. };
  10984. /**
  10985. * Webgl Shader Library for three.js
  10986. *
  10987. * @author alteredq / http://alteredqualia.com/
  10988. * @author mrdoob / http://mrdoob.com/
  10989. * @author mikael emtinger / http://gomo.se/
  10990. */
  10991. THREE.ShaderLib = {
  10992. 'basic': {
  10993. uniforms: THREE.UniformsUtils.merge( [
  10994. THREE.UniformsLib[ "common" ],
  10995. THREE.UniformsLib[ "fog" ],
  10996. THREE.UniformsLib[ "shadowmap" ]
  10997. ] ),
  10998. vertexShader: [
  10999. THREE.ShaderChunk[ "map_pars_vertex" ],
  11000. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11001. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11002. THREE.ShaderChunk[ "color_pars_vertex" ],
  11003. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11004. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11005. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11006. "void main() {",
  11007. THREE.ShaderChunk[ "map_vertex" ],
  11008. THREE.ShaderChunk[ "lightmap_vertex" ],
  11009. THREE.ShaderChunk[ "color_vertex" ],
  11010. THREE.ShaderChunk[ "skinbase_vertex" ],
  11011. "#ifdef USE_ENVMAP",
  11012. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11013. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11014. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11015. "#endif",
  11016. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11017. THREE.ShaderChunk[ "skinning_vertex" ],
  11018. THREE.ShaderChunk[ "default_vertex" ],
  11019. THREE.ShaderChunk[ "worldpos_vertex" ],
  11020. THREE.ShaderChunk[ "envmap_vertex" ],
  11021. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11022. "}"
  11023. ].join("\n"),
  11024. fragmentShader: [
  11025. "uniform vec3 diffuse;",
  11026. "uniform float opacity;",
  11027. THREE.ShaderChunk[ "color_pars_fragment" ],
  11028. THREE.ShaderChunk[ "map_pars_fragment" ],
  11029. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11030. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11031. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11032. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11033. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11034. "void main() {",
  11035. "gl_FragColor = vec4( diffuse, opacity );",
  11036. THREE.ShaderChunk[ "map_fragment" ],
  11037. THREE.ShaderChunk[ "alphatest_fragment" ],
  11038. THREE.ShaderChunk[ "specularmap_fragment" ],
  11039. THREE.ShaderChunk[ "lightmap_fragment" ],
  11040. THREE.ShaderChunk[ "color_fragment" ],
  11041. THREE.ShaderChunk[ "envmap_fragment" ],
  11042. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11043. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11044. THREE.ShaderChunk[ "fog_fragment" ],
  11045. "}"
  11046. ].join("\n")
  11047. },
  11048. 'lambert': {
  11049. uniforms: THREE.UniformsUtils.merge( [
  11050. THREE.UniformsLib[ "common" ],
  11051. THREE.UniformsLib[ "fog" ],
  11052. THREE.UniformsLib[ "lights" ],
  11053. THREE.UniformsLib[ "shadowmap" ],
  11054. {
  11055. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  11056. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  11057. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11058. }
  11059. ] ),
  11060. vertexShader: [
  11061. "#define LAMBERT",
  11062. "varying vec3 vLightFront;",
  11063. "#ifdef DOUBLE_SIDED",
  11064. "varying vec3 vLightBack;",
  11065. "#endif",
  11066. THREE.ShaderChunk[ "map_pars_vertex" ],
  11067. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11068. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11069. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  11070. THREE.ShaderChunk[ "color_pars_vertex" ],
  11071. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11072. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11073. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11074. "void main() {",
  11075. THREE.ShaderChunk[ "map_vertex" ],
  11076. THREE.ShaderChunk[ "lightmap_vertex" ],
  11077. THREE.ShaderChunk[ "color_vertex" ],
  11078. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11079. THREE.ShaderChunk[ "skinbase_vertex" ],
  11080. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11081. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11082. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11083. THREE.ShaderChunk[ "skinning_vertex" ],
  11084. THREE.ShaderChunk[ "default_vertex" ],
  11085. THREE.ShaderChunk[ "worldpos_vertex" ],
  11086. THREE.ShaderChunk[ "envmap_vertex" ],
  11087. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  11088. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11089. "}"
  11090. ].join("\n"),
  11091. fragmentShader: [
  11092. "uniform float opacity;",
  11093. "varying vec3 vLightFront;",
  11094. "#ifdef DOUBLE_SIDED",
  11095. "varying vec3 vLightBack;",
  11096. "#endif",
  11097. THREE.ShaderChunk[ "color_pars_fragment" ],
  11098. THREE.ShaderChunk[ "map_pars_fragment" ],
  11099. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11100. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11101. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11102. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11103. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11104. "void main() {",
  11105. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  11106. THREE.ShaderChunk[ "map_fragment" ],
  11107. THREE.ShaderChunk[ "alphatest_fragment" ],
  11108. THREE.ShaderChunk[ "specularmap_fragment" ],
  11109. "#ifdef DOUBLE_SIDED",
  11110. //"float isFront = float( gl_FrontFacing );",
  11111. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  11112. "if ( gl_FrontFacing )",
  11113. "gl_FragColor.xyz *= vLightFront;",
  11114. "else",
  11115. "gl_FragColor.xyz *= vLightBack;",
  11116. "#else",
  11117. "gl_FragColor.xyz *= vLightFront;",
  11118. "#endif",
  11119. THREE.ShaderChunk[ "lightmap_fragment" ],
  11120. THREE.ShaderChunk[ "color_fragment" ],
  11121. THREE.ShaderChunk[ "envmap_fragment" ],
  11122. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11123. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11124. THREE.ShaderChunk[ "fog_fragment" ],
  11125. "}"
  11126. ].join("\n")
  11127. },
  11128. 'phong': {
  11129. uniforms: THREE.UniformsUtils.merge( [
  11130. THREE.UniformsLib[ "common" ],
  11131. THREE.UniformsLib[ "bump" ],
  11132. THREE.UniformsLib[ "normalmap" ],
  11133. THREE.UniformsLib[ "fog" ],
  11134. THREE.UniformsLib[ "lights" ],
  11135. THREE.UniformsLib[ "shadowmap" ],
  11136. {
  11137. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  11138. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  11139. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  11140. "shininess": { type: "f", value: 30 },
  11141. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11142. }
  11143. ] ),
  11144. vertexShader: [
  11145. "#define PHONG",
  11146. "varying vec3 vViewPosition;",
  11147. "varying vec3 vNormal;",
  11148. THREE.ShaderChunk[ "map_pars_vertex" ],
  11149. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11150. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11151. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  11152. THREE.ShaderChunk[ "color_pars_vertex" ],
  11153. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11154. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11155. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11156. "void main() {",
  11157. THREE.ShaderChunk[ "map_vertex" ],
  11158. THREE.ShaderChunk[ "lightmap_vertex" ],
  11159. THREE.ShaderChunk[ "color_vertex" ],
  11160. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11161. THREE.ShaderChunk[ "skinbase_vertex" ],
  11162. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11163. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11164. "vNormal = normalize( transformedNormal );",
  11165. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11166. THREE.ShaderChunk[ "skinning_vertex" ],
  11167. THREE.ShaderChunk[ "default_vertex" ],
  11168. "vViewPosition = -mvPosition.xyz;",
  11169. THREE.ShaderChunk[ "worldpos_vertex" ],
  11170. THREE.ShaderChunk[ "envmap_vertex" ],
  11171. THREE.ShaderChunk[ "lights_phong_vertex" ],
  11172. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11173. "}"
  11174. ].join("\n"),
  11175. fragmentShader: [
  11176. "uniform vec3 diffuse;",
  11177. "uniform float opacity;",
  11178. "uniform vec3 ambient;",
  11179. "uniform vec3 emissive;",
  11180. "uniform vec3 specular;",
  11181. "uniform float shininess;",
  11182. THREE.ShaderChunk[ "color_pars_fragment" ],
  11183. THREE.ShaderChunk[ "map_pars_fragment" ],
  11184. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11185. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11186. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11187. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  11188. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11189. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  11190. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  11191. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11192. "void main() {",
  11193. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  11194. THREE.ShaderChunk[ "map_fragment" ],
  11195. THREE.ShaderChunk[ "alphatest_fragment" ],
  11196. THREE.ShaderChunk[ "specularmap_fragment" ],
  11197. THREE.ShaderChunk[ "lights_phong_fragment" ],
  11198. THREE.ShaderChunk[ "lightmap_fragment" ],
  11199. THREE.ShaderChunk[ "color_fragment" ],
  11200. THREE.ShaderChunk[ "envmap_fragment" ],
  11201. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11202. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11203. THREE.ShaderChunk[ "fog_fragment" ],
  11204. "}"
  11205. ].join("\n")
  11206. },
  11207. 'particle_basic': {
  11208. uniforms: THREE.UniformsUtils.merge( [
  11209. THREE.UniformsLib[ "particle" ],
  11210. THREE.UniformsLib[ "shadowmap" ]
  11211. ] ),
  11212. vertexShader: [
  11213. "uniform float size;",
  11214. "uniform float scale;",
  11215. THREE.ShaderChunk[ "color_pars_vertex" ],
  11216. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11217. "void main() {",
  11218. THREE.ShaderChunk[ "color_vertex" ],
  11219. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11220. "#ifdef USE_SIZEATTENUATION",
  11221. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  11222. "#else",
  11223. "gl_PointSize = size;",
  11224. "#endif",
  11225. "gl_Position = projectionMatrix * mvPosition;",
  11226. THREE.ShaderChunk[ "worldpos_vertex" ],
  11227. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11228. "}"
  11229. ].join("\n"),
  11230. fragmentShader: [
  11231. "uniform vec3 psColor;",
  11232. "uniform float opacity;",
  11233. THREE.ShaderChunk[ "color_pars_fragment" ],
  11234. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  11235. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11236. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11237. "void main() {",
  11238. "gl_FragColor = vec4( psColor, opacity );",
  11239. THREE.ShaderChunk[ "map_particle_fragment" ],
  11240. THREE.ShaderChunk[ "alphatest_fragment" ],
  11241. THREE.ShaderChunk[ "color_fragment" ],
  11242. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11243. THREE.ShaderChunk[ "fog_fragment" ],
  11244. "}"
  11245. ].join("\n")
  11246. },
  11247. 'dashed': {
  11248. uniforms: THREE.UniformsUtils.merge( [
  11249. THREE.UniformsLib[ "common" ],
  11250. THREE.UniformsLib[ "fog" ],
  11251. {
  11252. "scale": { type: "f", value: 1 },
  11253. "dashSize": { type: "f", value: 1 },
  11254. "totalSize": { type: "f", value: 2 }
  11255. }
  11256. ] ),
  11257. vertexShader: [
  11258. "uniform float scale;",
  11259. "attribute float lineDistance;",
  11260. "varying float vLineDistance;",
  11261. THREE.ShaderChunk[ "color_pars_vertex" ],
  11262. "void main() {",
  11263. THREE.ShaderChunk[ "color_vertex" ],
  11264. "vLineDistance = scale * lineDistance;",
  11265. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11266. "gl_Position = projectionMatrix * mvPosition;",
  11267. "}"
  11268. ].join("\n"),
  11269. fragmentShader: [
  11270. "uniform vec3 diffuse;",
  11271. "uniform float opacity;",
  11272. "uniform float dashSize;",
  11273. "uniform float totalSize;",
  11274. "varying float vLineDistance;",
  11275. THREE.ShaderChunk[ "color_pars_fragment" ],
  11276. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11277. "void main() {",
  11278. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  11279. "discard;",
  11280. "}",
  11281. "gl_FragColor = vec4( diffuse, opacity );",
  11282. THREE.ShaderChunk[ "color_fragment" ],
  11283. THREE.ShaderChunk[ "fog_fragment" ],
  11284. "}"
  11285. ].join("\n")
  11286. },
  11287. 'depth': {
  11288. uniforms: {
  11289. "mNear": { type: "f", value: 1.0 },
  11290. "mFar" : { type: "f", value: 2000.0 },
  11291. "opacity" : { type: "f", value: 1.0 }
  11292. },
  11293. vertexShader: [
  11294. "void main() {",
  11295. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11296. "}"
  11297. ].join("\n"),
  11298. fragmentShader: [
  11299. "uniform float mNear;",
  11300. "uniform float mFar;",
  11301. "uniform float opacity;",
  11302. "void main() {",
  11303. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  11304. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  11305. "gl_FragColor = vec4( vec3( color ), opacity );",
  11306. "}"
  11307. ].join("\n")
  11308. },
  11309. 'normal': {
  11310. uniforms: {
  11311. "opacity" : { type: "f", value: 1.0 }
  11312. },
  11313. vertexShader: [
  11314. "varying vec3 vNormal;",
  11315. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11316. "void main() {",
  11317. "vNormal = normalize( normalMatrix * normal );",
  11318. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11319. THREE.ShaderChunk[ "default_vertex" ],
  11320. "}"
  11321. ].join("\n"),
  11322. fragmentShader: [
  11323. "uniform float opacity;",
  11324. "varying vec3 vNormal;",
  11325. "void main() {",
  11326. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  11327. "}"
  11328. ].join("\n")
  11329. },
  11330. /* -------------------------------------------------------------------------
  11331. // Normal map shader
  11332. // - Blinn-Phong
  11333. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  11334. // - point and directional lights (use with "lights: true" material option)
  11335. ------------------------------------------------------------------------- */
  11336. 'normalmap' : {
  11337. uniforms: THREE.UniformsUtils.merge( [
  11338. THREE.UniformsLib[ "fog" ],
  11339. THREE.UniformsLib[ "lights" ],
  11340. THREE.UniformsLib[ "shadowmap" ],
  11341. {
  11342. "enableAO" : { type: "i", value: 0 },
  11343. "enableDiffuse" : { type: "i", value: 0 },
  11344. "enableSpecular" : { type: "i", value: 0 },
  11345. "enableReflection": { type: "i", value: 0 },
  11346. "enableDisplacement": { type: "i", value: 0 },
  11347. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  11348. "tDiffuse" : { type: "t", value: null },
  11349. "tCube" : { type: "t", value: null },
  11350. "tNormal" : { type: "t", value: null },
  11351. "tSpecular" : { type: "t", value: null },
  11352. "tAO" : { type: "t", value: null },
  11353. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11354. "uDisplacementBias": { type: "f", value: 0.0 },
  11355. "uDisplacementScale": { type: "f", value: 1.0 },
  11356. "diffuse": { type: "c", value: new THREE.Color( 0xffffff ) },
  11357. "specular": { type: "c", value: new THREE.Color( 0x111111 ) },
  11358. "ambient": { type: "c", value: new THREE.Color( 0xffffff ) },
  11359. "shininess": { type: "f", value: 30 },
  11360. "opacity": { type: "f", value: 1 },
  11361. "useRefract": { type: "i", value: 0 },
  11362. "refractionRatio": { type: "f", value: 0.98 },
  11363. "reflectivity": { type: "f", value: 0.5 },
  11364. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  11365. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11366. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11367. }
  11368. ] ),
  11369. fragmentShader: [
  11370. "uniform vec3 ambient;",
  11371. "uniform vec3 diffuse;",
  11372. "uniform vec3 specular;",
  11373. "uniform float shininess;",
  11374. "uniform float opacity;",
  11375. "uniform bool enableDiffuse;",
  11376. "uniform bool enableSpecular;",
  11377. "uniform bool enableAO;",
  11378. "uniform bool enableReflection;",
  11379. "uniform sampler2D tDiffuse;",
  11380. "uniform sampler2D tNormal;",
  11381. "uniform sampler2D tSpecular;",
  11382. "uniform sampler2D tAO;",
  11383. "uniform samplerCube tCube;",
  11384. "uniform vec2 uNormalScale;",
  11385. "uniform bool useRefract;",
  11386. "uniform float refractionRatio;",
  11387. "uniform float reflectivity;",
  11388. "varying vec3 vTangent;",
  11389. "varying vec3 vBinormal;",
  11390. "varying vec3 vNormal;",
  11391. "varying vec2 vUv;",
  11392. "uniform vec3 ambientLightColor;",
  11393. "#if MAX_DIR_LIGHTS > 0",
  11394. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  11395. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  11396. "#endif",
  11397. "#if MAX_HEMI_LIGHTS > 0",
  11398. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  11399. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  11400. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  11401. "#endif",
  11402. "#if MAX_POINT_LIGHTS > 0",
  11403. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  11404. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  11405. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  11406. "#endif",
  11407. "#if MAX_SPOT_LIGHTS > 0",
  11408. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  11409. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  11410. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  11411. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  11412. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  11413. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  11414. "#endif",
  11415. "#ifdef WRAP_AROUND",
  11416. "uniform vec3 wrapRGB;",
  11417. "#endif",
  11418. "varying vec3 vWorldPosition;",
  11419. "varying vec3 vViewPosition;",
  11420. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11421. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11422. "void main() {",
  11423. "gl_FragColor = vec4( vec3( 1.0 ), opacity );",
  11424. "vec3 specularTex = vec3( 1.0 );",
  11425. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  11426. "normalTex.xy *= uNormalScale;",
  11427. "normalTex = normalize( normalTex );",
  11428. "if( enableDiffuse ) {",
  11429. "#ifdef GAMMA_INPUT",
  11430. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  11431. "texelColor.xyz *= texelColor.xyz;",
  11432. "gl_FragColor = gl_FragColor * texelColor;",
  11433. "#else",
  11434. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  11435. "#endif",
  11436. "}",
  11437. "if( enableAO ) {",
  11438. "#ifdef GAMMA_INPUT",
  11439. "vec4 aoColor = texture2D( tAO, vUv );",
  11440. "aoColor.xyz *= aoColor.xyz;",
  11441. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  11442. "#else",
  11443. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  11444. "#endif",
  11445. "}",
  11446. "if( enableSpecular )",
  11447. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  11448. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  11449. "vec3 finalNormal = tsb * normalTex;",
  11450. "#ifdef FLIP_SIDED",
  11451. "finalNormal = -finalNormal;",
  11452. "#endif",
  11453. "vec3 normal = normalize( finalNormal );",
  11454. "vec3 viewPosition = normalize( vViewPosition );",
  11455. // point lights
  11456. "#if MAX_POINT_LIGHTS > 0",
  11457. "vec3 pointDiffuse = vec3( 0.0 );",
  11458. "vec3 pointSpecular = vec3( 0.0 );",
  11459. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  11460. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  11461. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  11462. "float pointDistance = 1.0;",
  11463. "if ( pointLightDistance[ i ] > 0.0 )",
  11464. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  11465. "pointVector = normalize( pointVector );",
  11466. // diffuse
  11467. "#ifdef WRAP_AROUND",
  11468. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  11469. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  11470. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  11471. "#else",
  11472. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  11473. "#endif",
  11474. "pointDiffuse += pointDistance * pointLightColor[ i ] * diffuse * pointDiffuseWeight;",
  11475. // specular
  11476. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  11477. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  11478. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  11479. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11480. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11481. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  11482. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  11483. "}",
  11484. "#endif",
  11485. // spot lights
  11486. "#if MAX_SPOT_LIGHTS > 0",
  11487. "vec3 spotDiffuse = vec3( 0.0 );",
  11488. "vec3 spotSpecular = vec3( 0.0 );",
  11489. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  11490. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  11491. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  11492. "float spotDistance = 1.0;",
  11493. "if ( spotLightDistance[ i ] > 0.0 )",
  11494. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  11495. "spotVector = normalize( spotVector );",
  11496. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  11497. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  11498. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  11499. // diffuse
  11500. "#ifdef WRAP_AROUND",
  11501. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  11502. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  11503. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  11504. "#else",
  11505. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  11506. "#endif",
  11507. "spotDiffuse += spotDistance * spotLightColor[ i ] * diffuse * spotDiffuseWeight * spotEffect;",
  11508. // specular
  11509. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  11510. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  11511. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  11512. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11513. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11514. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  11515. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  11516. "}",
  11517. "}",
  11518. "#endif",
  11519. // directional lights
  11520. "#if MAX_DIR_LIGHTS > 0",
  11521. "vec3 dirDiffuse = vec3( 0.0 );",
  11522. "vec3 dirSpecular = vec3( 0.0 );",
  11523. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  11524. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  11525. "vec3 dirVector = normalize( lDirection.xyz );",
  11526. // diffuse
  11527. "#ifdef WRAP_AROUND",
  11528. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  11529. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  11530. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  11531. "#else",
  11532. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  11533. "#endif",
  11534. "dirDiffuse += directionalLightColor[ i ] * diffuse * dirDiffuseWeight;",
  11535. // specular
  11536. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  11537. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  11538. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  11539. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11540. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11541. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  11542. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  11543. "}",
  11544. "#endif",
  11545. // hemisphere lights
  11546. "#if MAX_HEMI_LIGHTS > 0",
  11547. "vec3 hemiDiffuse = vec3( 0.0 );",
  11548. "vec3 hemiSpecular = vec3( 0.0 );" ,
  11549. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  11550. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  11551. "vec3 lVector = normalize( lDirection.xyz );",
  11552. // diffuse
  11553. "float dotProduct = dot( normal, lVector );",
  11554. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  11555. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  11556. "hemiDiffuse += diffuse * hemiColor;",
  11557. // specular (sky light)
  11558. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  11559. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  11560. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  11561. // specular (ground light)
  11562. "vec3 lVectorGround = -lVector;",
  11563. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  11564. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  11565. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  11566. "float dotProductGround = dot( normal, lVectorGround );",
  11567. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11568. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11569. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  11570. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  11571. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  11572. "}",
  11573. "#endif",
  11574. // all lights contribution summation
  11575. "vec3 totalDiffuse = vec3( 0.0 );",
  11576. "vec3 totalSpecular = vec3( 0.0 );",
  11577. "#if MAX_DIR_LIGHTS > 0",
  11578. "totalDiffuse += dirDiffuse;",
  11579. "totalSpecular += dirSpecular;",
  11580. "#endif",
  11581. "#if MAX_HEMI_LIGHTS > 0",
  11582. "totalDiffuse += hemiDiffuse;",
  11583. "totalSpecular += hemiSpecular;",
  11584. "#endif",
  11585. "#if MAX_POINT_LIGHTS > 0",
  11586. "totalDiffuse += pointDiffuse;",
  11587. "totalSpecular += pointSpecular;",
  11588. "#endif",
  11589. "#if MAX_SPOT_LIGHTS > 0",
  11590. "totalDiffuse += spotDiffuse;",
  11591. "totalSpecular += spotSpecular;",
  11592. "#endif",
  11593. "#ifdef METAL",
  11594. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  11595. "#else",
  11596. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  11597. "#endif",
  11598. "if ( enableReflection ) {",
  11599. "vec3 vReflect;",
  11600. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  11601. "if ( useRefract ) {",
  11602. "vReflect = refract( cameraToVertex, normal, refractionRatio );",
  11603. "} else {",
  11604. "vReflect = reflect( cameraToVertex, normal );",
  11605. "}",
  11606. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  11607. "#ifdef GAMMA_INPUT",
  11608. "cubeColor.xyz *= cubeColor.xyz;",
  11609. "#endif",
  11610. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * reflectivity );",
  11611. "}",
  11612. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11613. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11614. THREE.ShaderChunk[ "fog_fragment" ],
  11615. "}"
  11616. ].join("\n"),
  11617. vertexShader: [
  11618. "attribute vec4 tangent;",
  11619. "uniform vec2 uOffset;",
  11620. "uniform vec2 uRepeat;",
  11621. "uniform bool enableDisplacement;",
  11622. "#ifdef VERTEX_TEXTURES",
  11623. "uniform sampler2D tDisplacement;",
  11624. "uniform float uDisplacementScale;",
  11625. "uniform float uDisplacementBias;",
  11626. "#endif",
  11627. "varying vec3 vTangent;",
  11628. "varying vec3 vBinormal;",
  11629. "varying vec3 vNormal;",
  11630. "varying vec2 vUv;",
  11631. "varying vec3 vWorldPosition;",
  11632. "varying vec3 vViewPosition;",
  11633. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11634. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11635. "void main() {",
  11636. THREE.ShaderChunk[ "skinbase_vertex" ],
  11637. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11638. // normal, tangent and binormal vectors
  11639. "#ifdef USE_SKINNING",
  11640. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  11641. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  11642. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  11643. "#else",
  11644. "vNormal = normalize( normalMatrix * normal );",
  11645. "vTangent = normalize( normalMatrix * tangent.xyz );",
  11646. "#endif",
  11647. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  11648. "vUv = uv * uRepeat + uOffset;",
  11649. // displacement mapping
  11650. "vec3 displacedPosition;",
  11651. "#ifdef VERTEX_TEXTURES",
  11652. "if ( enableDisplacement ) {",
  11653. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  11654. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  11655. "displacedPosition = position + normalize( normal ) * df;",
  11656. "} else {",
  11657. "#ifdef USE_SKINNING",
  11658. "vec4 skinVertex = vec4( position, 1.0 );",
  11659. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11660. "skinned += boneMatY * skinVertex * skinWeight.y;",
  11661. "displacedPosition = skinned.xyz;",
  11662. "#else",
  11663. "displacedPosition = position;",
  11664. "#endif",
  11665. "}",
  11666. "#else",
  11667. "#ifdef USE_SKINNING",
  11668. "vec4 skinVertex = vec4( position, 1.0 );",
  11669. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11670. "skinned += boneMatY * skinVertex * skinWeight.y;",
  11671. "displacedPosition = skinned.xyz;",
  11672. "#else",
  11673. "displacedPosition = position;",
  11674. "#endif",
  11675. "#endif",
  11676. //
  11677. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  11678. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  11679. "gl_Position = projectionMatrix * mvPosition;",
  11680. //
  11681. "vWorldPosition = worldPosition.xyz;",
  11682. "vViewPosition = -mvPosition.xyz;",
  11683. // shadows
  11684. "#ifdef USE_SHADOWMAP",
  11685. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  11686. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  11687. "}",
  11688. "#endif",
  11689. "}"
  11690. ].join("\n")
  11691. },
  11692. /* -------------------------------------------------------------------------
  11693. // Cube map shader
  11694. ------------------------------------------------------------------------- */
  11695. 'cube': {
  11696. uniforms: { "tCube": { type: "t", value: null },
  11697. "tFlip": { type: "f", value: -1 } },
  11698. vertexShader: [
  11699. "varying vec3 vWorldPosition;",
  11700. "void main() {",
  11701. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  11702. "vWorldPosition = worldPosition.xyz;",
  11703. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11704. "}"
  11705. ].join("\n"),
  11706. fragmentShader: [
  11707. "uniform samplerCube tCube;",
  11708. "uniform float tFlip;",
  11709. "varying vec3 vWorldPosition;",
  11710. "void main() {",
  11711. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  11712. "}"
  11713. ].join("\n")
  11714. },
  11715. // Depth encoding into RGBA texture
  11716. // based on SpiderGL shadow map example
  11717. // http://spidergl.org/example.php?id=6
  11718. // originally from
  11719. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  11720. // see also here:
  11721. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  11722. 'depthRGBA': {
  11723. uniforms: {},
  11724. vertexShader: [
  11725. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11726. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11727. "void main() {",
  11728. THREE.ShaderChunk[ "skinbase_vertex" ],
  11729. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11730. THREE.ShaderChunk[ "skinning_vertex" ],
  11731. THREE.ShaderChunk[ "default_vertex" ],
  11732. "}"
  11733. ].join("\n"),
  11734. fragmentShader: [
  11735. "vec4 pack_depth( const in float depth ) {",
  11736. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  11737. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  11738. "vec4 res = fract( depth * bit_shift );",
  11739. "res -= res.xxyz * bit_mask;",
  11740. "return res;",
  11741. "}",
  11742. "void main() {",
  11743. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  11744. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  11745. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  11746. //"gl_FragData[ 0 ] = pack_depth( z );",
  11747. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  11748. "}"
  11749. ].join("\n")
  11750. }
  11751. };
  11752. /**
  11753. * @author supereggbert / http://www.paulbrunt.co.uk/
  11754. * @author mrdoob / http://mrdoob.com/
  11755. * @author alteredq / http://alteredqualia.com/
  11756. * @author szimek / https://github.com/szimek/
  11757. */
  11758. THREE.WebGLRenderer = function ( parameters ) {
  11759. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  11760. parameters = parameters || {};
  11761. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  11762. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  11763. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  11764. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  11765. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  11766. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  11767. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  11768. _clearColor = new THREE.Color( 0x000000 ),
  11769. _clearAlpha = 0;
  11770. // public properties
  11771. this.domElement = _canvas;
  11772. this.context = null;
  11773. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  11774. ? parameters.devicePixelRatio
  11775. : self.devicePixelRatio !== undefined
  11776. ? self.devicePixelRatio
  11777. : 1;
  11778. // clearing
  11779. this.autoClear = true;
  11780. this.autoClearColor = true;
  11781. this.autoClearDepth = true;
  11782. this.autoClearStencil = true;
  11783. // scene graph
  11784. this.sortObjects = true;
  11785. this.autoUpdateObjects = true;
  11786. // physically based shading
  11787. this.gammaInput = false;
  11788. this.gammaOutput = false;
  11789. // shadow map
  11790. this.shadowMapEnabled = false;
  11791. this.shadowMapAutoUpdate = true;
  11792. this.shadowMapType = THREE.PCFShadowMap;
  11793. this.shadowMapCullFace = THREE.CullFaceFront;
  11794. this.shadowMapDebug = false;
  11795. this.shadowMapCascade = false;
  11796. // morphs
  11797. this.maxMorphTargets = 8;
  11798. this.maxMorphNormals = 4;
  11799. // flags
  11800. this.autoScaleCubemaps = true;
  11801. // custom render plugins
  11802. this.renderPluginsPre = [];
  11803. this.renderPluginsPost = [];
  11804. // info
  11805. this.info = {
  11806. memory: {
  11807. programs: 0,
  11808. geometries: 0,
  11809. textures: 0
  11810. },
  11811. render: {
  11812. calls: 0,
  11813. vertices: 0,
  11814. faces: 0,
  11815. points: 0
  11816. }
  11817. };
  11818. // internal properties
  11819. var _this = this,
  11820. _programs = [],
  11821. _programs_counter = 0,
  11822. // internal state cache
  11823. _currentProgram = null,
  11824. _currentFramebuffer = null,
  11825. _currentMaterialId = -1,
  11826. _currentGeometryGroupHash = null,
  11827. _currentCamera = null,
  11828. _geometryGroupCounter = 0,
  11829. _usedTextureUnits = 0,
  11830. // GL state cache
  11831. _oldDoubleSided = -1,
  11832. _oldFlipSided = -1,
  11833. _oldBlending = -1,
  11834. _oldBlendEquation = -1,
  11835. _oldBlendSrc = -1,
  11836. _oldBlendDst = -1,
  11837. _oldDepthTest = -1,
  11838. _oldDepthWrite = -1,
  11839. _oldPolygonOffset = null,
  11840. _oldPolygonOffsetFactor = null,
  11841. _oldPolygonOffsetUnits = null,
  11842. _oldLineWidth = null,
  11843. _viewportX = 0,
  11844. _viewportY = 0,
  11845. _viewportWidth = _canvas.width,
  11846. _viewportHeight = _canvas.height,
  11847. _currentWidth = 0,
  11848. _currentHeight = 0,
  11849. _enabledAttributes = {},
  11850. // frustum
  11851. _frustum = new THREE.Frustum(),
  11852. // camera matrices cache
  11853. _projScreenMatrix = new THREE.Matrix4(),
  11854. _projScreenMatrixPS = new THREE.Matrix4(),
  11855. _vector3 = new THREE.Vector3(),
  11856. // light arrays cache
  11857. _direction = new THREE.Vector3(),
  11858. _lightsNeedUpdate = true,
  11859. _lights = {
  11860. ambient: [ 0, 0, 0 ],
  11861. directional: { length: 0, colors: new Array(), positions: new Array() },
  11862. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  11863. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  11864. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  11865. };
  11866. // initialize
  11867. var _gl;
  11868. var _glExtensionTextureFloat;
  11869. var _glExtensionTextureFloatLinear;
  11870. var _glExtensionStandardDerivatives;
  11871. var _glExtensionTextureFilterAnisotropic;
  11872. var _glExtensionCompressedTextureS3TC;
  11873. initGL();
  11874. setDefaultGLState();
  11875. this.context = _gl;
  11876. // GPU capabilities
  11877. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  11878. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  11879. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  11880. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  11881. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  11882. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  11883. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  11884. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  11885. //
  11886. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  11887. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  11888. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  11889. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  11890. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  11891. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  11892. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  11893. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  11894. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  11895. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  11896. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  11897. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  11898. // clamp precision to maximum available
  11899. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  11900. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  11901. if ( _precision === "highp" && ! highpAvailable ) {
  11902. if ( mediumpAvailable ) {
  11903. _precision = "mediump";
  11904. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  11905. } else {
  11906. _precision = "lowp";
  11907. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  11908. }
  11909. }
  11910. if ( _precision === "mediump" && ! mediumpAvailable ) {
  11911. _precision = "lowp";
  11912. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  11913. }
  11914. // API
  11915. this.getContext = function () {
  11916. return _gl;
  11917. };
  11918. this.supportsVertexTextures = function () {
  11919. return _supportsVertexTextures;
  11920. };
  11921. this.supportsFloatTextures = function () {
  11922. return _glExtensionTextureFloat;
  11923. };
  11924. this.supportsStandardDerivatives = function () {
  11925. return _glExtensionStandardDerivatives;
  11926. };
  11927. this.supportsCompressedTextureS3TC = function () {
  11928. return _glExtensionCompressedTextureS3TC;
  11929. };
  11930. this.getMaxAnisotropy = function () {
  11931. return _maxAnisotropy;
  11932. };
  11933. this.getPrecision = function () {
  11934. return _precision;
  11935. };
  11936. this.setSize = function ( width, height, updateStyle ) {
  11937. _canvas.width = width * this.devicePixelRatio;
  11938. _canvas.height = height * this.devicePixelRatio;
  11939. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  11940. _canvas.style.width = width + 'px';
  11941. _canvas.style.height = height + 'px';
  11942. }
  11943. this.setViewport( 0, 0, width, height );
  11944. };
  11945. this.setViewport = function ( x, y, width, height ) {
  11946. _viewportX = x * this.devicePixelRatio;
  11947. _viewportY = y * this.devicePixelRatio;
  11948. _viewportWidth = width * this.devicePixelRatio;
  11949. _viewportHeight = height * this.devicePixelRatio;
  11950. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  11951. };
  11952. this.setScissor = function ( x, y, width, height ) {
  11953. _gl.scissor(
  11954. x * this.devicePixelRatio,
  11955. y * this.devicePixelRatio,
  11956. width * this.devicePixelRatio,
  11957. height * this.devicePixelRatio
  11958. );
  11959. };
  11960. this.enableScissorTest = function ( enable ) {
  11961. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  11962. };
  11963. // Clearing
  11964. this.setClearColor = function ( color, alpha ) {
  11965. _clearColor.set( color );
  11966. _clearAlpha = alpha !== undefined ? alpha : 1;
  11967. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11968. };
  11969. this.setClearColorHex = function ( hex, alpha ) {
  11970. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  11971. this.setClearColor( hex, alpha );
  11972. };
  11973. this.getClearColor = function () {
  11974. return _clearColor;
  11975. };
  11976. this.getClearAlpha = function () {
  11977. return _clearAlpha;
  11978. };
  11979. this.clear = function ( color, depth, stencil ) {
  11980. var bits = 0;
  11981. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  11982. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  11983. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  11984. _gl.clear( bits );
  11985. };
  11986. this.clearColor = function () {
  11987. _gl.clear( _gl.COLOR_BUFFER_BIT );
  11988. };
  11989. this.clearDepth = function () {
  11990. _gl.clear( _gl.DEPTH_BUFFER_BIT );
  11991. };
  11992. this.clearStencil = function () {
  11993. _gl.clear( _gl.STENCIL_BUFFER_BIT );
  11994. };
  11995. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  11996. this.setRenderTarget( renderTarget );
  11997. this.clear( color, depth, stencil );
  11998. };
  11999. // Plugins
  12000. this.addPostPlugin = function ( plugin ) {
  12001. plugin.init( this );
  12002. this.renderPluginsPost.push( plugin );
  12003. };
  12004. this.addPrePlugin = function ( plugin ) {
  12005. plugin.init( this );
  12006. this.renderPluginsPre.push( plugin );
  12007. };
  12008. // Rendering
  12009. this.updateShadowMap = function ( scene, camera ) {
  12010. _currentProgram = null;
  12011. _oldBlending = -1;
  12012. _oldDepthTest = -1;
  12013. _oldDepthWrite = -1;
  12014. _currentGeometryGroupHash = -1;
  12015. _currentMaterialId = -1;
  12016. _lightsNeedUpdate = true;
  12017. _oldDoubleSided = -1;
  12018. _oldFlipSided = -1;
  12019. this.shadowMapPlugin.update( scene, camera );
  12020. };
  12021. // Internal functions
  12022. // Buffer allocation
  12023. function createParticleBuffers ( geometry ) {
  12024. geometry.__webglVertexBuffer = _gl.createBuffer();
  12025. geometry.__webglColorBuffer = _gl.createBuffer();
  12026. _this.info.memory.geometries ++;
  12027. };
  12028. function createLineBuffers ( geometry ) {
  12029. geometry.__webglVertexBuffer = _gl.createBuffer();
  12030. geometry.__webglColorBuffer = _gl.createBuffer();
  12031. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  12032. _this.info.memory.geometries ++;
  12033. };
  12034. function createMeshBuffers ( geometryGroup ) {
  12035. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  12036. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  12037. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  12038. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  12039. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  12040. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  12041. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  12042. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  12043. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  12044. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  12045. var m, ml;
  12046. if ( geometryGroup.numMorphTargets ) {
  12047. geometryGroup.__webglMorphTargetsBuffers = [];
  12048. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12049. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  12050. }
  12051. }
  12052. if ( geometryGroup.numMorphNormals ) {
  12053. geometryGroup.__webglMorphNormalsBuffers = [];
  12054. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12055. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  12056. }
  12057. }
  12058. _this.info.memory.geometries ++;
  12059. };
  12060. // Events
  12061. var onGeometryDispose = function ( event ) {
  12062. var geometry = event.target;
  12063. geometry.removeEventListener( 'dispose', onGeometryDispose );
  12064. deallocateGeometry( geometry );
  12065. };
  12066. var onTextureDispose = function ( event ) {
  12067. var texture = event.target;
  12068. texture.removeEventListener( 'dispose', onTextureDispose );
  12069. deallocateTexture( texture );
  12070. _this.info.memory.textures --;
  12071. };
  12072. var onRenderTargetDispose = function ( event ) {
  12073. var renderTarget = event.target;
  12074. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  12075. deallocateRenderTarget( renderTarget );
  12076. _this.info.memory.textures --;
  12077. };
  12078. var onMaterialDispose = function ( event ) {
  12079. var material = event.target;
  12080. material.removeEventListener( 'dispose', onMaterialDispose );
  12081. deallocateMaterial( material );
  12082. };
  12083. // Buffer deallocation
  12084. var deleteBuffers = function ( geometry ) {
  12085. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  12086. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  12087. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  12088. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  12089. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  12090. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  12091. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  12092. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  12093. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  12094. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  12095. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  12096. // custom attributes
  12097. if ( geometry.__webglCustomAttributesList !== undefined ) {
  12098. for ( var id in geometry.__webglCustomAttributesList ) {
  12099. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  12100. }
  12101. }
  12102. _this.info.memory.geometries --;
  12103. };
  12104. var deallocateGeometry = function ( geometry ) {
  12105. geometry.__webglInit = undefined;
  12106. if ( geometry instanceof THREE.BufferGeometry ) {
  12107. var attributes = geometry.attributes;
  12108. for ( var key in attributes ) {
  12109. if ( attributes[ key ].buffer !== undefined ) {
  12110. _gl.deleteBuffer( attributes[ key ].buffer );
  12111. }
  12112. }
  12113. _this.info.memory.geometries --;
  12114. } else {
  12115. if ( geometry.geometryGroups !== undefined ) {
  12116. for ( var g in geometry.geometryGroups ) {
  12117. var geometryGroup = geometry.geometryGroups[ g ];
  12118. if ( geometryGroup.numMorphTargets !== undefined ) {
  12119. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12120. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  12121. }
  12122. }
  12123. if ( geometryGroup.numMorphNormals !== undefined ) {
  12124. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12125. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  12126. }
  12127. }
  12128. deleteBuffers( geometryGroup );
  12129. }
  12130. } else {
  12131. deleteBuffers( geometry );
  12132. }
  12133. }
  12134. };
  12135. var deallocateTexture = function ( texture ) {
  12136. if ( texture.image && texture.image.__webglTextureCube ) {
  12137. // cube texture
  12138. _gl.deleteTexture( texture.image.__webglTextureCube );
  12139. } else {
  12140. // 2D texture
  12141. if ( ! texture.__webglInit ) return;
  12142. texture.__webglInit = false;
  12143. _gl.deleteTexture( texture.__webglTexture );
  12144. }
  12145. };
  12146. var deallocateRenderTarget = function ( renderTarget ) {
  12147. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  12148. _gl.deleteTexture( renderTarget.__webglTexture );
  12149. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  12150. for ( var i = 0; i < 6; i ++ ) {
  12151. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  12152. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  12153. }
  12154. } else {
  12155. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  12156. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  12157. }
  12158. };
  12159. var deallocateMaterial = function ( material ) {
  12160. var program = material.program;
  12161. if ( program === undefined ) return;
  12162. material.program = undefined;
  12163. // only deallocate GL program if this was the last use of shared program
  12164. // assumed there is only single copy of any program in the _programs list
  12165. // (that's how it's constructed)
  12166. var i, il, programInfo;
  12167. var deleteProgram = false;
  12168. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  12169. programInfo = _programs[ i ];
  12170. if ( programInfo.program === program ) {
  12171. programInfo.usedTimes --;
  12172. if ( programInfo.usedTimes === 0 ) {
  12173. deleteProgram = true;
  12174. }
  12175. break;
  12176. }
  12177. }
  12178. if ( deleteProgram === true ) {
  12179. // avoid using array.splice, this is costlier than creating new array from scratch
  12180. var newPrograms = [];
  12181. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  12182. programInfo = _programs[ i ];
  12183. if ( programInfo.program !== program ) {
  12184. newPrograms.push( programInfo );
  12185. }
  12186. }
  12187. _programs = newPrograms;
  12188. _gl.deleteProgram( program );
  12189. _this.info.memory.programs --;
  12190. }
  12191. };
  12192. // Buffer initialization
  12193. function initCustomAttributes ( geometry, object ) {
  12194. var nvertices = geometry.vertices.length;
  12195. var material = object.material;
  12196. if ( material.attributes ) {
  12197. if ( geometry.__webglCustomAttributesList === undefined ) {
  12198. geometry.__webglCustomAttributesList = [];
  12199. }
  12200. for ( var a in material.attributes ) {
  12201. var attribute = material.attributes[ a ];
  12202. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  12203. attribute.__webglInitialized = true;
  12204. var size = 1; // "f" and "i"
  12205. if ( attribute.type === "v2" ) size = 2;
  12206. else if ( attribute.type === "v3" ) size = 3;
  12207. else if ( attribute.type === "v4" ) size = 4;
  12208. else if ( attribute.type === "c" ) size = 3;
  12209. attribute.size = size;
  12210. attribute.array = new Float32Array( nvertices * size );
  12211. attribute.buffer = _gl.createBuffer();
  12212. attribute.buffer.belongsToAttribute = a;
  12213. attribute.needsUpdate = true;
  12214. }
  12215. geometry.__webglCustomAttributesList.push( attribute );
  12216. }
  12217. }
  12218. };
  12219. function initParticleBuffers ( geometry, object ) {
  12220. var nvertices = geometry.vertices.length;
  12221. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12222. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12223. geometry.__sortArray = [];
  12224. geometry.__webglParticleCount = nvertices;
  12225. initCustomAttributes ( geometry, object );
  12226. };
  12227. function initLineBuffers ( geometry, object ) {
  12228. var nvertices = geometry.vertices.length;
  12229. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12230. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12231. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  12232. geometry.__webglLineCount = nvertices;
  12233. initCustomAttributes ( geometry, object );
  12234. };
  12235. function initMeshBuffers ( geometryGroup, object ) {
  12236. var geometry = object.geometry,
  12237. faces3 = geometryGroup.faces3,
  12238. nvertices = faces3.length * 3,
  12239. ntris = faces3.length * 1,
  12240. nlines = faces3.length * 3,
  12241. material = getBufferMaterial( object, geometryGroup ),
  12242. uvType = bufferGuessUVType( material ),
  12243. normalType = bufferGuessNormalType( material ),
  12244. vertexColorType = bufferGuessVertexColorType( material );
  12245. // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  12246. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  12247. if ( normalType ) {
  12248. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  12249. }
  12250. if ( geometry.hasTangents ) {
  12251. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  12252. }
  12253. if ( vertexColorType ) {
  12254. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  12255. }
  12256. if ( uvType ) {
  12257. if ( geometry.faceVertexUvs.length > 0 ) {
  12258. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  12259. }
  12260. if ( geometry.faceVertexUvs.length > 1 ) {
  12261. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  12262. }
  12263. }
  12264. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  12265. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  12266. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  12267. }
  12268. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  12269. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  12270. var m, ml;
  12271. if ( geometryGroup.numMorphTargets ) {
  12272. geometryGroup.__morphTargetsArrays = [];
  12273. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12274. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  12275. }
  12276. }
  12277. if ( geometryGroup.numMorphNormals ) {
  12278. geometryGroup.__morphNormalsArrays = [];
  12279. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12280. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  12281. }
  12282. }
  12283. geometryGroup.__webglFaceCount = ntris * 3;
  12284. geometryGroup.__webglLineCount = nlines * 2;
  12285. // custom attributes
  12286. if ( material.attributes ) {
  12287. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  12288. geometryGroup.__webglCustomAttributesList = [];
  12289. }
  12290. for ( var a in material.attributes ) {
  12291. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  12292. // attribute buffers which are correctly indexed in the setMeshBuffers function
  12293. var originalAttribute = material.attributes[ a ];
  12294. var attribute = {};
  12295. for ( var property in originalAttribute ) {
  12296. attribute[ property ] = originalAttribute[ property ];
  12297. }
  12298. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  12299. attribute.__webglInitialized = true;
  12300. var size = 1; // "f" and "i"
  12301. if( attribute.type === "v2" ) size = 2;
  12302. else if( attribute.type === "v3" ) size = 3;
  12303. else if( attribute.type === "v4" ) size = 4;
  12304. else if( attribute.type === "c" ) size = 3;
  12305. attribute.size = size;
  12306. attribute.array = new Float32Array( nvertices * size );
  12307. attribute.buffer = _gl.createBuffer();
  12308. attribute.buffer.belongsToAttribute = a;
  12309. originalAttribute.needsUpdate = true;
  12310. attribute.__original = originalAttribute;
  12311. }
  12312. geometryGroup.__webglCustomAttributesList.push( attribute );
  12313. }
  12314. }
  12315. geometryGroup.__inittedArrays = true;
  12316. };
  12317. function getBufferMaterial( object, geometryGroup ) {
  12318. return object.material instanceof THREE.MeshFaceMaterial
  12319. ? object.material.materials[ geometryGroup.materialIndex ]
  12320. : object.material;
  12321. };
  12322. function materialNeedsSmoothNormals ( material ) {
  12323. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  12324. };
  12325. function bufferGuessNormalType ( material ) {
  12326. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  12327. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  12328. return false;
  12329. }
  12330. if ( materialNeedsSmoothNormals( material ) ) {
  12331. return THREE.SmoothShading;
  12332. } else {
  12333. return THREE.FlatShading;
  12334. }
  12335. };
  12336. function bufferGuessVertexColorType( material ) {
  12337. if ( material.vertexColors ) {
  12338. return material.vertexColors;
  12339. }
  12340. return false;
  12341. };
  12342. function bufferGuessUVType( material ) {
  12343. // material must use some texture to require uvs
  12344. if ( material.map ||
  12345. material.lightMap ||
  12346. material.bumpMap ||
  12347. material.normalMap ||
  12348. material.specularMap ||
  12349. material instanceof THREE.ShaderMaterial ) {
  12350. return true;
  12351. }
  12352. return false;
  12353. };
  12354. //
  12355. function initDirectBuffers( geometry ) {
  12356. var a, attribute, type;
  12357. for ( a in geometry.attributes ) {
  12358. if ( a === "index" ) {
  12359. type = _gl.ELEMENT_ARRAY_BUFFER;
  12360. } else {
  12361. type = _gl.ARRAY_BUFFER;
  12362. }
  12363. attribute = geometry.attributes[ a ];
  12364. attribute.buffer = _gl.createBuffer();
  12365. _gl.bindBuffer( type, attribute.buffer );
  12366. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  12367. }
  12368. };
  12369. // Buffer setting
  12370. function setParticleBuffers ( geometry, hint, object ) {
  12371. var v, c, vertex, offset, index, color,
  12372. vertices = geometry.vertices,
  12373. vl = vertices.length,
  12374. colors = geometry.colors,
  12375. cl = colors.length,
  12376. vertexArray = geometry.__vertexArray,
  12377. colorArray = geometry.__colorArray,
  12378. sortArray = geometry.__sortArray,
  12379. dirtyVertices = geometry.verticesNeedUpdate,
  12380. dirtyElements = geometry.elementsNeedUpdate,
  12381. dirtyColors = geometry.colorsNeedUpdate,
  12382. customAttributes = geometry.__webglCustomAttributesList,
  12383. i, il,
  12384. a, ca, cal, value,
  12385. customAttribute;
  12386. if ( object.sortParticles ) {
  12387. _projScreenMatrixPS.copy( _projScreenMatrix );
  12388. _projScreenMatrixPS.multiply( object.matrixWorld );
  12389. for ( v = 0; v < vl; v ++ ) {
  12390. vertex = vertices[ v ];
  12391. _vector3.copy( vertex );
  12392. _vector3.applyProjection( _projScreenMatrixPS );
  12393. sortArray[ v ] = [ _vector3.z, v ];
  12394. }
  12395. sortArray.sort( numericalSort );
  12396. for ( v = 0; v < vl; v ++ ) {
  12397. vertex = vertices[ sortArray[v][1] ];
  12398. offset = v * 3;
  12399. vertexArray[ offset ] = vertex.x;
  12400. vertexArray[ offset + 1 ] = vertex.y;
  12401. vertexArray[ offset + 2 ] = vertex.z;
  12402. }
  12403. for ( c = 0; c < cl; c ++ ) {
  12404. offset = c * 3;
  12405. color = colors[ sortArray[c][1] ];
  12406. colorArray[ offset ] = color.r;
  12407. colorArray[ offset + 1 ] = color.g;
  12408. colorArray[ offset + 2 ] = color.b;
  12409. }
  12410. if ( customAttributes ) {
  12411. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12412. customAttribute = customAttributes[ i ];
  12413. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  12414. offset = 0;
  12415. cal = customAttribute.value.length;
  12416. if ( customAttribute.size === 1 ) {
  12417. for ( ca = 0; ca < cal; ca ++ ) {
  12418. index = sortArray[ ca ][ 1 ];
  12419. customAttribute.array[ ca ] = customAttribute.value[ index ];
  12420. }
  12421. } else if ( customAttribute.size === 2 ) {
  12422. for ( ca = 0; ca < cal; ca ++ ) {
  12423. index = sortArray[ ca ][ 1 ];
  12424. value = customAttribute.value[ index ];
  12425. customAttribute.array[ offset ] = value.x;
  12426. customAttribute.array[ offset + 1 ] = value.y;
  12427. offset += 2;
  12428. }
  12429. } else if ( customAttribute.size === 3 ) {
  12430. if ( customAttribute.type === "c" ) {
  12431. for ( ca = 0; ca < cal; ca ++ ) {
  12432. index = sortArray[ ca ][ 1 ];
  12433. value = customAttribute.value[ index ];
  12434. customAttribute.array[ offset ] = value.r;
  12435. customAttribute.array[ offset + 1 ] = value.g;
  12436. customAttribute.array[ offset + 2 ] = value.b;
  12437. offset += 3;
  12438. }
  12439. } else {
  12440. for ( ca = 0; ca < cal; ca ++ ) {
  12441. index = sortArray[ ca ][ 1 ];
  12442. value = customAttribute.value[ index ];
  12443. customAttribute.array[ offset ] = value.x;
  12444. customAttribute.array[ offset + 1 ] = value.y;
  12445. customAttribute.array[ offset + 2 ] = value.z;
  12446. offset += 3;
  12447. }
  12448. }
  12449. } else if ( customAttribute.size === 4 ) {
  12450. for ( ca = 0; ca < cal; ca ++ ) {
  12451. index = sortArray[ ca ][ 1 ];
  12452. value = customAttribute.value[ index ];
  12453. customAttribute.array[ offset ] = value.x;
  12454. customAttribute.array[ offset + 1 ] = value.y;
  12455. customAttribute.array[ offset + 2 ] = value.z;
  12456. customAttribute.array[ offset + 3 ] = value.w;
  12457. offset += 4;
  12458. }
  12459. }
  12460. }
  12461. }
  12462. } else {
  12463. if ( dirtyVertices ) {
  12464. for ( v = 0; v < vl; v ++ ) {
  12465. vertex = vertices[ v ];
  12466. offset = v * 3;
  12467. vertexArray[ offset ] = vertex.x;
  12468. vertexArray[ offset + 1 ] = vertex.y;
  12469. vertexArray[ offset + 2 ] = vertex.z;
  12470. }
  12471. }
  12472. if ( dirtyColors ) {
  12473. for ( c = 0; c < cl; c ++ ) {
  12474. color = colors[ c ];
  12475. offset = c * 3;
  12476. colorArray[ offset ] = color.r;
  12477. colorArray[ offset + 1 ] = color.g;
  12478. colorArray[ offset + 2 ] = color.b;
  12479. }
  12480. }
  12481. if ( customAttributes ) {
  12482. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12483. customAttribute = customAttributes[ i ];
  12484. if ( customAttribute.needsUpdate &&
  12485. ( customAttribute.boundTo === undefined ||
  12486. customAttribute.boundTo === "vertices") ) {
  12487. cal = customAttribute.value.length;
  12488. offset = 0;
  12489. if ( customAttribute.size === 1 ) {
  12490. for ( ca = 0; ca < cal; ca ++ ) {
  12491. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12492. }
  12493. } else if ( customAttribute.size === 2 ) {
  12494. for ( ca = 0; ca < cal; ca ++ ) {
  12495. value = customAttribute.value[ ca ];
  12496. customAttribute.array[ offset ] = value.x;
  12497. customAttribute.array[ offset + 1 ] = value.y;
  12498. offset += 2;
  12499. }
  12500. } else if ( customAttribute.size === 3 ) {
  12501. if ( customAttribute.type === "c" ) {
  12502. for ( ca = 0; ca < cal; ca ++ ) {
  12503. value = customAttribute.value[ ca ];
  12504. customAttribute.array[ offset ] = value.r;
  12505. customAttribute.array[ offset + 1 ] = value.g;
  12506. customAttribute.array[ offset + 2 ] = value.b;
  12507. offset += 3;
  12508. }
  12509. } else {
  12510. for ( ca = 0; ca < cal; ca ++ ) {
  12511. value = customAttribute.value[ ca ];
  12512. customAttribute.array[ offset ] = value.x;
  12513. customAttribute.array[ offset + 1 ] = value.y;
  12514. customAttribute.array[ offset + 2 ] = value.z;
  12515. offset += 3;
  12516. }
  12517. }
  12518. } else if ( customAttribute.size === 4 ) {
  12519. for ( ca = 0; ca < cal; ca ++ ) {
  12520. value = customAttribute.value[ ca ];
  12521. customAttribute.array[ offset ] = value.x;
  12522. customAttribute.array[ offset + 1 ] = value.y;
  12523. customAttribute.array[ offset + 2 ] = value.z;
  12524. customAttribute.array[ offset + 3 ] = value.w;
  12525. offset += 4;
  12526. }
  12527. }
  12528. }
  12529. }
  12530. }
  12531. }
  12532. if ( dirtyVertices || object.sortParticles ) {
  12533. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12534. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12535. }
  12536. if ( dirtyColors || object.sortParticles ) {
  12537. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12538. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12539. }
  12540. if ( customAttributes ) {
  12541. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12542. customAttribute = customAttributes[ i ];
  12543. if ( customAttribute.needsUpdate || object.sortParticles ) {
  12544. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12545. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12546. }
  12547. }
  12548. }
  12549. };
  12550. function setLineBuffers ( geometry, hint ) {
  12551. var v, c, d, vertex, offset, color,
  12552. vertices = geometry.vertices,
  12553. colors = geometry.colors,
  12554. lineDistances = geometry.lineDistances,
  12555. vl = vertices.length,
  12556. cl = colors.length,
  12557. dl = lineDistances.length,
  12558. vertexArray = geometry.__vertexArray,
  12559. colorArray = geometry.__colorArray,
  12560. lineDistanceArray = geometry.__lineDistanceArray,
  12561. dirtyVertices = geometry.verticesNeedUpdate,
  12562. dirtyColors = geometry.colorsNeedUpdate,
  12563. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  12564. customAttributes = geometry.__webglCustomAttributesList,
  12565. i, il,
  12566. a, ca, cal, value,
  12567. customAttribute;
  12568. if ( dirtyVertices ) {
  12569. for ( v = 0; v < vl; v ++ ) {
  12570. vertex = vertices[ v ];
  12571. offset = v * 3;
  12572. vertexArray[ offset ] = vertex.x;
  12573. vertexArray[ offset + 1 ] = vertex.y;
  12574. vertexArray[ offset + 2 ] = vertex.z;
  12575. }
  12576. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12577. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12578. }
  12579. if ( dirtyColors ) {
  12580. for ( c = 0; c < cl; c ++ ) {
  12581. color = colors[ c ];
  12582. offset = c * 3;
  12583. colorArray[ offset ] = color.r;
  12584. colorArray[ offset + 1 ] = color.g;
  12585. colorArray[ offset + 2 ] = color.b;
  12586. }
  12587. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12588. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12589. }
  12590. if ( dirtyLineDistances ) {
  12591. for ( d = 0; d < dl; d ++ ) {
  12592. lineDistanceArray[ d ] = lineDistances[ d ];
  12593. }
  12594. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  12595. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  12596. }
  12597. if ( customAttributes ) {
  12598. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12599. customAttribute = customAttributes[ i ];
  12600. if ( customAttribute.needsUpdate &&
  12601. ( customAttribute.boundTo === undefined ||
  12602. customAttribute.boundTo === "vertices" ) ) {
  12603. offset = 0;
  12604. cal = customAttribute.value.length;
  12605. if ( customAttribute.size === 1 ) {
  12606. for ( ca = 0; ca < cal; ca ++ ) {
  12607. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12608. }
  12609. } else if ( customAttribute.size === 2 ) {
  12610. for ( ca = 0; ca < cal; ca ++ ) {
  12611. value = customAttribute.value[ ca ];
  12612. customAttribute.array[ offset ] = value.x;
  12613. customAttribute.array[ offset + 1 ] = value.y;
  12614. offset += 2;
  12615. }
  12616. } else if ( customAttribute.size === 3 ) {
  12617. if ( customAttribute.type === "c" ) {
  12618. for ( ca = 0; ca < cal; ca ++ ) {
  12619. value = customAttribute.value[ ca ];
  12620. customAttribute.array[ offset ] = value.r;
  12621. customAttribute.array[ offset + 1 ] = value.g;
  12622. customAttribute.array[ offset + 2 ] = value.b;
  12623. offset += 3;
  12624. }
  12625. } else {
  12626. for ( ca = 0; ca < cal; ca ++ ) {
  12627. value = customAttribute.value[ ca ];
  12628. customAttribute.array[ offset ] = value.x;
  12629. customAttribute.array[ offset + 1 ] = value.y;
  12630. customAttribute.array[ offset + 2 ] = value.z;
  12631. offset += 3;
  12632. }
  12633. }
  12634. } else if ( customAttribute.size === 4 ) {
  12635. for ( ca = 0; ca < cal; ca ++ ) {
  12636. value = customAttribute.value[ ca ];
  12637. customAttribute.array[ offset ] = value.x;
  12638. customAttribute.array[ offset + 1 ] = value.y;
  12639. customAttribute.array[ offset + 2 ] = value.z;
  12640. customAttribute.array[ offset + 3 ] = value.w;
  12641. offset += 4;
  12642. }
  12643. }
  12644. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12645. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12646. }
  12647. }
  12648. }
  12649. };
  12650. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  12651. if ( ! geometryGroup.__inittedArrays ) {
  12652. return;
  12653. }
  12654. var normalType = bufferGuessNormalType( material ),
  12655. vertexColorType = bufferGuessVertexColorType( material ),
  12656. uvType = bufferGuessUVType( material ),
  12657. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  12658. var f, fl, fi, face,
  12659. vertexNormals, faceNormal, normal,
  12660. vertexColors, faceColor,
  12661. vertexTangents,
  12662. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  12663. c1, c2, c3, c4,
  12664. sw1, sw2, sw3, sw4,
  12665. si1, si2, si3, si4,
  12666. sa1, sa2, sa3, sa4,
  12667. sb1, sb2, sb3, sb4,
  12668. m, ml, i, il,
  12669. vn, uvi, uv2i,
  12670. vk, vkl, vka,
  12671. nka, chf, faceVertexNormals,
  12672. a,
  12673. vertexIndex = 0,
  12674. offset = 0,
  12675. offset_uv = 0,
  12676. offset_uv2 = 0,
  12677. offset_face = 0,
  12678. offset_normal = 0,
  12679. offset_tangent = 0,
  12680. offset_line = 0,
  12681. offset_color = 0,
  12682. offset_skin = 0,
  12683. offset_morphTarget = 0,
  12684. offset_custom = 0,
  12685. offset_customSrc = 0,
  12686. value,
  12687. vertexArray = geometryGroup.__vertexArray,
  12688. uvArray = geometryGroup.__uvArray,
  12689. uv2Array = geometryGroup.__uv2Array,
  12690. normalArray = geometryGroup.__normalArray,
  12691. tangentArray = geometryGroup.__tangentArray,
  12692. colorArray = geometryGroup.__colorArray,
  12693. skinIndexArray = geometryGroup.__skinIndexArray,
  12694. skinWeightArray = geometryGroup.__skinWeightArray,
  12695. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  12696. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  12697. customAttributes = geometryGroup.__webglCustomAttributesList,
  12698. customAttribute,
  12699. faceArray = geometryGroup.__faceArray,
  12700. lineArray = geometryGroup.__lineArray,
  12701. geometry = object.geometry, // this is shared for all chunks
  12702. dirtyVertices = geometry.verticesNeedUpdate,
  12703. dirtyElements = geometry.elementsNeedUpdate,
  12704. dirtyUvs = geometry.uvsNeedUpdate,
  12705. dirtyNormals = geometry.normalsNeedUpdate,
  12706. dirtyTangents = geometry.tangentsNeedUpdate,
  12707. dirtyColors = geometry.colorsNeedUpdate,
  12708. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  12709. vertices = geometry.vertices,
  12710. chunk_faces3 = geometryGroup.faces3,
  12711. obj_faces = geometry.faces,
  12712. obj_uvs = geometry.faceVertexUvs[ 0 ],
  12713. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  12714. obj_colors = geometry.colors,
  12715. obj_skinIndices = geometry.skinIndices,
  12716. obj_skinWeights = geometry.skinWeights,
  12717. morphTargets = geometry.morphTargets,
  12718. morphNormals = geometry.morphNormals;
  12719. if ( dirtyVertices ) {
  12720. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12721. face = obj_faces[ chunk_faces3[ f ] ];
  12722. v1 = vertices[ face.a ];
  12723. v2 = vertices[ face.b ];
  12724. v3 = vertices[ face.c ];
  12725. vertexArray[ offset ] = v1.x;
  12726. vertexArray[ offset + 1 ] = v1.y;
  12727. vertexArray[ offset + 2 ] = v1.z;
  12728. vertexArray[ offset + 3 ] = v2.x;
  12729. vertexArray[ offset + 4 ] = v2.y;
  12730. vertexArray[ offset + 5 ] = v2.z;
  12731. vertexArray[ offset + 6 ] = v3.x;
  12732. vertexArray[ offset + 7 ] = v3.y;
  12733. vertexArray[ offset + 8 ] = v3.z;
  12734. offset += 9;
  12735. }
  12736. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12737. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12738. }
  12739. if ( dirtyMorphTargets ) {
  12740. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  12741. offset_morphTarget = 0;
  12742. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12743. chf = chunk_faces3[ f ];
  12744. face = obj_faces[ chf ];
  12745. // morph positions
  12746. v1 = morphTargets[ vk ].vertices[ face.a ];
  12747. v2 = morphTargets[ vk ].vertices[ face.b ];
  12748. v3 = morphTargets[ vk ].vertices[ face.c ];
  12749. vka = morphTargetsArrays[ vk ];
  12750. vka[ offset_morphTarget ] = v1.x;
  12751. vka[ offset_morphTarget + 1 ] = v1.y;
  12752. vka[ offset_morphTarget + 2 ] = v1.z;
  12753. vka[ offset_morphTarget + 3 ] = v2.x;
  12754. vka[ offset_morphTarget + 4 ] = v2.y;
  12755. vka[ offset_morphTarget + 5 ] = v2.z;
  12756. vka[ offset_morphTarget + 6 ] = v3.x;
  12757. vka[ offset_morphTarget + 7 ] = v3.y;
  12758. vka[ offset_morphTarget + 8 ] = v3.z;
  12759. // morph normals
  12760. if ( material.morphNormals ) {
  12761. if ( needsSmoothNormals ) {
  12762. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  12763. n1 = faceVertexNormals.a;
  12764. n2 = faceVertexNormals.b;
  12765. n3 = faceVertexNormals.c;
  12766. } else {
  12767. n1 = morphNormals[ vk ].faceNormals[ chf ];
  12768. n2 = n1;
  12769. n3 = n1;
  12770. }
  12771. nka = morphNormalsArrays[ vk ];
  12772. nka[ offset_morphTarget ] = n1.x;
  12773. nka[ offset_morphTarget + 1 ] = n1.y;
  12774. nka[ offset_morphTarget + 2 ] = n1.z;
  12775. nka[ offset_morphTarget + 3 ] = n2.x;
  12776. nka[ offset_morphTarget + 4 ] = n2.y;
  12777. nka[ offset_morphTarget + 5 ] = n2.z;
  12778. nka[ offset_morphTarget + 6 ] = n3.x;
  12779. nka[ offset_morphTarget + 7 ] = n3.y;
  12780. nka[ offset_morphTarget + 8 ] = n3.z;
  12781. }
  12782. //
  12783. offset_morphTarget += 9;
  12784. }
  12785. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  12786. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  12787. if ( material.morphNormals ) {
  12788. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  12789. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  12790. }
  12791. }
  12792. }
  12793. if ( obj_skinWeights.length ) {
  12794. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12795. face = obj_faces[ chunk_faces3[ f ] ];
  12796. // weights
  12797. sw1 = obj_skinWeights[ face.a ];
  12798. sw2 = obj_skinWeights[ face.b ];
  12799. sw3 = obj_skinWeights[ face.c ];
  12800. skinWeightArray[ offset_skin ] = sw1.x;
  12801. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  12802. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  12803. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  12804. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  12805. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  12806. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  12807. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  12808. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  12809. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  12810. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  12811. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  12812. // indices
  12813. si1 = obj_skinIndices[ face.a ];
  12814. si2 = obj_skinIndices[ face.b ];
  12815. si3 = obj_skinIndices[ face.c ];
  12816. skinIndexArray[ offset_skin ] = si1.x;
  12817. skinIndexArray[ offset_skin + 1 ] = si1.y;
  12818. skinIndexArray[ offset_skin + 2 ] = si1.z;
  12819. skinIndexArray[ offset_skin + 3 ] = si1.w;
  12820. skinIndexArray[ offset_skin + 4 ] = si2.x;
  12821. skinIndexArray[ offset_skin + 5 ] = si2.y;
  12822. skinIndexArray[ offset_skin + 6 ] = si2.z;
  12823. skinIndexArray[ offset_skin + 7 ] = si2.w;
  12824. skinIndexArray[ offset_skin + 8 ] = si3.x;
  12825. skinIndexArray[ offset_skin + 9 ] = si3.y;
  12826. skinIndexArray[ offset_skin + 10 ] = si3.z;
  12827. skinIndexArray[ offset_skin + 11 ] = si3.w;
  12828. offset_skin += 12;
  12829. }
  12830. if ( offset_skin > 0 ) {
  12831. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  12832. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  12833. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  12834. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  12835. }
  12836. }
  12837. if ( dirtyColors && vertexColorType ) {
  12838. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12839. face = obj_faces[ chunk_faces3[ f ] ];
  12840. vertexColors = face.vertexColors;
  12841. faceColor = face.color;
  12842. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  12843. c1 = vertexColors[ 0 ];
  12844. c2 = vertexColors[ 1 ];
  12845. c3 = vertexColors[ 2 ];
  12846. } else {
  12847. c1 = faceColor;
  12848. c2 = faceColor;
  12849. c3 = faceColor;
  12850. }
  12851. colorArray[ offset_color ] = c1.r;
  12852. colorArray[ offset_color + 1 ] = c1.g;
  12853. colorArray[ offset_color + 2 ] = c1.b;
  12854. colorArray[ offset_color + 3 ] = c2.r;
  12855. colorArray[ offset_color + 4 ] = c2.g;
  12856. colorArray[ offset_color + 5 ] = c2.b;
  12857. colorArray[ offset_color + 6 ] = c3.r;
  12858. colorArray[ offset_color + 7 ] = c3.g;
  12859. colorArray[ offset_color + 8 ] = c3.b;
  12860. offset_color += 9;
  12861. }
  12862. if ( offset_color > 0 ) {
  12863. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12864. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12865. }
  12866. }
  12867. if ( dirtyTangents && geometry.hasTangents ) {
  12868. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12869. face = obj_faces[ chunk_faces3[ f ] ];
  12870. vertexTangents = face.vertexTangents;
  12871. t1 = vertexTangents[ 0 ];
  12872. t2 = vertexTangents[ 1 ];
  12873. t3 = vertexTangents[ 2 ];
  12874. tangentArray[ offset_tangent ] = t1.x;
  12875. tangentArray[ offset_tangent + 1 ] = t1.y;
  12876. tangentArray[ offset_tangent + 2 ] = t1.z;
  12877. tangentArray[ offset_tangent + 3 ] = t1.w;
  12878. tangentArray[ offset_tangent + 4 ] = t2.x;
  12879. tangentArray[ offset_tangent + 5 ] = t2.y;
  12880. tangentArray[ offset_tangent + 6 ] = t2.z;
  12881. tangentArray[ offset_tangent + 7 ] = t2.w;
  12882. tangentArray[ offset_tangent + 8 ] = t3.x;
  12883. tangentArray[ offset_tangent + 9 ] = t3.y;
  12884. tangentArray[ offset_tangent + 10 ] = t3.z;
  12885. tangentArray[ offset_tangent + 11 ] = t3.w;
  12886. offset_tangent += 12;
  12887. }
  12888. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12889. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  12890. }
  12891. if ( dirtyNormals && normalType ) {
  12892. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12893. face = obj_faces[ chunk_faces3[ f ] ];
  12894. vertexNormals = face.vertexNormals;
  12895. faceNormal = face.normal;
  12896. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  12897. for ( i = 0; i < 3; i ++ ) {
  12898. vn = vertexNormals[ i ];
  12899. normalArray[ offset_normal ] = vn.x;
  12900. normalArray[ offset_normal + 1 ] = vn.y;
  12901. normalArray[ offset_normal + 2 ] = vn.z;
  12902. offset_normal += 3;
  12903. }
  12904. } else {
  12905. for ( i = 0; i < 3; i ++ ) {
  12906. normalArray[ offset_normal ] = faceNormal.x;
  12907. normalArray[ offset_normal + 1 ] = faceNormal.y;
  12908. normalArray[ offset_normal + 2 ] = faceNormal.z;
  12909. offset_normal += 3;
  12910. }
  12911. }
  12912. }
  12913. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12914. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  12915. }
  12916. if ( dirtyUvs && obj_uvs && uvType ) {
  12917. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12918. fi = chunk_faces3[ f ];
  12919. uv = obj_uvs[ fi ];
  12920. if ( uv === undefined ) continue;
  12921. for ( i = 0; i < 3; i ++ ) {
  12922. uvi = uv[ i ];
  12923. uvArray[ offset_uv ] = uvi.x;
  12924. uvArray[ offset_uv + 1 ] = uvi.y;
  12925. offset_uv += 2;
  12926. }
  12927. }
  12928. if ( offset_uv > 0 ) {
  12929. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12930. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  12931. }
  12932. }
  12933. if ( dirtyUvs && obj_uvs2 && uvType ) {
  12934. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12935. fi = chunk_faces3[ f ];
  12936. uv2 = obj_uvs2[ fi ];
  12937. if ( uv2 === undefined ) continue;
  12938. for ( i = 0; i < 3; i ++ ) {
  12939. uv2i = uv2[ i ];
  12940. uv2Array[ offset_uv2 ] = uv2i.x;
  12941. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  12942. offset_uv2 += 2;
  12943. }
  12944. }
  12945. if ( offset_uv2 > 0 ) {
  12946. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12947. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  12948. }
  12949. }
  12950. if ( dirtyElements ) {
  12951. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12952. faceArray[ offset_face ] = vertexIndex;
  12953. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12954. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  12955. offset_face += 3;
  12956. lineArray[ offset_line ] = vertexIndex;
  12957. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  12958. lineArray[ offset_line + 2 ] = vertexIndex;
  12959. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  12960. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  12961. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  12962. offset_line += 6;
  12963. vertexIndex += 3;
  12964. }
  12965. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12966. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  12967. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  12968. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  12969. }
  12970. if ( customAttributes ) {
  12971. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12972. customAttribute = customAttributes[ i ];
  12973. if ( ! customAttribute.__original.needsUpdate ) continue;
  12974. offset_custom = 0;
  12975. offset_customSrc = 0;
  12976. if ( customAttribute.size === 1 ) {
  12977. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12978. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12979. face = obj_faces[ chunk_faces3[ f ] ];
  12980. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  12981. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  12982. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  12983. offset_custom += 3;
  12984. }
  12985. } else if ( customAttribute.boundTo === "faces" ) {
  12986. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12987. value = customAttribute.value[ chunk_faces3[ f ] ];
  12988. customAttribute.array[ offset_custom ] = value;
  12989. customAttribute.array[ offset_custom + 1 ] = value;
  12990. customAttribute.array[ offset_custom + 2 ] = value;
  12991. offset_custom += 3;
  12992. }
  12993. }
  12994. } else if ( customAttribute.size === 2 ) {
  12995. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12996. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12997. face = obj_faces[ chunk_faces3[ f ] ];
  12998. v1 = customAttribute.value[ face.a ];
  12999. v2 = customAttribute.value[ face.b ];
  13000. v3 = customAttribute.value[ face.c ];
  13001. customAttribute.array[ offset_custom ] = v1.x;
  13002. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13003. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13004. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13005. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13006. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13007. offset_custom += 6;
  13008. }
  13009. } else if ( customAttribute.boundTo === "faces" ) {
  13010. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13011. value = customAttribute.value[ chunk_faces3[ f ] ];
  13012. v1 = value;
  13013. v2 = value;
  13014. v3 = value;
  13015. customAttribute.array[ offset_custom ] = v1.x;
  13016. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13017. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13018. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13019. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13020. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13021. offset_custom += 6;
  13022. }
  13023. }
  13024. } else if ( customAttribute.size === 3 ) {
  13025. var pp;
  13026. if ( customAttribute.type === "c" ) {
  13027. pp = [ "r", "g", "b" ];
  13028. } else {
  13029. pp = [ "x", "y", "z" ];
  13030. }
  13031. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13032. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13033. face = obj_faces[ chunk_faces3[ f ] ];
  13034. v1 = customAttribute.value[ face.a ];
  13035. v2 = customAttribute.value[ face.b ];
  13036. v3 = customAttribute.value[ face.c ];
  13037. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13038. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13039. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13040. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13041. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13042. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13043. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13044. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13045. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13046. offset_custom += 9;
  13047. }
  13048. } else if ( customAttribute.boundTo === "faces" ) {
  13049. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13050. value = customAttribute.value[ chunk_faces3[ f ] ];
  13051. v1 = value;
  13052. v2 = value;
  13053. v3 = value;
  13054. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13055. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13056. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13057. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13058. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13059. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13060. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13061. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13062. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13063. offset_custom += 9;
  13064. }
  13065. } else if ( customAttribute.boundTo === "faceVertices" ) {
  13066. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13067. value = customAttribute.value[ chunk_faces3[ f ] ];
  13068. v1 = value[ 0 ];
  13069. v2 = value[ 1 ];
  13070. v3 = value[ 2 ];
  13071. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13072. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13073. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13074. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13075. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13076. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13077. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13078. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13079. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13080. offset_custom += 9;
  13081. }
  13082. }
  13083. } else if ( customAttribute.size === 4 ) {
  13084. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13085. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13086. face = obj_faces[ chunk_faces3[ f ] ];
  13087. v1 = customAttribute.value[ face.a ];
  13088. v2 = customAttribute.value[ face.b ];
  13089. v3 = customAttribute.value[ face.c ];
  13090. customAttribute.array[ offset_custom ] = v1.x;
  13091. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13092. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13093. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13094. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13095. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13096. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13097. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13098. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13099. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13100. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13101. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13102. offset_custom += 12;
  13103. }
  13104. } else if ( customAttribute.boundTo === "faces" ) {
  13105. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13106. value = customAttribute.value[ chunk_faces3[ f ] ];
  13107. v1 = value;
  13108. v2 = value;
  13109. v3 = value;
  13110. customAttribute.array[ offset_custom ] = v1.x;
  13111. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13112. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13113. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13114. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13115. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13116. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13117. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13118. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13119. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13120. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13121. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13122. offset_custom += 12;
  13123. }
  13124. } else if ( customAttribute.boundTo === "faceVertices" ) {
  13125. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13126. value = customAttribute.value[ chunk_faces3[ f ] ];
  13127. v1 = value[ 0 ];
  13128. v2 = value[ 1 ];
  13129. v3 = value[ 2 ];
  13130. customAttribute.array[ offset_custom ] = v1.x;
  13131. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13132. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13133. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13134. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13135. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13136. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13137. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13138. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13139. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13140. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13141. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13142. offset_custom += 12;
  13143. }
  13144. }
  13145. }
  13146. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  13147. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  13148. }
  13149. }
  13150. if ( dispose ) {
  13151. delete geometryGroup.__inittedArrays;
  13152. delete geometryGroup.__colorArray;
  13153. delete geometryGroup.__normalArray;
  13154. delete geometryGroup.__tangentArray;
  13155. delete geometryGroup.__uvArray;
  13156. delete geometryGroup.__uv2Array;
  13157. delete geometryGroup.__faceArray;
  13158. delete geometryGroup.__vertexArray;
  13159. delete geometryGroup.__lineArray;
  13160. delete geometryGroup.__skinIndexArray;
  13161. delete geometryGroup.__skinWeightArray;
  13162. }
  13163. };
  13164. // used by renderBufferDirect for THREE.Line
  13165. function setupLinesVertexAttributes( material, programAttributes, geometryAttributes, startIndex ) {
  13166. var attributeItem, attributeName, attributePointer, attributeSize;
  13167. for ( attributeName in programAttributes ) {
  13168. attributePointer = programAttributes[ attributeName ];
  13169. attributeItem = geometryAttributes[ attributeName ];
  13170. if ( attributePointer >= 0 ) {
  13171. if ( attributeItem ) {
  13172. attributeSize = attributeItem.itemSize;
  13173. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13174. enableAttribute( attributePointer );
  13175. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  13176. } else if ( material.defaultAttributeValues ) {
  13177. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13178. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13179. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13180. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13181. }
  13182. }
  13183. }
  13184. }
  13185. }
  13186. function setDirectBuffers ( geometry, hint, dispose ) {
  13187. var attributes = geometry.attributes;
  13188. var attributeName, attributeItem;
  13189. for ( attributeName in attributes ) {
  13190. attributeItem = attributes[ attributeName ];
  13191. if ( attributeItem.needsUpdate ) {
  13192. if ( attributeName === 'index' ) {
  13193. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer );
  13194. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint );
  13195. } else {
  13196. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13197. _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint );
  13198. }
  13199. attributeItem.needsUpdate = false;
  13200. }
  13201. if ( dispose && ! attributeItem.dynamic ) {
  13202. attributeItem.array = null;
  13203. }
  13204. }
  13205. };
  13206. // Buffer rendering
  13207. this.renderBufferImmediate = function ( object, program, material ) {
  13208. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  13209. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  13210. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  13211. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  13212. if ( object.hasPositions ) {
  13213. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  13214. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  13215. _gl.enableVertexAttribArray( program.attributes.position );
  13216. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13217. }
  13218. if ( object.hasNormals ) {
  13219. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  13220. if ( material.shading === THREE.FlatShading ) {
  13221. var nx, ny, nz,
  13222. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  13223. normalArray,
  13224. i, il = object.count * 3;
  13225. for( i = 0; i < il; i += 9 ) {
  13226. normalArray = object.normalArray;
  13227. nax = normalArray[ i ];
  13228. nay = normalArray[ i + 1 ];
  13229. naz = normalArray[ i + 2 ];
  13230. nbx = normalArray[ i + 3 ];
  13231. nby = normalArray[ i + 4 ];
  13232. nbz = normalArray[ i + 5 ];
  13233. ncx = normalArray[ i + 6 ];
  13234. ncy = normalArray[ i + 7 ];
  13235. ncz = normalArray[ i + 8 ];
  13236. nx = ( nax + nbx + ncx ) / 3;
  13237. ny = ( nay + nby + ncy ) / 3;
  13238. nz = ( naz + nbz + ncz ) / 3;
  13239. normalArray[ i ] = nx;
  13240. normalArray[ i + 1 ] = ny;
  13241. normalArray[ i + 2 ] = nz;
  13242. normalArray[ i + 3 ] = nx;
  13243. normalArray[ i + 4 ] = ny;
  13244. normalArray[ i + 5 ] = nz;
  13245. normalArray[ i + 6 ] = nx;
  13246. normalArray[ i + 7 ] = ny;
  13247. normalArray[ i + 8 ] = nz;
  13248. }
  13249. }
  13250. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  13251. _gl.enableVertexAttribArray( program.attributes.normal );
  13252. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13253. }
  13254. if ( object.hasUvs && material.map ) {
  13255. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  13256. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  13257. _gl.enableVertexAttribArray( program.attributes.uv );
  13258. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13259. }
  13260. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  13261. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  13262. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  13263. _gl.enableVertexAttribArray( program.attributes.color );
  13264. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13265. }
  13266. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  13267. object.count = 0;
  13268. };
  13269. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  13270. if ( material.visible === false ) return;
  13271. var linewidth, a, attribute;
  13272. var attributeItem, attributeName, attributePointer, attributeSize;
  13273. var program = setProgram( camera, lights, fog, material, object );
  13274. var programAttributes = program.attributes;
  13275. var geometryAttributes = geometry.attributes;
  13276. var updateBuffers = false,
  13277. wireframeBit = material.wireframe ? 1 : 0,
  13278. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13279. if ( geometryHash !== _currentGeometryGroupHash ) {
  13280. _currentGeometryGroupHash = geometryHash;
  13281. updateBuffers = true;
  13282. }
  13283. if ( updateBuffers ) {
  13284. disableAttributes();
  13285. }
  13286. // render mesh
  13287. if ( object instanceof THREE.Mesh ) {
  13288. var index = geometryAttributes[ "index" ];
  13289. // indexed triangles
  13290. if ( index ) {
  13291. var offsets = geometry.offsets;
  13292. // if there is more than 1 chunk
  13293. // must set attribute pointers to use new offsets for each chunk
  13294. // even if geometry and materials didn't change
  13295. if ( offsets.length > 1 ) updateBuffers = true;
  13296. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13297. var startIndex = offsets[ i ].index;
  13298. if ( updateBuffers ) {
  13299. for ( attributeName in programAttributes ) {
  13300. attributePointer = programAttributes[ attributeName ];
  13301. attributeItem = geometryAttributes[ attributeName ];
  13302. if ( attributePointer >= 0 ) {
  13303. if ( attributeItem ) {
  13304. attributeSize = attributeItem.itemSize;
  13305. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13306. enableAttribute( attributePointer );
  13307. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  13308. } else if ( material.defaultAttributeValues ) {
  13309. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13310. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13311. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13312. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13313. }
  13314. }
  13315. }
  13316. }
  13317. // indices
  13318. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13319. }
  13320. // render indexed triangles
  13321. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  13322. _this.info.render.calls ++;
  13323. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13324. _this.info.render.faces += offsets[ i ].count / 3;
  13325. }
  13326. // non-indexed triangles
  13327. } else {
  13328. if ( updateBuffers ) {
  13329. for ( attributeName in programAttributes ) {
  13330. if ( attributeName === 'index') continue;
  13331. attributePointer = programAttributes[ attributeName ];
  13332. attributeItem = geometryAttributes[ attributeName ];
  13333. if ( attributePointer >= 0 ) {
  13334. if ( attributeItem ) {
  13335. attributeSize = attributeItem.itemSize;
  13336. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13337. enableAttribute( attributePointer );
  13338. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13339. } else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
  13340. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13341. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13342. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13343. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13344. }
  13345. }
  13346. }
  13347. }
  13348. }
  13349. var position = geometry.attributes[ "position" ];
  13350. // render non-indexed triangles
  13351. _gl.drawArrays( _gl.TRIANGLES, 0, position.array.length / 3 );
  13352. _this.info.render.calls ++;
  13353. _this.info.render.vertices += position.array.length / 3;
  13354. _this.info.render.faces += position.array.length / 3 / 3;
  13355. }
  13356. // render particles
  13357. } else if ( object instanceof THREE.ParticleSystem ) {
  13358. if ( updateBuffers ) {
  13359. for ( attributeName in programAttributes ) {
  13360. attributePointer = programAttributes[ attributeName ];
  13361. attributeItem = geometryAttributes[ attributeName ];
  13362. if ( attributePointer >= 0 ) {
  13363. if ( attributeItem ) {
  13364. attributeSize = attributeItem.itemSize;
  13365. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13366. enableAttribute( attributePointer );
  13367. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13368. } else if ( material.defaultAttributeValues && material.defaultAttributeValues[ attributeName ] ) {
  13369. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13370. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13371. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13372. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13373. }
  13374. }
  13375. }
  13376. }
  13377. }
  13378. var position = geometryAttributes[ "position" ];
  13379. // render particles
  13380. _gl.drawArrays( _gl.POINTS, 0, position.array.length / 3 );
  13381. _this.info.render.calls ++;
  13382. _this.info.render.points += position.array.length / 3;
  13383. } else if ( object instanceof THREE.Line ) {
  13384. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13385. setLineWidth( material.linewidth );
  13386. var index = geometryAttributes[ "index" ];
  13387. // indexed lines
  13388. if ( index ) {
  13389. var offsets = geometry.offsets;
  13390. // if there is more than 1 chunk
  13391. // must set attribute pointers to use new offsets for each chunk
  13392. // even if geometry and materials didn't change
  13393. if ( offsets.length > 1 ) updateBuffers = true;
  13394. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13395. var startIndex = offsets[ i ].index;
  13396. if ( updateBuffers ) {
  13397. setupLinesVertexAttributes(material, programAttributes, geometryAttributes, startIndex);
  13398. // indices
  13399. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13400. }
  13401. // render indexed lines
  13402. _gl.drawElements( _gl.LINES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16Array
  13403. _this.info.render.calls ++;
  13404. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13405. }
  13406. }
  13407. // non-indexed lines
  13408. else {
  13409. if ( updateBuffers ) {
  13410. setupLinesVertexAttributes(material, programAttributes, geometryAttributes, 0);
  13411. }
  13412. var position = geometryAttributes[ "position" ];
  13413. _gl.drawArrays( primitives, 0, position.array.length / 3 );
  13414. _this.info.render.calls ++;
  13415. _this.info.render.points += position.array.length;
  13416. }
  13417. }
  13418. };
  13419. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  13420. if ( material.visible === false ) return;
  13421. var linewidth, a, attribute, i, il;
  13422. var program = setProgram( camera, lights, fog, material, object );
  13423. var attributes = program.attributes;
  13424. var updateBuffers = false,
  13425. wireframeBit = material.wireframe ? 1 : 0,
  13426. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13427. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  13428. _currentGeometryGroupHash = geometryGroupHash;
  13429. updateBuffers = true;
  13430. }
  13431. if ( updateBuffers ) {
  13432. disableAttributes();
  13433. }
  13434. // vertices
  13435. if ( !material.morphTargets && attributes.position >= 0 ) {
  13436. if ( updateBuffers ) {
  13437. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13438. enableAttribute( attributes.position );
  13439. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13440. }
  13441. } else {
  13442. if ( object.morphTargetBase ) {
  13443. setupMorphTargets( material, geometryGroup, object );
  13444. }
  13445. }
  13446. if ( updateBuffers ) {
  13447. // custom attributes
  13448. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  13449. if ( geometryGroup.__webglCustomAttributesList ) {
  13450. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  13451. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  13452. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  13453. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  13454. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  13455. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  13456. }
  13457. }
  13458. }
  13459. // colors
  13460. if ( attributes.color >= 0 ) {
  13461. if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) {
  13462. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13463. enableAttribute( attributes.color );
  13464. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13465. } else if ( material.defaultAttributeValues ) {
  13466. _gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color );
  13467. }
  13468. }
  13469. // normals
  13470. if ( attributes.normal >= 0 ) {
  13471. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13472. enableAttribute( attributes.normal );
  13473. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13474. }
  13475. // tangents
  13476. if ( attributes.tangent >= 0 ) {
  13477. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13478. enableAttribute( attributes.tangent );
  13479. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  13480. }
  13481. // uvs
  13482. if ( attributes.uv >= 0 ) {
  13483. if ( object.geometry.faceVertexUvs[0] ) {
  13484. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13485. enableAttribute( attributes.uv );
  13486. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13487. } else if ( material.defaultAttributeValues ) {
  13488. _gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv );
  13489. }
  13490. }
  13491. if ( attributes.uv2 >= 0 ) {
  13492. if ( object.geometry.faceVertexUvs[1] ) {
  13493. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13494. enableAttribute( attributes.uv2 );
  13495. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  13496. } else if ( material.defaultAttributeValues ) {
  13497. _gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 );
  13498. }
  13499. }
  13500. if ( material.skinning &&
  13501. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  13502. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13503. enableAttribute( attributes.skinIndex );
  13504. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  13505. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13506. enableAttribute( attributes.skinWeight );
  13507. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  13508. }
  13509. // line distances
  13510. if ( attributes.lineDistance >= 0 ) {
  13511. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  13512. enableAttribute( attributes.lineDistance );
  13513. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  13514. }
  13515. }
  13516. // render mesh
  13517. if ( object instanceof THREE.Mesh ) {
  13518. // wireframe
  13519. if ( material.wireframe ) {
  13520. setLineWidth( material.wireframeLinewidth );
  13521. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13522. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  13523. // triangles
  13524. } else {
  13525. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13526. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  13527. }
  13528. _this.info.render.calls ++;
  13529. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  13530. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  13531. // render lines
  13532. } else if ( object instanceof THREE.Line ) {
  13533. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13534. setLineWidth( material.linewidth );
  13535. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  13536. _this.info.render.calls ++;
  13537. // render particles
  13538. } else if ( object instanceof THREE.ParticleSystem ) {
  13539. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  13540. _this.info.render.calls ++;
  13541. _this.info.render.points += geometryGroup.__webglParticleCount;
  13542. }
  13543. };
  13544. function enableAttribute( attribute ) {
  13545. if ( ! _enabledAttributes[ attribute ] ) {
  13546. _gl.enableVertexAttribArray( attribute );
  13547. _enabledAttributes[ attribute ] = true;
  13548. }
  13549. };
  13550. function disableAttributes() {
  13551. for ( var attribute in _enabledAttributes ) {
  13552. if ( _enabledAttributes[ attribute ] ) {
  13553. _gl.disableVertexAttribArray( attribute );
  13554. _enabledAttributes[ attribute ] = false;
  13555. }
  13556. }
  13557. };
  13558. function setupMorphTargets ( material, geometryGroup, object ) {
  13559. // set base
  13560. var attributes = material.program.attributes;
  13561. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  13562. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  13563. enableAttribute( attributes.position );
  13564. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13565. } else if ( attributes.position >= 0 ) {
  13566. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13567. enableAttribute( attributes.position );
  13568. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13569. }
  13570. if ( object.morphTargetForcedOrder.length ) {
  13571. // set forced order
  13572. var m = 0;
  13573. var order = object.morphTargetForcedOrder;
  13574. var influences = object.morphTargetInfluences;
  13575. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  13576. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13577. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  13578. enableAttribute( attributes[ "morphTarget" + m ] );
  13579. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13580. }
  13581. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13582. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  13583. enableAttribute( attributes[ "morphNormal" + m ] );
  13584. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13585. }
  13586. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  13587. m ++;
  13588. }
  13589. } else {
  13590. // find the most influencing
  13591. var influence, activeInfluenceIndices = [];
  13592. var influences = object.morphTargetInfluences;
  13593. var i, il = influences.length;
  13594. for ( i = 0; i < il; i ++ ) {
  13595. influence = influences[ i ];
  13596. if ( influence > 0 ) {
  13597. activeInfluenceIndices.push( [ influence, i ] );
  13598. }
  13599. }
  13600. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  13601. activeInfluenceIndices.sort( numericalSort );
  13602. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  13603. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  13604. activeInfluenceIndices.sort( numericalSort );
  13605. } else if ( activeInfluenceIndices.length === 0 ) {
  13606. activeInfluenceIndices.push( [ 0, 0 ] );
  13607. };
  13608. var influenceIndex, m = 0;
  13609. while ( m < material.numSupportedMorphTargets ) {
  13610. if ( activeInfluenceIndices[ m ] ) {
  13611. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  13612. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13613. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  13614. enableAttribute( attributes[ "morphTarget" + m ] );
  13615. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13616. }
  13617. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13618. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  13619. enableAttribute( attributes[ "morphNormal" + m ] );
  13620. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13621. }
  13622. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  13623. } else {
  13624. /*
  13625. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13626. if ( material.morphNormals ) {
  13627. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13628. }
  13629. */
  13630. object.__webglMorphTargetInfluences[ m ] = 0;
  13631. }
  13632. m ++;
  13633. }
  13634. }
  13635. // load updated influences uniform
  13636. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  13637. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  13638. }
  13639. };
  13640. // Sorting
  13641. function painterSortStable ( a, b ) {
  13642. if ( a.z !== b.z ) {
  13643. return b.z - a.z;
  13644. } else {
  13645. return a.id - b.id;
  13646. }
  13647. };
  13648. function numericalSort ( a, b ) {
  13649. return b[ 0 ] - a[ 0 ];
  13650. };
  13651. // Rendering
  13652. this.render = function ( scene, camera, renderTarget, forceClear ) {
  13653. if ( camera instanceof THREE.Camera === false ) {
  13654. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  13655. return;
  13656. }
  13657. var i, il,
  13658. webglObject, object,
  13659. renderList,
  13660. lights = scene.__lights,
  13661. fog = scene.fog;
  13662. // reset caching for this frame
  13663. _currentMaterialId = -1;
  13664. _lightsNeedUpdate = true;
  13665. // update scene graph
  13666. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  13667. // update camera matrices and frustum
  13668. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  13669. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  13670. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  13671. _frustum.setFromMatrix( _projScreenMatrix );
  13672. // update WebGL objects
  13673. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  13674. // custom render plugins (pre pass)
  13675. renderPlugins( this.renderPluginsPre, scene, camera );
  13676. //
  13677. _this.info.render.calls = 0;
  13678. _this.info.render.vertices = 0;
  13679. _this.info.render.faces = 0;
  13680. _this.info.render.points = 0;
  13681. this.setRenderTarget( renderTarget );
  13682. if ( this.autoClear || forceClear ) {
  13683. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  13684. }
  13685. // set matrices for regular objects (frustum culled)
  13686. renderList = scene.__webglObjects;
  13687. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13688. webglObject = renderList[ i ];
  13689. object = webglObject.object;
  13690. webglObject.id = i;
  13691. webglObject.render = false;
  13692. if ( object.visible ) {
  13693. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  13694. setupMatrices( object, camera );
  13695. unrollBufferMaterial( webglObject );
  13696. webglObject.render = true;
  13697. if ( this.sortObjects === true ) {
  13698. if ( object.renderDepth !== null ) {
  13699. webglObject.z = object.renderDepth;
  13700. } else {
  13701. _vector3.setFromMatrixPosition( object.matrixWorld );
  13702. _vector3.applyProjection( _projScreenMatrix );
  13703. webglObject.z = _vector3.z;
  13704. }
  13705. }
  13706. }
  13707. }
  13708. }
  13709. if ( this.sortObjects ) {
  13710. renderList.sort( painterSortStable );
  13711. }
  13712. // set matrices for immediate objects
  13713. renderList = scene.__webglObjectsImmediate;
  13714. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13715. webglObject = renderList[ i ];
  13716. object = webglObject.object;
  13717. if ( object.visible ) {
  13718. setupMatrices( object, camera );
  13719. unrollImmediateBufferMaterial( webglObject );
  13720. }
  13721. }
  13722. if ( scene.overrideMaterial ) {
  13723. var material = scene.overrideMaterial;
  13724. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13725. this.setDepthTest( material.depthTest );
  13726. this.setDepthWrite( material.depthWrite );
  13727. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13728. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  13729. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  13730. } else {
  13731. var material = null;
  13732. // opaque pass (front-to-back order)
  13733. this.setBlending( THREE.NoBlending );
  13734. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  13735. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  13736. // transparent pass (back-to-front order)
  13737. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  13738. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  13739. }
  13740. // custom render plugins (post pass)
  13741. renderPlugins( this.renderPluginsPost, scene, camera );
  13742. // Generate mipmap if we're using any kind of mipmap filtering
  13743. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  13744. updateRenderTargetMipmap( renderTarget );
  13745. }
  13746. // Ensure depth buffer writing is enabled so it can be cleared on next render
  13747. this.setDepthTest( true );
  13748. this.setDepthWrite( true );
  13749. // _gl.finish();
  13750. };
  13751. function renderPlugins( plugins, scene, camera ) {
  13752. if ( ! plugins.length ) return;
  13753. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  13754. // reset state for plugin (to start from clean slate)
  13755. _currentProgram = null;
  13756. _currentCamera = null;
  13757. _oldBlending = -1;
  13758. _oldDepthTest = -1;
  13759. _oldDepthWrite = -1;
  13760. _oldDoubleSided = -1;
  13761. _oldFlipSided = -1;
  13762. _currentGeometryGroupHash = -1;
  13763. _currentMaterialId = -1;
  13764. _lightsNeedUpdate = true;
  13765. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  13766. // reset state after plugin (anything could have changed)
  13767. _currentProgram = null;
  13768. _currentCamera = null;
  13769. _oldBlending = -1;
  13770. _oldDepthTest = -1;
  13771. _oldDepthWrite = -1;
  13772. _oldDoubleSided = -1;
  13773. _oldFlipSided = -1;
  13774. _currentGeometryGroupHash = -1;
  13775. _currentMaterialId = -1;
  13776. _lightsNeedUpdate = true;
  13777. }
  13778. };
  13779. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13780. var webglObject, object, buffer, material, start, end, delta;
  13781. if ( reverse ) {
  13782. start = renderList.length - 1;
  13783. end = -1;
  13784. delta = -1;
  13785. } else {
  13786. start = 0;
  13787. end = renderList.length;
  13788. delta = 1;
  13789. }
  13790. for ( var i = start; i !== end; i += delta ) {
  13791. webglObject = renderList[ i ];
  13792. if ( webglObject.render ) {
  13793. object = webglObject.object;
  13794. buffer = webglObject.buffer;
  13795. if ( overrideMaterial ) {
  13796. material = overrideMaterial;
  13797. } else {
  13798. material = webglObject[ materialType ];
  13799. if ( ! material ) continue;
  13800. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13801. _this.setDepthTest( material.depthTest );
  13802. _this.setDepthWrite( material.depthWrite );
  13803. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13804. }
  13805. _this.setMaterialFaces( material );
  13806. if ( buffer instanceof THREE.BufferGeometry ) {
  13807. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  13808. } else {
  13809. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  13810. }
  13811. }
  13812. }
  13813. };
  13814. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13815. var webglObject, object, material, program;
  13816. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  13817. webglObject = renderList[ i ];
  13818. object = webglObject.object;
  13819. if ( object.visible ) {
  13820. if ( overrideMaterial ) {
  13821. material = overrideMaterial;
  13822. } else {
  13823. material = webglObject[ materialType ];
  13824. if ( ! material ) continue;
  13825. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13826. _this.setDepthTest( material.depthTest );
  13827. _this.setDepthWrite( material.depthWrite );
  13828. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13829. }
  13830. _this.renderImmediateObject( camera, lights, fog, material, object );
  13831. }
  13832. }
  13833. };
  13834. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  13835. var program = setProgram( camera, lights, fog, material, object );
  13836. _currentGeometryGroupHash = -1;
  13837. _this.setMaterialFaces( material );
  13838. if ( object.immediateRenderCallback ) {
  13839. object.immediateRenderCallback( program, _gl, _frustum );
  13840. } else {
  13841. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  13842. }
  13843. };
  13844. function unrollImmediateBufferMaterial ( globject ) {
  13845. var object = globject.object,
  13846. material = object.material;
  13847. if ( material.transparent ) {
  13848. globject.transparent = material;
  13849. globject.opaque = null;
  13850. } else {
  13851. globject.opaque = material;
  13852. globject.transparent = null;
  13853. }
  13854. };
  13855. function unrollBufferMaterial ( globject ) {
  13856. var object = globject.object,
  13857. buffer = globject.buffer,
  13858. material, materialIndex, meshMaterial;
  13859. meshMaterial = object.material;
  13860. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  13861. materialIndex = buffer.materialIndex;
  13862. material = meshMaterial.materials[ materialIndex ];
  13863. if ( material.transparent ) {
  13864. globject.transparent = material;
  13865. globject.opaque = null;
  13866. } else {
  13867. globject.opaque = material;
  13868. globject.transparent = null;
  13869. }
  13870. } else {
  13871. material = meshMaterial;
  13872. if ( material ) {
  13873. if ( material.transparent ) {
  13874. globject.transparent = material;
  13875. globject.opaque = null;
  13876. } else {
  13877. globject.opaque = material;
  13878. globject.transparent = null;
  13879. }
  13880. }
  13881. }
  13882. };
  13883. // Geometry splitting
  13884. function sortFacesByMaterial ( geometry, material ) {
  13885. var f, fl, face, materialIndex, vertices,
  13886. groupHash, hash_map = {};
  13887. var numMorphTargets = geometry.morphTargets.length;
  13888. var numMorphNormals = geometry.morphNormals.length;
  13889. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  13890. geometry.geometryGroups = {};
  13891. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  13892. face = geometry.faces[ f ];
  13893. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  13894. if ( hash_map[ materialIndex ] === undefined ) {
  13895. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  13896. }
  13897. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13898. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13899. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13900. }
  13901. vertices = 3;
  13902. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  13903. hash_map[ materialIndex ].counter += 1;
  13904. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  13905. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  13906. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  13907. }
  13908. }
  13909. geometry.geometryGroups[ groupHash ].faces3.push( f );
  13910. geometry.geometryGroups[ groupHash ].vertices += vertices;
  13911. }
  13912. geometry.geometryGroupsList = [];
  13913. for ( var g in geometry.geometryGroups ) {
  13914. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  13915. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  13916. }
  13917. };
  13918. // Objects refresh
  13919. this.initWebGLObjects = function ( scene ) {
  13920. if ( !scene.__webglObjects ) {
  13921. scene.__webglObjects = [];
  13922. scene.__webglObjectsImmediate = [];
  13923. scene.__webglSprites = [];
  13924. scene.__webglFlares = [];
  13925. }
  13926. while ( scene.__objectsAdded.length ) {
  13927. addObject( scene.__objectsAdded[ 0 ], scene );
  13928. scene.__objectsAdded.splice( 0, 1 );
  13929. }
  13930. while ( scene.__objectsRemoved.length ) {
  13931. removeObject( scene.__objectsRemoved[ 0 ], scene );
  13932. scene.__objectsRemoved.splice( 0, 1 );
  13933. }
  13934. // update must be called after objects adding / removal
  13935. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  13936. var object = scene.__webglObjects[ o ].object;
  13937. // TODO: Remove this hack (WebGLRenderer refactoring)
  13938. if ( object.__webglInit === undefined ) {
  13939. if ( object.__webglActive !== undefined ) {
  13940. removeObject( object, scene );
  13941. }
  13942. addObject( object, scene );
  13943. }
  13944. updateObject( object );
  13945. }
  13946. };
  13947. // Objects adding
  13948. function addObject( object, scene ) {
  13949. var g, geometry, material, geometryGroup;
  13950. if ( object.__webglInit === undefined ) {
  13951. object.__webglInit = true;
  13952. object._modelViewMatrix = new THREE.Matrix4();
  13953. object._normalMatrix = new THREE.Matrix3();
  13954. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  13955. object.geometry.__webglInit = true;
  13956. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  13957. }
  13958. geometry = object.geometry;
  13959. if ( geometry === undefined ) {
  13960. // fail silently for now
  13961. } else if ( geometry instanceof THREE.BufferGeometry ) {
  13962. initDirectBuffers( geometry );
  13963. } else if ( object instanceof THREE.Mesh ) {
  13964. material = object.material;
  13965. if ( geometry.geometryGroups === undefined ) {
  13966. sortFacesByMaterial( geometry, material );
  13967. }
  13968. // create separate VBOs per geometry chunk
  13969. for ( g in geometry.geometryGroups ) {
  13970. geometryGroup = geometry.geometryGroups[ g ];
  13971. // initialise VBO on the first access
  13972. if ( ! geometryGroup.__webglVertexBuffer ) {
  13973. createMeshBuffers( geometryGroup );
  13974. initMeshBuffers( geometryGroup, object );
  13975. geometry.verticesNeedUpdate = true;
  13976. geometry.morphTargetsNeedUpdate = true;
  13977. geometry.elementsNeedUpdate = true;
  13978. geometry.uvsNeedUpdate = true;
  13979. geometry.normalsNeedUpdate = true;
  13980. geometry.tangentsNeedUpdate = true;
  13981. geometry.colorsNeedUpdate = true;
  13982. }
  13983. }
  13984. } else if ( object instanceof THREE.Line ) {
  13985. if ( ! geometry.__webglVertexBuffer ) {
  13986. createLineBuffers( geometry );
  13987. initLineBuffers( geometry, object );
  13988. geometry.verticesNeedUpdate = true;
  13989. geometry.colorsNeedUpdate = true;
  13990. geometry.lineDistancesNeedUpdate = true;
  13991. }
  13992. } else if ( object instanceof THREE.ParticleSystem ) {
  13993. if ( ! geometry.__webglVertexBuffer ) {
  13994. createParticleBuffers( geometry );
  13995. initParticleBuffers( geometry, object );
  13996. geometry.verticesNeedUpdate = true;
  13997. geometry.colorsNeedUpdate = true;
  13998. }
  13999. }
  14000. }
  14001. if ( object.__webglActive === undefined ) {
  14002. if ( object instanceof THREE.Mesh ) {
  14003. geometry = object.geometry;
  14004. if ( geometry instanceof THREE.BufferGeometry ) {
  14005. addBuffer( scene.__webglObjects, geometry, object );
  14006. } else if ( geometry instanceof THREE.Geometry ) {
  14007. for ( g in geometry.geometryGroups ) {
  14008. geometryGroup = geometry.geometryGroups[ g ];
  14009. addBuffer( scene.__webglObjects, geometryGroup, object );
  14010. }
  14011. }
  14012. } else if ( object instanceof THREE.Line ||
  14013. object instanceof THREE.ParticleSystem ) {
  14014. geometry = object.geometry;
  14015. addBuffer( scene.__webglObjects, geometry, object );
  14016. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14017. addBufferImmediate( scene.__webglObjectsImmediate, object );
  14018. } else if ( object instanceof THREE.Sprite ) {
  14019. scene.__webglSprites.push( object );
  14020. } else if ( object instanceof THREE.LensFlare ) {
  14021. scene.__webglFlares.push( object );
  14022. }
  14023. object.__webglActive = true;
  14024. }
  14025. };
  14026. function addBuffer( objlist, buffer, object ) {
  14027. objlist.push(
  14028. {
  14029. id: null,
  14030. buffer: buffer,
  14031. object: object,
  14032. opaque: null,
  14033. transparent: null,
  14034. z: 0
  14035. }
  14036. );
  14037. };
  14038. function addBufferImmediate( objlist, object ) {
  14039. objlist.push(
  14040. {
  14041. id: null,
  14042. object: object,
  14043. opaque: null,
  14044. transparent: null,
  14045. z: 0
  14046. }
  14047. );
  14048. };
  14049. // Objects updates
  14050. function updateObject( object ) {
  14051. var geometry = object.geometry,
  14052. geometryGroup, customAttributesDirty, material;
  14053. if ( geometry instanceof THREE.BufferGeometry ) {
  14054. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  14055. } else if ( object instanceof THREE.Mesh ) {
  14056. // check all geometry groups
  14057. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  14058. geometryGroup = geometry.geometryGroupsList[ i ];
  14059. material = getBufferMaterial( object, geometryGroup );
  14060. if ( geometry.buffersNeedUpdate ) {
  14061. initMeshBuffers( geometryGroup, object );
  14062. }
  14063. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14064. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  14065. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  14066. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  14067. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  14068. }
  14069. }
  14070. geometry.verticesNeedUpdate = false;
  14071. geometry.morphTargetsNeedUpdate = false;
  14072. geometry.elementsNeedUpdate = false;
  14073. geometry.uvsNeedUpdate = false;
  14074. geometry.normalsNeedUpdate = false;
  14075. geometry.colorsNeedUpdate = false;
  14076. geometry.tangentsNeedUpdate = false;
  14077. geometry.buffersNeedUpdate = false;
  14078. material.attributes && clearCustomAttributes( material );
  14079. } else if ( object instanceof THREE.Line ) {
  14080. material = getBufferMaterial( object, geometry );
  14081. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14082. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  14083. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  14084. }
  14085. geometry.verticesNeedUpdate = false;
  14086. geometry.colorsNeedUpdate = false;
  14087. geometry.lineDistancesNeedUpdate = false;
  14088. material.attributes && clearCustomAttributes( material );
  14089. } else if ( object instanceof THREE.ParticleSystem ) {
  14090. material = getBufferMaterial( object, geometry );
  14091. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14092. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  14093. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  14094. }
  14095. geometry.verticesNeedUpdate = false;
  14096. geometry.colorsNeedUpdate = false;
  14097. material.attributes && clearCustomAttributes( material );
  14098. }
  14099. };
  14100. // Objects updates - custom attributes check
  14101. function areCustomAttributesDirty( material ) {
  14102. for ( var a in material.attributes ) {
  14103. if ( material.attributes[ a ].needsUpdate ) return true;
  14104. }
  14105. return false;
  14106. };
  14107. function clearCustomAttributes( material ) {
  14108. for ( var a in material.attributes ) {
  14109. material.attributes[ a ].needsUpdate = false;
  14110. }
  14111. };
  14112. // Objects removal
  14113. function removeObject( object, scene ) {
  14114. if ( object instanceof THREE.Mesh ||
  14115. object instanceof THREE.ParticleSystem ||
  14116. object instanceof THREE.Line ) {
  14117. removeInstances( scene.__webglObjects, object );
  14118. } else if ( object instanceof THREE.Sprite ) {
  14119. removeInstancesDirect( scene.__webglSprites, object );
  14120. } else if ( object instanceof THREE.LensFlare ) {
  14121. removeInstancesDirect( scene.__webglFlares, object );
  14122. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14123. removeInstances( scene.__webglObjectsImmediate, object );
  14124. }
  14125. delete object.__webglActive;
  14126. };
  14127. function removeInstances( objlist, object ) {
  14128. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  14129. if ( objlist[ o ].object === object ) {
  14130. objlist.splice( o, 1 );
  14131. }
  14132. }
  14133. };
  14134. function removeInstancesDirect( objlist, object ) {
  14135. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  14136. if ( objlist[ o ] === object ) {
  14137. objlist.splice( o, 1 );
  14138. }
  14139. }
  14140. };
  14141. // Materials
  14142. this.initMaterial = function ( material, lights, fog, object ) {
  14143. material.addEventListener( 'dispose', onMaterialDispose );
  14144. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  14145. if ( material instanceof THREE.MeshDepthMaterial ) {
  14146. shaderID = 'depth';
  14147. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14148. shaderID = 'normal';
  14149. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  14150. shaderID = 'basic';
  14151. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14152. shaderID = 'lambert';
  14153. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14154. shaderID = 'phong';
  14155. } else if ( material instanceof THREE.LineBasicMaterial ) {
  14156. shaderID = 'basic';
  14157. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14158. shaderID = 'dashed';
  14159. } else if ( material instanceof THREE.ParticleSystemMaterial ) {
  14160. shaderID = 'particle_basic';
  14161. }
  14162. if ( shaderID ) {
  14163. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  14164. }
  14165. // heuristics to create shader parameters according to lights in the scene
  14166. // (not to blow over maxLights budget)
  14167. maxLightCount = allocateLights( lights );
  14168. maxShadows = allocateShadows( lights );
  14169. maxBones = allocateBones( object );
  14170. parameters = {
  14171. map: !!material.map,
  14172. envMap: !!material.envMap,
  14173. lightMap: !!material.lightMap,
  14174. bumpMap: !!material.bumpMap,
  14175. normalMap: !!material.normalMap,
  14176. specularMap: !!material.specularMap,
  14177. vertexColors: material.vertexColors,
  14178. fog: fog,
  14179. useFog: material.fog,
  14180. fogExp: fog instanceof THREE.FogExp2,
  14181. sizeAttenuation: material.sizeAttenuation,
  14182. skinning: material.skinning,
  14183. maxBones: maxBones,
  14184. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  14185. morphTargets: material.morphTargets,
  14186. morphNormals: material.morphNormals,
  14187. maxMorphTargets: this.maxMorphTargets,
  14188. maxMorphNormals: this.maxMorphNormals,
  14189. maxDirLights: maxLightCount.directional,
  14190. maxPointLights: maxLightCount.point,
  14191. maxSpotLights: maxLightCount.spot,
  14192. maxHemiLights: maxLightCount.hemi,
  14193. maxShadows: maxShadows,
  14194. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  14195. shadowMapType: this.shadowMapType,
  14196. shadowMapDebug: this.shadowMapDebug,
  14197. shadowMapCascade: this.shadowMapCascade,
  14198. alphaTest: material.alphaTest,
  14199. metal: material.metal,
  14200. perPixel: material.perPixel,
  14201. wrapAround: material.wrapAround,
  14202. doubleSided: material.side === THREE.DoubleSide,
  14203. flipSided: material.side === THREE.BackSide
  14204. };
  14205. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters, material.index0AttributeName );
  14206. var attributes = material.program.attributes;
  14207. if ( material.morphTargets ) {
  14208. material.numSupportedMorphTargets = 0;
  14209. var id, base = "morphTarget";
  14210. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  14211. id = base + i;
  14212. if ( attributes[ id ] >= 0 ) {
  14213. material.numSupportedMorphTargets ++;
  14214. }
  14215. }
  14216. }
  14217. if ( material.morphNormals ) {
  14218. material.numSupportedMorphNormals = 0;
  14219. var id, base = "morphNormal";
  14220. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  14221. id = base + i;
  14222. if ( attributes[ id ] >= 0 ) {
  14223. material.numSupportedMorphNormals ++;
  14224. }
  14225. }
  14226. }
  14227. material.uniformsList = [];
  14228. for ( u in material.uniforms ) {
  14229. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  14230. }
  14231. };
  14232. function setMaterialShaders( material, shaders ) {
  14233. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  14234. material.vertexShader = shaders.vertexShader;
  14235. material.fragmentShader = shaders.fragmentShader;
  14236. };
  14237. function setProgram( camera, lights, fog, material, object ) {
  14238. _usedTextureUnits = 0;
  14239. if ( material.needsUpdate ) {
  14240. if ( material.program ) deallocateMaterial( material );
  14241. _this.initMaterial( material, lights, fog, object );
  14242. material.needsUpdate = false;
  14243. }
  14244. if ( material.morphTargets ) {
  14245. if ( ! object.__webglMorphTargetInfluences ) {
  14246. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  14247. }
  14248. }
  14249. var refreshMaterial = false;
  14250. var program = material.program,
  14251. p_uniforms = program.uniforms,
  14252. m_uniforms = material.uniforms;
  14253. if ( program !== _currentProgram ) {
  14254. _gl.useProgram( program );
  14255. _currentProgram = program;
  14256. refreshMaterial = true;
  14257. }
  14258. if ( material.id !== _currentMaterialId ) {
  14259. _currentMaterialId = material.id;
  14260. refreshMaterial = true;
  14261. }
  14262. if ( refreshMaterial || camera !== _currentCamera ) {
  14263. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  14264. if ( camera !== _currentCamera ) _currentCamera = camera;
  14265. }
  14266. // skinning uniforms must be set even if material didn't change
  14267. // auto-setting of texture unit for bone texture must go before other textures
  14268. // not sure why, but otherwise weird things happen
  14269. if ( material.skinning ) {
  14270. if ( _supportsBoneTextures && object.useVertexTexture ) {
  14271. if ( p_uniforms.boneTexture !== null ) {
  14272. var textureUnit = getTextureUnit();
  14273. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  14274. _this.setTexture( object.boneTexture, textureUnit );
  14275. }
  14276. if ( p_uniforms.boneTextureWidth !== null ) {
  14277. _gl.uniform1i( p_uniforms.boneTextureWidth, object.boneTextureWidth );
  14278. }
  14279. if ( p_uniforms.boneTextureHeight !== null ) {
  14280. _gl.uniform1i( p_uniforms.boneTextureHeight, object.boneTextureHeight );
  14281. }
  14282. } else {
  14283. if ( p_uniforms.boneGlobalMatrices !== null ) {
  14284. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  14285. }
  14286. }
  14287. }
  14288. if ( refreshMaterial ) {
  14289. // refresh uniforms common to several materials
  14290. if ( fog && material.fog ) {
  14291. refreshUniformsFog( m_uniforms, fog );
  14292. }
  14293. if ( material instanceof THREE.MeshPhongMaterial ||
  14294. material instanceof THREE.MeshLambertMaterial ||
  14295. material.lights ) {
  14296. if ( _lightsNeedUpdate ) {
  14297. setupLights( program, lights );
  14298. _lightsNeedUpdate = false;
  14299. }
  14300. refreshUniformsLights( m_uniforms, _lights );
  14301. }
  14302. if ( material instanceof THREE.MeshBasicMaterial ||
  14303. material instanceof THREE.MeshLambertMaterial ||
  14304. material instanceof THREE.MeshPhongMaterial ) {
  14305. refreshUniformsCommon( m_uniforms, material );
  14306. }
  14307. // refresh single material specific uniforms
  14308. if ( material instanceof THREE.LineBasicMaterial ) {
  14309. refreshUniformsLine( m_uniforms, material );
  14310. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14311. refreshUniformsLine( m_uniforms, material );
  14312. refreshUniformsDash( m_uniforms, material );
  14313. } else if ( material instanceof THREE.ParticleSystemMaterial ) {
  14314. refreshUniformsParticle( m_uniforms, material );
  14315. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14316. refreshUniformsPhong( m_uniforms, material );
  14317. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14318. refreshUniformsLambert( m_uniforms, material );
  14319. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  14320. m_uniforms.mNear.value = camera.near;
  14321. m_uniforms.mFar.value = camera.far;
  14322. m_uniforms.opacity.value = material.opacity;
  14323. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14324. m_uniforms.opacity.value = material.opacity;
  14325. }
  14326. if ( object.receiveShadow && ! material._shadowPass ) {
  14327. refreshUniformsShadow( m_uniforms, lights );
  14328. }
  14329. // load common uniforms
  14330. loadUniformsGeneric( program, material.uniformsList );
  14331. // load material specific uniforms
  14332. // (shader material also gets them for the sake of genericity)
  14333. if ( material instanceof THREE.ShaderMaterial ||
  14334. material instanceof THREE.MeshPhongMaterial ||
  14335. material.envMap ) {
  14336. if ( p_uniforms.cameraPosition !== null ) {
  14337. _vector3.setFromMatrixPosition( camera.matrixWorld );
  14338. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  14339. }
  14340. }
  14341. if ( material instanceof THREE.MeshPhongMaterial ||
  14342. material instanceof THREE.MeshLambertMaterial ||
  14343. material instanceof THREE.ShaderMaterial ||
  14344. material.skinning ) {
  14345. if ( p_uniforms.viewMatrix !== null ) {
  14346. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  14347. }
  14348. }
  14349. }
  14350. loadUniformsMatrices( p_uniforms, object );
  14351. if ( p_uniforms.modelMatrix !== null ) {
  14352. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  14353. }
  14354. return program;
  14355. };
  14356. // Uniforms (refresh uniforms objects)
  14357. function refreshUniformsCommon ( uniforms, material ) {
  14358. uniforms.opacity.value = material.opacity;
  14359. if ( _this.gammaInput ) {
  14360. uniforms.diffuse.value.copyGammaToLinear( material.color );
  14361. } else {
  14362. uniforms.diffuse.value = material.color;
  14363. }
  14364. uniforms.map.value = material.map;
  14365. uniforms.lightMap.value = material.lightMap;
  14366. uniforms.specularMap.value = material.specularMap;
  14367. if ( material.bumpMap ) {
  14368. uniforms.bumpMap.value = material.bumpMap;
  14369. uniforms.bumpScale.value = material.bumpScale;
  14370. }
  14371. if ( material.normalMap ) {
  14372. uniforms.normalMap.value = material.normalMap;
  14373. uniforms.normalScale.value.copy( material.normalScale );
  14374. }
  14375. // uv repeat and offset setting priorities
  14376. // 1. color map
  14377. // 2. specular map
  14378. // 3. normal map
  14379. // 4. bump map
  14380. var uvScaleMap;
  14381. if ( material.map ) {
  14382. uvScaleMap = material.map;
  14383. } else if ( material.specularMap ) {
  14384. uvScaleMap = material.specularMap;
  14385. } else if ( material.normalMap ) {
  14386. uvScaleMap = material.normalMap;
  14387. } else if ( material.bumpMap ) {
  14388. uvScaleMap = material.bumpMap;
  14389. }
  14390. if ( uvScaleMap !== undefined ) {
  14391. var offset = uvScaleMap.offset;
  14392. var repeat = uvScaleMap.repeat;
  14393. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  14394. }
  14395. uniforms.envMap.value = material.envMap;
  14396. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  14397. if ( _this.gammaInput ) {
  14398. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  14399. uniforms.reflectivity.value = material.reflectivity;
  14400. } else {
  14401. uniforms.reflectivity.value = material.reflectivity;
  14402. }
  14403. uniforms.refractionRatio.value = material.refractionRatio;
  14404. uniforms.combine.value = material.combine;
  14405. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  14406. };
  14407. function refreshUniformsLine ( uniforms, material ) {
  14408. uniforms.diffuse.value = material.color;
  14409. uniforms.opacity.value = material.opacity;
  14410. };
  14411. function refreshUniformsDash ( uniforms, material ) {
  14412. uniforms.dashSize.value = material.dashSize;
  14413. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14414. uniforms.scale.value = material.scale;
  14415. };
  14416. function refreshUniformsParticle ( uniforms, material ) {
  14417. uniforms.psColor.value = material.color;
  14418. uniforms.opacity.value = material.opacity;
  14419. uniforms.size.value = material.size;
  14420. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  14421. uniforms.map.value = material.map;
  14422. };
  14423. function refreshUniformsFog ( uniforms, fog ) {
  14424. uniforms.fogColor.value = fog.color;
  14425. if ( fog instanceof THREE.Fog ) {
  14426. uniforms.fogNear.value = fog.near;
  14427. uniforms.fogFar.value = fog.far;
  14428. } else if ( fog instanceof THREE.FogExp2 ) {
  14429. uniforms.fogDensity.value = fog.density;
  14430. }
  14431. };
  14432. function refreshUniformsPhong ( uniforms, material ) {
  14433. uniforms.shininess.value = material.shininess;
  14434. if ( _this.gammaInput ) {
  14435. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14436. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14437. uniforms.specular.value.copyGammaToLinear( material.specular );
  14438. } else {
  14439. uniforms.ambient.value = material.ambient;
  14440. uniforms.emissive.value = material.emissive;
  14441. uniforms.specular.value = material.specular;
  14442. }
  14443. if ( material.wrapAround ) {
  14444. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14445. }
  14446. };
  14447. function refreshUniformsLambert ( uniforms, material ) {
  14448. if ( _this.gammaInput ) {
  14449. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14450. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14451. } else {
  14452. uniforms.ambient.value = material.ambient;
  14453. uniforms.emissive.value = material.emissive;
  14454. }
  14455. if ( material.wrapAround ) {
  14456. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14457. }
  14458. };
  14459. function refreshUniformsLights ( uniforms, lights ) {
  14460. uniforms.ambientLightColor.value = lights.ambient;
  14461. uniforms.directionalLightColor.value = lights.directional.colors;
  14462. uniforms.directionalLightDirection.value = lights.directional.positions;
  14463. uniforms.pointLightColor.value = lights.point.colors;
  14464. uniforms.pointLightPosition.value = lights.point.positions;
  14465. uniforms.pointLightDistance.value = lights.point.distances;
  14466. uniforms.spotLightColor.value = lights.spot.colors;
  14467. uniforms.spotLightPosition.value = lights.spot.positions;
  14468. uniforms.spotLightDistance.value = lights.spot.distances;
  14469. uniforms.spotLightDirection.value = lights.spot.directions;
  14470. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  14471. uniforms.spotLightExponent.value = lights.spot.exponents;
  14472. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  14473. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  14474. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  14475. };
  14476. function refreshUniformsShadow ( uniforms, lights ) {
  14477. if ( uniforms.shadowMatrix ) {
  14478. var j = 0;
  14479. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  14480. var light = lights[ i ];
  14481. if ( ! light.castShadow ) continue;
  14482. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  14483. uniforms.shadowMap.value[ j ] = light.shadowMap;
  14484. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  14485. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  14486. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  14487. uniforms.shadowBias.value[ j ] = light.shadowBias;
  14488. j ++;
  14489. }
  14490. }
  14491. }
  14492. };
  14493. // Uniforms (load to GPU)
  14494. function loadUniformsMatrices ( uniforms, object ) {
  14495. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  14496. if ( uniforms.normalMatrix ) {
  14497. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  14498. }
  14499. };
  14500. function getTextureUnit() {
  14501. var textureUnit = _usedTextureUnits;
  14502. if ( textureUnit >= _maxTextures ) {
  14503. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  14504. }
  14505. _usedTextureUnits += 1;
  14506. return textureUnit;
  14507. };
  14508. function loadUniformsGeneric ( program, uniforms ) {
  14509. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  14510. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  14511. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  14512. if ( !location ) continue;
  14513. uniform = uniforms[ j ][ 0 ];
  14514. type = uniform.type;
  14515. value = uniform.value;
  14516. if ( type === "i" ) { // single integer
  14517. _gl.uniform1i( location, value );
  14518. } else if ( type === "f" ) { // single float
  14519. _gl.uniform1f( location, value );
  14520. } else if ( type === "v2" ) { // single THREE.Vector2
  14521. _gl.uniform2f( location, value.x, value.y );
  14522. } else if ( type === "v3" ) { // single THREE.Vector3
  14523. _gl.uniform3f( location, value.x, value.y, value.z );
  14524. } else if ( type === "v4" ) { // single THREE.Vector4
  14525. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  14526. } else if ( type === "c" ) { // single THREE.Color
  14527. _gl.uniform3f( location, value.r, value.g, value.b );
  14528. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  14529. _gl.uniform1iv( location, value );
  14530. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  14531. _gl.uniform3iv( location, value );
  14532. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  14533. _gl.uniform1fv( location, value );
  14534. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  14535. _gl.uniform3fv( location, value );
  14536. } else if ( type === "v2v" ) { // array of THREE.Vector2
  14537. if ( uniform._array === undefined ) {
  14538. uniform._array = new Float32Array( 2 * value.length );
  14539. }
  14540. for ( i = 0, il = value.length; i < il; i ++ ) {
  14541. offset = i * 2;
  14542. uniform._array[ offset ] = value[ i ].x;
  14543. uniform._array[ offset + 1 ] = value[ i ].y;
  14544. }
  14545. _gl.uniform2fv( location, uniform._array );
  14546. } else if ( type === "v3v" ) { // array of THREE.Vector3
  14547. if ( uniform._array === undefined ) {
  14548. uniform._array = new Float32Array( 3 * value.length );
  14549. }
  14550. for ( i = 0, il = value.length; i < il; i ++ ) {
  14551. offset = i * 3;
  14552. uniform._array[ offset ] = value[ i ].x;
  14553. uniform._array[ offset + 1 ] = value[ i ].y;
  14554. uniform._array[ offset + 2 ] = value[ i ].z;
  14555. }
  14556. _gl.uniform3fv( location, uniform._array );
  14557. } else if ( type === "v4v" ) { // array of THREE.Vector4
  14558. if ( uniform._array === undefined ) {
  14559. uniform._array = new Float32Array( 4 * value.length );
  14560. }
  14561. for ( i = 0, il = value.length; i < il; i ++ ) {
  14562. offset = i * 4;
  14563. uniform._array[ offset ] = value[ i ].x;
  14564. uniform._array[ offset + 1 ] = value[ i ].y;
  14565. uniform._array[ offset + 2 ] = value[ i ].z;
  14566. uniform._array[ offset + 3 ] = value[ i ].w;
  14567. }
  14568. _gl.uniform4fv( location, uniform._array );
  14569. } else if ( type === "m4") { // single THREE.Matrix4
  14570. if ( uniform._array === undefined ) {
  14571. uniform._array = new Float32Array( 16 );
  14572. }
  14573. value.flattenToArray( uniform._array );
  14574. _gl.uniformMatrix4fv( location, false, uniform._array );
  14575. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  14576. if ( uniform._array === undefined ) {
  14577. uniform._array = new Float32Array( 16 * value.length );
  14578. }
  14579. for ( i = 0, il = value.length; i < il; i ++ ) {
  14580. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  14581. }
  14582. _gl.uniformMatrix4fv( location, false, uniform._array );
  14583. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  14584. texture = value;
  14585. textureUnit = getTextureUnit();
  14586. _gl.uniform1i( location, textureUnit );
  14587. if ( !texture ) continue;
  14588. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  14589. setCubeTexture( texture, textureUnit );
  14590. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  14591. setCubeTextureDynamic( texture, textureUnit );
  14592. } else {
  14593. _this.setTexture( texture, textureUnit );
  14594. }
  14595. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  14596. if ( uniform._array === undefined ) {
  14597. uniform._array = [];
  14598. }
  14599. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14600. uniform._array[ i ] = getTextureUnit();
  14601. }
  14602. _gl.uniform1iv( location, uniform._array );
  14603. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14604. texture = uniform.value[ i ];
  14605. textureUnit = uniform._array[ i ];
  14606. if ( !texture ) continue;
  14607. _this.setTexture( texture, textureUnit );
  14608. }
  14609. } else {
  14610. console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  14611. }
  14612. }
  14613. };
  14614. function setupMatrices ( object, camera ) {
  14615. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  14616. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  14617. };
  14618. //
  14619. function setColorGamma( array, offset, color, intensitySq ) {
  14620. array[ offset ] = color.r * color.r * intensitySq;
  14621. array[ offset + 1 ] = color.g * color.g * intensitySq;
  14622. array[ offset + 2 ] = color.b * color.b * intensitySq;
  14623. };
  14624. function setColorLinear( array, offset, color, intensity ) {
  14625. array[ offset ] = color.r * intensity;
  14626. array[ offset + 1 ] = color.g * intensity;
  14627. array[ offset + 2 ] = color.b * intensity;
  14628. };
  14629. function setupLights ( program, lights ) {
  14630. var l, ll, light, n,
  14631. r = 0, g = 0, b = 0,
  14632. color, skyColor, groundColor,
  14633. intensity, intensitySq,
  14634. position,
  14635. distance,
  14636. zlights = _lights,
  14637. dirColors = zlights.directional.colors,
  14638. dirPositions = zlights.directional.positions,
  14639. pointColors = zlights.point.colors,
  14640. pointPositions = zlights.point.positions,
  14641. pointDistances = zlights.point.distances,
  14642. spotColors = zlights.spot.colors,
  14643. spotPositions = zlights.spot.positions,
  14644. spotDistances = zlights.spot.distances,
  14645. spotDirections = zlights.spot.directions,
  14646. spotAnglesCos = zlights.spot.anglesCos,
  14647. spotExponents = zlights.spot.exponents,
  14648. hemiSkyColors = zlights.hemi.skyColors,
  14649. hemiGroundColors = zlights.hemi.groundColors,
  14650. hemiPositions = zlights.hemi.positions,
  14651. dirLength = 0,
  14652. pointLength = 0,
  14653. spotLength = 0,
  14654. hemiLength = 0,
  14655. dirCount = 0,
  14656. pointCount = 0,
  14657. spotCount = 0,
  14658. hemiCount = 0,
  14659. dirOffset = 0,
  14660. pointOffset = 0,
  14661. spotOffset = 0,
  14662. hemiOffset = 0;
  14663. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14664. light = lights[ l ];
  14665. if ( light.onlyShadow ) continue;
  14666. color = light.color;
  14667. intensity = light.intensity;
  14668. distance = light.distance;
  14669. if ( light instanceof THREE.AmbientLight ) {
  14670. if ( ! light.visible ) continue;
  14671. if ( _this.gammaInput ) {
  14672. r += color.r * color.r;
  14673. g += color.g * color.g;
  14674. b += color.b * color.b;
  14675. } else {
  14676. r += color.r;
  14677. g += color.g;
  14678. b += color.b;
  14679. }
  14680. } else if ( light instanceof THREE.DirectionalLight ) {
  14681. dirCount += 1;
  14682. if ( ! light.visible ) continue;
  14683. _direction.setFromMatrixPosition( light.matrixWorld );
  14684. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  14685. _direction.sub( _vector3 );
  14686. _direction.normalize();
  14687. // skip lights with undefined direction
  14688. // these create troubles in OpenGL (making pixel black)
  14689. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14690. dirOffset = dirLength * 3;
  14691. dirPositions[ dirOffset ] = _direction.x;
  14692. dirPositions[ dirOffset + 1 ] = _direction.y;
  14693. dirPositions[ dirOffset + 2 ] = _direction.z;
  14694. if ( _this.gammaInput ) {
  14695. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  14696. } else {
  14697. setColorLinear( dirColors, dirOffset, color, intensity );
  14698. }
  14699. dirLength += 1;
  14700. } else if ( light instanceof THREE.PointLight ) {
  14701. pointCount += 1;
  14702. if ( ! light.visible ) continue;
  14703. pointOffset = pointLength * 3;
  14704. if ( _this.gammaInput ) {
  14705. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  14706. } else {
  14707. setColorLinear( pointColors, pointOffset, color, intensity );
  14708. }
  14709. _vector3.setFromMatrixPosition( light.matrixWorld );
  14710. pointPositions[ pointOffset ] = _vector3.x;
  14711. pointPositions[ pointOffset + 1 ] = _vector3.y;
  14712. pointPositions[ pointOffset + 2 ] = _vector3.z;
  14713. pointDistances[ pointLength ] = distance;
  14714. pointLength += 1;
  14715. } else if ( light instanceof THREE.SpotLight ) {
  14716. spotCount += 1;
  14717. if ( ! light.visible ) continue;
  14718. spotOffset = spotLength * 3;
  14719. if ( _this.gammaInput ) {
  14720. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  14721. } else {
  14722. setColorLinear( spotColors, spotOffset, color, intensity );
  14723. }
  14724. _vector3.setFromMatrixPosition( light.matrixWorld );
  14725. spotPositions[ spotOffset ] = _vector3.x;
  14726. spotPositions[ spotOffset + 1 ] = _vector3.y;
  14727. spotPositions[ spotOffset + 2 ] = _vector3.z;
  14728. spotDistances[ spotLength ] = distance;
  14729. _direction.copy( _vector3 );
  14730. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  14731. _direction.sub( _vector3 );
  14732. _direction.normalize();
  14733. spotDirections[ spotOffset ] = _direction.x;
  14734. spotDirections[ spotOffset + 1 ] = _direction.y;
  14735. spotDirections[ spotOffset + 2 ] = _direction.z;
  14736. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  14737. spotExponents[ spotLength ] = light.exponent;
  14738. spotLength += 1;
  14739. } else if ( light instanceof THREE.HemisphereLight ) {
  14740. hemiCount += 1;
  14741. if ( ! light.visible ) continue;
  14742. _direction.setFromMatrixPosition( light.matrixWorld );
  14743. _direction.normalize();
  14744. // skip lights with undefined direction
  14745. // these create troubles in OpenGL (making pixel black)
  14746. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14747. hemiOffset = hemiLength * 3;
  14748. hemiPositions[ hemiOffset ] = _direction.x;
  14749. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  14750. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  14751. skyColor = light.color;
  14752. groundColor = light.groundColor;
  14753. if ( _this.gammaInput ) {
  14754. intensitySq = intensity * intensity;
  14755. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  14756. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  14757. } else {
  14758. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  14759. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  14760. }
  14761. hemiLength += 1;
  14762. }
  14763. }
  14764. // null eventual remains from removed lights
  14765. // (this is to avoid if in shader)
  14766. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  14767. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  14768. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  14769. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  14770. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  14771. zlights.directional.length = dirLength;
  14772. zlights.point.length = pointLength;
  14773. zlights.spot.length = spotLength;
  14774. zlights.hemi.length = hemiLength;
  14775. zlights.ambient[ 0 ] = r;
  14776. zlights.ambient[ 1 ] = g;
  14777. zlights.ambient[ 2 ] = b;
  14778. };
  14779. // GL state setting
  14780. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  14781. if ( cullFace === THREE.CullFaceNone ) {
  14782. _gl.disable( _gl.CULL_FACE );
  14783. } else {
  14784. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  14785. _gl.frontFace( _gl.CW );
  14786. } else {
  14787. _gl.frontFace( _gl.CCW );
  14788. }
  14789. if ( cullFace === THREE.CullFaceBack ) {
  14790. _gl.cullFace( _gl.BACK );
  14791. } else if ( cullFace === THREE.CullFaceFront ) {
  14792. _gl.cullFace( _gl.FRONT );
  14793. } else {
  14794. _gl.cullFace( _gl.FRONT_AND_BACK );
  14795. }
  14796. _gl.enable( _gl.CULL_FACE );
  14797. }
  14798. };
  14799. this.setMaterialFaces = function ( material ) {
  14800. var doubleSided = material.side === THREE.DoubleSide;
  14801. var flipSided = material.side === THREE.BackSide;
  14802. if ( _oldDoubleSided !== doubleSided ) {
  14803. if ( doubleSided ) {
  14804. _gl.disable( _gl.CULL_FACE );
  14805. } else {
  14806. _gl.enable( _gl.CULL_FACE );
  14807. }
  14808. _oldDoubleSided = doubleSided;
  14809. }
  14810. if ( _oldFlipSided !== flipSided ) {
  14811. if ( flipSided ) {
  14812. _gl.frontFace( _gl.CW );
  14813. } else {
  14814. _gl.frontFace( _gl.CCW );
  14815. }
  14816. _oldFlipSided = flipSided;
  14817. }
  14818. };
  14819. this.setDepthTest = function ( depthTest ) {
  14820. if ( _oldDepthTest !== depthTest ) {
  14821. if ( depthTest ) {
  14822. _gl.enable( _gl.DEPTH_TEST );
  14823. } else {
  14824. _gl.disable( _gl.DEPTH_TEST );
  14825. }
  14826. _oldDepthTest = depthTest;
  14827. }
  14828. };
  14829. this.setDepthWrite = function ( depthWrite ) {
  14830. if ( _oldDepthWrite !== depthWrite ) {
  14831. _gl.depthMask( depthWrite );
  14832. _oldDepthWrite = depthWrite;
  14833. }
  14834. };
  14835. function setLineWidth ( width ) {
  14836. if ( width !== _oldLineWidth ) {
  14837. _gl.lineWidth( width );
  14838. _oldLineWidth = width;
  14839. }
  14840. };
  14841. function setPolygonOffset ( polygonoffset, factor, units ) {
  14842. if ( _oldPolygonOffset !== polygonoffset ) {
  14843. if ( polygonoffset ) {
  14844. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  14845. } else {
  14846. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  14847. }
  14848. _oldPolygonOffset = polygonoffset;
  14849. }
  14850. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  14851. _gl.polygonOffset( factor, units );
  14852. _oldPolygonOffsetFactor = factor;
  14853. _oldPolygonOffsetUnits = units;
  14854. }
  14855. };
  14856. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  14857. if ( blending !== _oldBlending ) {
  14858. if ( blending === THREE.NoBlending ) {
  14859. _gl.disable( _gl.BLEND );
  14860. } else if ( blending === THREE.AdditiveBlending ) {
  14861. _gl.enable( _gl.BLEND );
  14862. _gl.blendEquation( _gl.FUNC_ADD );
  14863. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  14864. } else if ( blending === THREE.SubtractiveBlending ) {
  14865. // TODO: Find blendFuncSeparate() combination
  14866. _gl.enable( _gl.BLEND );
  14867. _gl.blendEquation( _gl.FUNC_ADD );
  14868. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  14869. } else if ( blending === THREE.MultiplyBlending ) {
  14870. // TODO: Find blendFuncSeparate() combination
  14871. _gl.enable( _gl.BLEND );
  14872. _gl.blendEquation( _gl.FUNC_ADD );
  14873. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  14874. } else if ( blending === THREE.CustomBlending ) {
  14875. _gl.enable( _gl.BLEND );
  14876. } else {
  14877. _gl.enable( _gl.BLEND );
  14878. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  14879. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  14880. }
  14881. _oldBlending = blending;
  14882. }
  14883. if ( blending === THREE.CustomBlending ) {
  14884. if ( blendEquation !== _oldBlendEquation ) {
  14885. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  14886. _oldBlendEquation = blendEquation;
  14887. }
  14888. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  14889. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  14890. _oldBlendSrc = blendSrc;
  14891. _oldBlendDst = blendDst;
  14892. }
  14893. } else {
  14894. _oldBlendEquation = null;
  14895. _oldBlendSrc = null;
  14896. _oldBlendDst = null;
  14897. }
  14898. };
  14899. // Defines
  14900. function generateDefines ( defines ) {
  14901. var value, chunk, chunks = [];
  14902. for ( var d in defines ) {
  14903. value = defines[ d ];
  14904. if ( value === false ) continue;
  14905. chunk = "#define " + d + " " + value;
  14906. chunks.push( chunk );
  14907. }
  14908. return chunks.join( "\n" );
  14909. };
  14910. // Shaders
  14911. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters, index0AttributeName ) {
  14912. var p, pl, d, program, code;
  14913. var chunks = [];
  14914. // Generate code
  14915. if ( shaderID ) {
  14916. chunks.push( shaderID );
  14917. } else {
  14918. chunks.push( fragmentShader );
  14919. chunks.push( vertexShader );
  14920. }
  14921. for ( d in defines ) {
  14922. chunks.push( d );
  14923. chunks.push( defines[ d ] );
  14924. }
  14925. for ( p in parameters ) {
  14926. chunks.push( p );
  14927. chunks.push( parameters[ p ] );
  14928. }
  14929. code = chunks.join();
  14930. // Check if code has been already compiled
  14931. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  14932. var programInfo = _programs[ p ];
  14933. if ( programInfo.code === code ) {
  14934. // console.log( "Code already compiled." /*: \n\n" + code*/ );
  14935. programInfo.usedTimes ++;
  14936. return programInfo.program;
  14937. }
  14938. }
  14939. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  14940. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  14941. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  14942. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  14943. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  14944. }
  14945. // console.log( "building new program " );
  14946. //
  14947. var customDefines = generateDefines( defines );
  14948. //
  14949. program = _gl.createProgram();
  14950. var prefix_vertex = [
  14951. "precision " + _precision + " float;",
  14952. "precision " + _precision + " int;",
  14953. customDefines,
  14954. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  14955. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  14956. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  14957. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  14958. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  14959. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  14960. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  14961. "#define MAX_SHADOWS " + parameters.maxShadows,
  14962. "#define MAX_BONES " + parameters.maxBones,
  14963. parameters.map ? "#define USE_MAP" : "",
  14964. parameters.envMap ? "#define USE_ENVMAP" : "",
  14965. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  14966. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  14967. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  14968. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  14969. parameters.vertexColors ? "#define USE_COLOR" : "",
  14970. parameters.skinning ? "#define USE_SKINNING" : "",
  14971. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  14972. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  14973. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  14974. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  14975. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  14976. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  14977. parameters.flipSided ? "#define FLIP_SIDED" : "",
  14978. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  14979. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  14980. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  14981. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  14982. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  14983. "uniform mat4 modelMatrix;",
  14984. "uniform mat4 modelViewMatrix;",
  14985. "uniform mat4 projectionMatrix;",
  14986. "uniform mat4 viewMatrix;",
  14987. "uniform mat3 normalMatrix;",
  14988. "uniform vec3 cameraPosition;",
  14989. "attribute vec3 position;",
  14990. "attribute vec3 normal;",
  14991. "attribute vec2 uv;",
  14992. "attribute vec2 uv2;",
  14993. "#ifdef USE_COLOR",
  14994. "attribute vec3 color;",
  14995. "#endif",
  14996. "#ifdef USE_MORPHTARGETS",
  14997. "attribute vec3 morphTarget0;",
  14998. "attribute vec3 morphTarget1;",
  14999. "attribute vec3 morphTarget2;",
  15000. "attribute vec3 morphTarget3;",
  15001. "#ifdef USE_MORPHNORMALS",
  15002. "attribute vec3 morphNormal0;",
  15003. "attribute vec3 morphNormal1;",
  15004. "attribute vec3 morphNormal2;",
  15005. "attribute vec3 morphNormal3;",
  15006. "#else",
  15007. "attribute vec3 morphTarget4;",
  15008. "attribute vec3 morphTarget5;",
  15009. "attribute vec3 morphTarget6;",
  15010. "attribute vec3 morphTarget7;",
  15011. "#endif",
  15012. "#endif",
  15013. "#ifdef USE_SKINNING",
  15014. "attribute vec4 skinIndex;",
  15015. "attribute vec4 skinWeight;",
  15016. "#endif",
  15017. ""
  15018. ].join("\n");
  15019. var prefix_fragment = [
  15020. "precision " + _precision + " float;",
  15021. "precision " + _precision + " int;",
  15022. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  15023. customDefines,
  15024. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  15025. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  15026. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  15027. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  15028. "#define MAX_SHADOWS " + parameters.maxShadows,
  15029. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  15030. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  15031. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  15032. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  15033. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  15034. parameters.map ? "#define USE_MAP" : "",
  15035. parameters.envMap ? "#define USE_ENVMAP" : "",
  15036. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  15037. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  15038. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  15039. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  15040. parameters.vertexColors ? "#define USE_COLOR" : "",
  15041. parameters.metal ? "#define METAL" : "",
  15042. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  15043. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  15044. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  15045. parameters.flipSided ? "#define FLIP_SIDED" : "",
  15046. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  15047. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  15048. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  15049. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  15050. "uniform mat4 viewMatrix;",
  15051. "uniform vec3 cameraPosition;",
  15052. ""
  15053. ].join("\n");
  15054. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  15055. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  15056. _gl.attachShader( program, glVertexShader );
  15057. _gl.attachShader( program, glFragmentShader );
  15058. //Force a particular attribute to index 0.
  15059. // because potentially expensive emulation is done by browser if attribute 0 is disabled.
  15060. //And, color, for example is often automatically bound to index 0 so disabling it
  15061. if ( index0AttributeName ) {
  15062. _gl.bindAttribLocation( program, 0, index0AttributeName );
  15063. }
  15064. _gl.linkProgram( program );
  15065. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  15066. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  15067. console.error( "Program Info Log: " + _gl.getProgramInfoLog( program ) );
  15068. }
  15069. // clean up
  15070. _gl.deleteShader( glFragmentShader );
  15071. _gl.deleteShader( glVertexShader );
  15072. // console.log( prefix_fragment + fragmentShader );
  15073. // console.log( prefix_vertex + vertexShader );
  15074. program.uniforms = {};
  15075. program.attributes = {};
  15076. var identifiers, u, a, i;
  15077. // cache uniform locations
  15078. identifiers = [
  15079. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  15080. 'morphTargetInfluences'
  15081. ];
  15082. if ( parameters.useVertexTexture ) {
  15083. identifiers.push( 'boneTexture' );
  15084. identifiers.push( 'boneTextureWidth' );
  15085. identifiers.push( 'boneTextureHeight' );
  15086. } else {
  15087. identifiers.push( 'boneGlobalMatrices' );
  15088. }
  15089. for ( u in uniforms ) {
  15090. identifiers.push( u );
  15091. }
  15092. cacheUniformLocations( program, identifiers );
  15093. // cache attributes locations
  15094. identifiers = [
  15095. "position", "normal", "uv", "uv2", "tangent", "color",
  15096. "skinIndex", "skinWeight", "lineDistance"
  15097. ];
  15098. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  15099. identifiers.push( "morphTarget" + i );
  15100. }
  15101. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  15102. identifiers.push( "morphNormal" + i );
  15103. }
  15104. for ( a in attributes ) {
  15105. identifiers.push( a );
  15106. }
  15107. cacheAttributeLocations( program, identifiers );
  15108. program.id = _programs_counter ++;
  15109. _programs.push( { program: program, code: code, usedTimes: 1 } );
  15110. _this.info.memory.programs = _programs.length;
  15111. return program;
  15112. };
  15113. // Shader parameters cache
  15114. function cacheUniformLocations ( program, identifiers ) {
  15115. var i, l, id;
  15116. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  15117. id = identifiers[ i ];
  15118. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  15119. }
  15120. };
  15121. function cacheAttributeLocations ( program, identifiers ) {
  15122. var i, l, id;
  15123. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  15124. id = identifiers[ i ];
  15125. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  15126. }
  15127. };
  15128. function addLineNumbers ( string ) {
  15129. var chunks = string.split( "\n" );
  15130. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  15131. // Chrome reports shader errors on lines
  15132. // starting counting from 1
  15133. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  15134. }
  15135. return chunks.join( "\n" );
  15136. };
  15137. function getShader ( type, string ) {
  15138. var shader;
  15139. if ( type === "fragment" ) {
  15140. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  15141. } else if ( type === "vertex" ) {
  15142. shader = _gl.createShader( _gl.VERTEX_SHADER );
  15143. }
  15144. _gl.shaderSource( shader, string );
  15145. _gl.compileShader( shader );
  15146. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  15147. console.error( _gl.getShaderInfoLog( shader ) );
  15148. console.error( addLineNumbers( string ) );
  15149. return null;
  15150. }
  15151. return shader;
  15152. };
  15153. // Textures
  15154. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  15155. if ( isImagePowerOfTwo ) {
  15156. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  15157. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  15158. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  15159. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  15160. } else {
  15161. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  15162. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  15163. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  15164. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  15165. }
  15166. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  15167. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  15168. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  15169. texture.__oldAnisotropy = texture.anisotropy;
  15170. }
  15171. }
  15172. };
  15173. this.setTexture = function ( texture, slot ) {
  15174. if ( texture.needsUpdate ) {
  15175. if ( ! texture.__webglInit ) {
  15176. texture.__webglInit = true;
  15177. texture.addEventListener( 'dispose', onTextureDispose );
  15178. texture.__webglTexture = _gl.createTexture();
  15179. _this.info.memory.textures ++;
  15180. }
  15181. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15182. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15183. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15184. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  15185. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  15186. var image = texture.image,
  15187. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  15188. glFormat = paramThreeToGL( texture.format ),
  15189. glType = paramThreeToGL( texture.type );
  15190. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  15191. var mipmap, mipmaps = texture.mipmaps;
  15192. if ( texture instanceof THREE.DataTexture ) {
  15193. // use manually created mipmaps if available
  15194. // if there are no manual mipmaps
  15195. // set 0 level mipmap and then use GL to generate other mipmap levels
  15196. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15197. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15198. mipmap = mipmaps[ i ];
  15199. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15200. }
  15201. texture.generateMipmaps = false;
  15202. } else {
  15203. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  15204. }
  15205. } else if ( texture instanceof THREE.CompressedTexture ) {
  15206. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15207. mipmap = mipmaps[ i ];
  15208. if ( texture.format!==THREE.RGBAFormat ) {
  15209. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15210. } else {
  15211. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15212. }
  15213. }
  15214. } else { // regular Texture (image, video, canvas)
  15215. // use manually created mipmaps if available
  15216. // if there are no manual mipmaps
  15217. // set 0 level mipmap and then use GL to generate other mipmap levels
  15218. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15219. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15220. mipmap = mipmaps[ i ];
  15221. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  15222. }
  15223. texture.generateMipmaps = false;
  15224. } else {
  15225. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  15226. }
  15227. }
  15228. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15229. texture.needsUpdate = false;
  15230. if ( texture.onUpdate ) texture.onUpdate();
  15231. } else {
  15232. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15233. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15234. }
  15235. };
  15236. function clampToMaxSize ( image, maxSize ) {
  15237. if ( image.width <= maxSize && image.height <= maxSize ) {
  15238. return image;
  15239. }
  15240. // Warning: Scaling through the canvas will only work with images that use
  15241. // premultiplied alpha.
  15242. var maxDimension = Math.max( image.width, image.height );
  15243. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  15244. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  15245. var canvas = document.createElement( 'canvas' );
  15246. canvas.width = newWidth;
  15247. canvas.height = newHeight;
  15248. var ctx = canvas.getContext( "2d" );
  15249. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  15250. return canvas;
  15251. }
  15252. function setCubeTexture ( texture, slot ) {
  15253. if ( texture.image.length === 6 ) {
  15254. if ( texture.needsUpdate ) {
  15255. if ( ! texture.image.__webglTextureCube ) {
  15256. texture.addEventListener( 'dispose', onTextureDispose );
  15257. texture.image.__webglTextureCube = _gl.createTexture();
  15258. _this.info.memory.textures ++;
  15259. }
  15260. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15261. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15262. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15263. var isCompressed = texture instanceof THREE.CompressedTexture;
  15264. var cubeImage = [];
  15265. for ( var i = 0; i < 6; i ++ ) {
  15266. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  15267. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  15268. } else {
  15269. cubeImage[ i ] = texture.image[ i ];
  15270. }
  15271. }
  15272. var image = cubeImage[ 0 ],
  15273. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  15274. glFormat = paramThreeToGL( texture.format ),
  15275. glType = paramThreeToGL( texture.type );
  15276. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  15277. for ( var i = 0; i < 6; i ++ ) {
  15278. if( !isCompressed ) {
  15279. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  15280. } else {
  15281. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  15282. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  15283. mipmap = mipmaps[ j ];
  15284. if ( texture.format!==THREE.RGBAFormat ) {
  15285. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15286. } else {
  15287. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15288. }
  15289. }
  15290. }
  15291. }
  15292. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  15293. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15294. }
  15295. texture.needsUpdate = false;
  15296. if ( texture.onUpdate ) texture.onUpdate();
  15297. } else {
  15298. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15299. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15300. }
  15301. }
  15302. };
  15303. function setCubeTextureDynamic ( texture, slot ) {
  15304. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15305. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  15306. };
  15307. // Render targets
  15308. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  15309. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15310. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  15311. };
  15312. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  15313. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15314. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15315. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  15316. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15317. /* For some reason this is not working. Defaulting to RGBA4.
  15318. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15319. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  15320. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15321. */
  15322. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15323. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15324. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15325. } else {
  15326. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  15327. }
  15328. };
  15329. this.setRenderTarget = function ( renderTarget ) {
  15330. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  15331. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  15332. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  15333. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  15334. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15335. renderTarget.__webglTexture = _gl.createTexture();
  15336. _this.info.memory.textures ++;
  15337. // Setup texture, create render and frame buffers
  15338. var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height ),
  15339. glFormat = paramThreeToGL( renderTarget.format ),
  15340. glType = paramThreeToGL( renderTarget.type );
  15341. if ( isCube ) {
  15342. renderTarget.__webglFramebuffer = [];
  15343. renderTarget.__webglRenderbuffer = [];
  15344. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15345. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  15346. for ( var i = 0; i < 6; i ++ ) {
  15347. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15348. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  15349. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15350. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  15351. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  15352. }
  15353. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15354. } else {
  15355. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  15356. if ( renderTarget.shareDepthFrom ) {
  15357. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  15358. } else {
  15359. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  15360. }
  15361. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15362. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  15363. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15364. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  15365. if ( renderTarget.shareDepthFrom ) {
  15366. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15367. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15368. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15369. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15370. }
  15371. } else {
  15372. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  15373. }
  15374. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15375. }
  15376. // Release everything
  15377. if ( isCube ) {
  15378. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15379. } else {
  15380. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15381. }
  15382. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15383. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15384. }
  15385. var framebuffer, width, height, vx, vy;
  15386. if ( renderTarget ) {
  15387. if ( isCube ) {
  15388. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  15389. } else {
  15390. framebuffer = renderTarget.__webglFramebuffer;
  15391. }
  15392. width = renderTarget.width;
  15393. height = renderTarget.height;
  15394. vx = 0;
  15395. vy = 0;
  15396. } else {
  15397. framebuffer = null;
  15398. width = _viewportWidth;
  15399. height = _viewportHeight;
  15400. vx = _viewportX;
  15401. vy = _viewportY;
  15402. }
  15403. if ( framebuffer !== _currentFramebuffer ) {
  15404. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15405. _gl.viewport( vx, vy, width, height );
  15406. _currentFramebuffer = framebuffer;
  15407. }
  15408. _currentWidth = width;
  15409. _currentHeight = height;
  15410. };
  15411. function updateRenderTargetMipmap ( renderTarget ) {
  15412. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  15413. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15414. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15415. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15416. } else {
  15417. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15418. _gl.generateMipmap( _gl.TEXTURE_2D );
  15419. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15420. }
  15421. };
  15422. // Fallback filters for non-power-of-2 textures
  15423. function filterFallback ( f ) {
  15424. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  15425. return _gl.NEAREST;
  15426. }
  15427. return _gl.LINEAR;
  15428. };
  15429. // Map three.js constants to WebGL constants
  15430. function paramThreeToGL ( p ) {
  15431. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  15432. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  15433. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  15434. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  15435. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  15436. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  15437. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  15438. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  15439. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  15440. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  15441. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  15442. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  15443. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  15444. if ( p === THREE.ByteType ) return _gl.BYTE;
  15445. if ( p === THREE.ShortType ) return _gl.SHORT;
  15446. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  15447. if ( p === THREE.IntType ) return _gl.INT;
  15448. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  15449. if ( p === THREE.FloatType ) return _gl.FLOAT;
  15450. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  15451. if ( p === THREE.RGBFormat ) return _gl.RGB;
  15452. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  15453. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  15454. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  15455. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  15456. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  15457. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  15458. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  15459. if ( p === THREE.OneFactor ) return _gl.ONE;
  15460. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  15461. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  15462. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  15463. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  15464. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  15465. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  15466. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  15467. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  15468. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  15469. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  15470. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15471. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15472. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15473. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15474. }
  15475. return 0;
  15476. };
  15477. // Allocations
  15478. function allocateBones ( object ) {
  15479. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  15480. return 1024;
  15481. } else {
  15482. // default for when object is not specified
  15483. // ( for example when prebuilding shader
  15484. // to be used with multiple objects )
  15485. //
  15486. // - leave some extra space for other uniforms
  15487. // - limit here is ANGLE's 254 max uniform vectors
  15488. // (up to 54 should be safe)
  15489. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  15490. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  15491. var maxBones = nVertexMatrices;
  15492. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  15493. maxBones = Math.min( object.bones.length, maxBones );
  15494. if ( maxBones < object.bones.length ) {
  15495. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  15496. }
  15497. }
  15498. return maxBones;
  15499. }
  15500. };
  15501. function allocateLights( lights ) {
  15502. var dirLights = 0;
  15503. var pointLights = 0;
  15504. var spotLights = 0;
  15505. var hemiLights = 0;
  15506. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  15507. var light = lights[ l ];
  15508. if ( light.onlyShadow ) continue;
  15509. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  15510. if ( light instanceof THREE.PointLight ) pointLights ++;
  15511. if ( light instanceof THREE.SpotLight ) spotLights ++;
  15512. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  15513. }
  15514. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  15515. };
  15516. function allocateShadows( lights ) {
  15517. var maxShadows = 0;
  15518. for ( var l = 0, ll = lights.length; l < ll; l++ ) {
  15519. var light = lights[ l ];
  15520. if ( ! light.castShadow ) continue;
  15521. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  15522. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  15523. }
  15524. return maxShadows;
  15525. };
  15526. // Initialization
  15527. function initGL() {
  15528. try {
  15529. var attributes = {
  15530. alpha: _alpha,
  15531. premultipliedAlpha: _premultipliedAlpha,
  15532. antialias: _antialias,
  15533. stencil: _stencil,
  15534. preserveDrawingBuffer: _preserveDrawingBuffer
  15535. };
  15536. _gl = _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  15537. if ( _gl === null ) {
  15538. throw 'Error creating WebGL context.';
  15539. }
  15540. } catch ( error ) {
  15541. console.error( error );
  15542. }
  15543. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  15544. _glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' );
  15545. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  15546. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15547. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15548. if ( ! _glExtensionTextureFloat ) {
  15549. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  15550. }
  15551. if ( ! _glExtensionStandardDerivatives ) {
  15552. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  15553. }
  15554. if ( ! _glExtensionTextureFilterAnisotropic ) {
  15555. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  15556. }
  15557. if ( ! _glExtensionCompressedTextureS3TC ) {
  15558. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  15559. }
  15560. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15561. _gl.getShaderPrecisionFormat = function() {
  15562. return {
  15563. "rangeMin" : 1,
  15564. "rangeMax" : 1,
  15565. "precision" : 1
  15566. };
  15567. }
  15568. }
  15569. };
  15570. function setDefaultGLState () {
  15571. _gl.clearColor( 0, 0, 0, 1 );
  15572. _gl.clearDepth( 1 );
  15573. _gl.clearStencil( 0 );
  15574. _gl.enable( _gl.DEPTH_TEST );
  15575. _gl.depthFunc( _gl.LEQUAL );
  15576. _gl.frontFace( _gl.CCW );
  15577. _gl.cullFace( _gl.BACK );
  15578. _gl.enable( _gl.CULL_FACE );
  15579. _gl.enable( _gl.BLEND );
  15580. _gl.blendEquation( _gl.FUNC_ADD );
  15581. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  15582. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  15583. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  15584. };
  15585. // default plugins (order is important)
  15586. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  15587. this.addPrePlugin( this.shadowMapPlugin );
  15588. this.addPostPlugin( new THREE.SpritePlugin() );
  15589. this.addPostPlugin( new THREE.LensFlarePlugin() );
  15590. };
  15591. /**
  15592. * @author szimek / https://github.com/szimek/
  15593. * @author alteredq / http://alteredqualia.com/
  15594. */
  15595. THREE.WebGLRenderTarget = function ( width, height, options ) {
  15596. this.width = width;
  15597. this.height = height;
  15598. options = options || {};
  15599. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  15600. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  15601. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  15602. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  15603. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  15604. this.offset = new THREE.Vector2( 0, 0 );
  15605. this.repeat = new THREE.Vector2( 1, 1 );
  15606. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  15607. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  15608. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  15609. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  15610. this.generateMipmaps = true;
  15611. this.shareDepthFrom = null;
  15612. };
  15613. THREE.WebGLRenderTarget.prototype = {
  15614. constructor: THREE.WebGLRenderTarget,
  15615. clone: function () {
  15616. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  15617. tmp.wrapS = this.wrapS;
  15618. tmp.wrapT = this.wrapT;
  15619. tmp.magFilter = this.magFilter;
  15620. tmp.minFilter = this.minFilter;
  15621. tmp.anisotropy = this.anisotropy;
  15622. tmp.offset.copy( this.offset );
  15623. tmp.repeat.copy( this.repeat );
  15624. tmp.format = this.format;
  15625. tmp.type = this.type;
  15626. tmp.depthBuffer = this.depthBuffer;
  15627. tmp.stencilBuffer = this.stencilBuffer;
  15628. tmp.generateMipmaps = this.generateMipmaps;
  15629. tmp.shareDepthFrom = this.shareDepthFrom;
  15630. return tmp;
  15631. },
  15632. dispose: function () {
  15633. this.dispatchEvent( { type: 'dispose' } );
  15634. }
  15635. };
  15636. THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype );
  15637. /**
  15638. * @author alteredq / http://alteredqualia.com
  15639. */
  15640. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  15641. THREE.WebGLRenderTarget.call( this, width, height, options );
  15642. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  15643. };
  15644. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  15645. /**
  15646. * @author mrdoob / http://mrdoob.com/
  15647. */
  15648. THREE.RenderableVertex = function () {
  15649. this.position = new THREE.Vector3();
  15650. this.positionWorld = new THREE.Vector3();
  15651. this.positionScreen = new THREE.Vector4();
  15652. this.visible = true;
  15653. };
  15654. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  15655. this.positionWorld.copy( vertex.positionWorld );
  15656. this.positionScreen.copy( vertex.positionScreen );
  15657. };
  15658. /**
  15659. * @author mrdoob / http://mrdoob.com/
  15660. */
  15661. THREE.RenderableFace3 = function () {
  15662. this.id = 0;
  15663. this.v1 = new THREE.RenderableVertex();
  15664. this.v2 = new THREE.RenderableVertex();
  15665. this.v3 = new THREE.RenderableVertex();
  15666. this.centroidModel = new THREE.Vector3();
  15667. this.normalModel = new THREE.Vector3();
  15668. this.normalModelView = new THREE.Vector3();
  15669. this.vertexNormalsLength = 0;
  15670. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15671. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15672. this.color = null;
  15673. this.material = null;
  15674. this.uvs = [[]];
  15675. this.z = 0;
  15676. };
  15677. /**
  15678. * @author mrdoob / http://mrdoob.com/
  15679. */
  15680. THREE.RenderableObject = function () {
  15681. this.id = 0;
  15682. this.object = null;
  15683. this.z = 0;
  15684. };
  15685. /**
  15686. * @author mrdoob / http://mrdoob.com/
  15687. */
  15688. THREE.RenderableSprite = function () {
  15689. this.id = 0;
  15690. this.object = null;
  15691. this.x = 0;
  15692. this.y = 0;
  15693. this.z = 0;
  15694. this.rotation = 0;
  15695. this.scale = new THREE.Vector2();
  15696. this.material = null;
  15697. };
  15698. /**
  15699. * @author mrdoob / http://mrdoob.com/
  15700. */
  15701. THREE.RenderableLine = function () {
  15702. this.id = 0;
  15703. this.v1 = new THREE.RenderableVertex();
  15704. this.v2 = new THREE.RenderableVertex();
  15705. this.vertexColors = [ new THREE.Color(), new THREE.Color() ];
  15706. this.material = null;
  15707. this.z = 0;
  15708. };
  15709. /**
  15710. * @author mrdoob / http://mrdoob.com/
  15711. * @author alteredq / http://alteredqualia.com/
  15712. */
  15713. THREE.GeometryUtils = {
  15714. // Merge two geometries or geometry and geometry from object (using object's transform)
  15715. merge: function ( geometry1, object2 /* mesh | geometry */, materialIndexOffset ) {
  15716. var matrix, normalMatrix,
  15717. vertexOffset = geometry1.vertices.length,
  15718. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  15719. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  15720. vertices1 = geometry1.vertices,
  15721. vertices2 = geometry2.vertices,
  15722. faces1 = geometry1.faces,
  15723. faces2 = geometry2.faces,
  15724. uvs1 = geometry1.faceVertexUvs[ 0 ],
  15725. uvs2 = geometry2.faceVertexUvs[ 0 ];
  15726. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  15727. if ( object2 instanceof THREE.Mesh ) {
  15728. object2.matrixAutoUpdate && object2.updateMatrix();
  15729. matrix = object2.matrix;
  15730. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  15731. }
  15732. // vertices
  15733. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  15734. var vertex = vertices2[ i ];
  15735. var vertexCopy = vertex.clone();
  15736. if ( matrix ) vertexCopy.applyMatrix4( matrix );
  15737. vertices1.push( vertexCopy );
  15738. }
  15739. // faces
  15740. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  15741. var face = faces2[ i ], faceCopy, normal, color,
  15742. faceVertexNormals = face.vertexNormals,
  15743. faceVertexColors = face.vertexColors;
  15744. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  15745. faceCopy.normal.copy( face.normal );
  15746. if ( normalMatrix ) {
  15747. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  15748. }
  15749. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  15750. normal = faceVertexNormals[ j ].clone();
  15751. if ( normalMatrix ) {
  15752. normal.applyMatrix3( normalMatrix ).normalize();
  15753. }
  15754. faceCopy.vertexNormals.push( normal );
  15755. }
  15756. faceCopy.color.copy( face.color );
  15757. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  15758. color = faceVertexColors[ j ];
  15759. faceCopy.vertexColors.push( color.clone() );
  15760. }
  15761. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  15762. faceCopy.centroid.copy( face.centroid );
  15763. if ( matrix ) {
  15764. faceCopy.centroid.applyMatrix4( matrix );
  15765. }
  15766. faces1.push( faceCopy );
  15767. }
  15768. // uvs
  15769. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  15770. var uv = uvs2[ i ], uvCopy = [];
  15771. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  15772. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  15773. }
  15774. uvs1.push( uvCopy );
  15775. }
  15776. },
  15777. // Get random point in triangle (via barycentric coordinates)
  15778. // (uniform distribution)
  15779. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  15780. randomPointInTriangle: function () {
  15781. var vector = new THREE.Vector3();
  15782. return function ( vectorA, vectorB, vectorC ) {
  15783. var point = new THREE.Vector3();
  15784. var a = THREE.Math.random16();
  15785. var b = THREE.Math.random16();
  15786. if ( ( a + b ) > 1 ) {
  15787. a = 1 - a;
  15788. b = 1 - b;
  15789. }
  15790. var c = 1 - a - b;
  15791. point.copy( vectorA );
  15792. point.multiplyScalar( a );
  15793. vector.copy( vectorB );
  15794. vector.multiplyScalar( b );
  15795. point.add( vector );
  15796. vector.copy( vectorC );
  15797. vector.multiplyScalar( c );
  15798. point.add( vector );
  15799. return point;
  15800. };
  15801. }(),
  15802. // Get random point in face (triangle / quad)
  15803. // (uniform distribution)
  15804. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  15805. var vA, vB, vC, vD;
  15806. vA = geometry.vertices[ face.a ];
  15807. vB = geometry.vertices[ face.b ];
  15808. vC = geometry.vertices[ face.c ];
  15809. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  15810. },
  15811. // Get uniformly distributed random points in mesh
  15812. // - create array with cumulative sums of face areas
  15813. // - pick random number from 0 to total area
  15814. // - find corresponding place in area array by binary search
  15815. // - get random point in face
  15816. randomPointsInGeometry: function ( geometry, n ) {
  15817. var face, i,
  15818. faces = geometry.faces,
  15819. vertices = geometry.vertices,
  15820. il = faces.length,
  15821. totalArea = 0,
  15822. cumulativeAreas = [],
  15823. vA, vB, vC, vD;
  15824. // precompute face areas
  15825. for ( i = 0; i < il; i ++ ) {
  15826. face = faces[ i ];
  15827. vA = vertices[ face.a ];
  15828. vB = vertices[ face.b ];
  15829. vC = vertices[ face.c ];
  15830. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  15831. totalArea += face._area;
  15832. cumulativeAreas[ i ] = totalArea;
  15833. }
  15834. // binary search cumulative areas array
  15835. function binarySearchIndices( value ) {
  15836. function binarySearch( start, end ) {
  15837. // return closest larger index
  15838. // if exact number is not found
  15839. if ( end < start )
  15840. return start;
  15841. var mid = start + Math.floor( ( end - start ) / 2 );
  15842. if ( cumulativeAreas[ mid ] > value ) {
  15843. return binarySearch( start, mid - 1 );
  15844. } else if ( cumulativeAreas[ mid ] < value ) {
  15845. return binarySearch( mid + 1, end );
  15846. } else {
  15847. return mid;
  15848. }
  15849. }
  15850. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  15851. return result;
  15852. }
  15853. // pick random face weighted by face area
  15854. var r, index,
  15855. result = [];
  15856. var stats = {};
  15857. for ( i = 0; i < n; i ++ ) {
  15858. r = THREE.Math.random16() * totalArea;
  15859. index = binarySearchIndices( r );
  15860. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  15861. if ( ! stats[ index ] ) {
  15862. stats[ index ] = 1;
  15863. } else {
  15864. stats[ index ] += 1;
  15865. }
  15866. }
  15867. return result;
  15868. },
  15869. // Get triangle area (half of parallelogram)
  15870. // http://mathworld.wolfram.com/TriangleArea.html
  15871. triangleArea: function () {
  15872. var vector1 = new THREE.Vector3();
  15873. var vector2 = new THREE.Vector3();
  15874. return function ( vectorA, vectorB, vectorC ) {
  15875. vector1.subVectors( vectorB, vectorA );
  15876. vector2.subVectors( vectorC, vectorA );
  15877. vector1.cross( vector2 );
  15878. return 0.5 * vector1.length();
  15879. };
  15880. }(),
  15881. // Center geometry so that 0,0,0 is in center of bounding box
  15882. center: function ( geometry ) {
  15883. geometry.computeBoundingBox();
  15884. var bb = geometry.boundingBox;
  15885. var offset = new THREE.Vector3();
  15886. offset.addVectors( bb.min, bb.max );
  15887. offset.multiplyScalar( -0.5 );
  15888. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  15889. geometry.computeBoundingBox();
  15890. return offset;
  15891. },
  15892. triangulateQuads: function ( geometry ) {
  15893. var i, il, j, jl;
  15894. var faces = [];
  15895. var faceVertexUvs = [];
  15896. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  15897. faceVertexUvs[ i ] = [];
  15898. }
  15899. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15900. var face = geometry.faces[ i ];
  15901. faces.push( face );
  15902. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15903. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  15904. }
  15905. }
  15906. geometry.faces = faces;
  15907. geometry.faceVertexUvs = faceVertexUvs;
  15908. geometry.computeCentroids();
  15909. geometry.computeFaceNormals();
  15910. geometry.computeVertexNormals();
  15911. if ( geometry.hasTangents ) geometry.computeTangents();
  15912. }
  15913. };
  15914. /**
  15915. * @author alteredq / http://alteredqualia.com/
  15916. * @author mrdoob / http://mrdoob.com/
  15917. */
  15918. THREE.ImageUtils = {
  15919. crossOrigin: undefined,
  15920. loadTexture: function ( url, mapping, onLoad, onError ) {
  15921. var loader = new THREE.ImageLoader();
  15922. loader.crossOrigin = this.crossOrigin;
  15923. var texture = new THREE.Texture( undefined, mapping );
  15924. var image = loader.load( url, function () {
  15925. texture.needsUpdate = true;
  15926. if ( onLoad ) onLoad( texture );
  15927. } );
  15928. texture.image = image;
  15929. texture.sourceFile = url;
  15930. return texture;
  15931. },
  15932. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  15933. var texture = new THREE.CompressedTexture();
  15934. texture.mapping = mapping;
  15935. var request = new XMLHttpRequest();
  15936. request.onload = function () {
  15937. var buffer = request.response;
  15938. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15939. texture.format = dds.format;
  15940. texture.mipmaps = dds.mipmaps;
  15941. texture.image.width = dds.width;
  15942. texture.image.height = dds.height;
  15943. // gl.generateMipmap fails for compressed textures
  15944. // mipmaps must be embedded in the DDS file
  15945. // or texture filters must not use mipmapping
  15946. texture.generateMipmaps = false;
  15947. texture.needsUpdate = true;
  15948. if ( onLoad ) onLoad( texture );
  15949. }
  15950. request.onerror = onError;
  15951. request.open( 'GET', url, true );
  15952. request.responseType = "arraybuffer";
  15953. request.send( null );
  15954. return texture;
  15955. },
  15956. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  15957. var images = [];
  15958. images.loadCount = 0;
  15959. var texture = new THREE.Texture();
  15960. texture.image = images;
  15961. if ( mapping !== undefined ) texture.mapping = mapping;
  15962. // no flipping needed for cube textures
  15963. texture.flipY = false;
  15964. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15965. var cubeImage = new Image();
  15966. images[ i ] = cubeImage;
  15967. cubeImage.onload = function () {
  15968. images.loadCount += 1;
  15969. if ( images.loadCount === 6 ) {
  15970. texture.needsUpdate = true;
  15971. if ( onLoad ) onLoad( texture );
  15972. }
  15973. };
  15974. cubeImage.onerror = onError;
  15975. cubeImage.crossOrigin = this.crossOrigin;
  15976. cubeImage.src = array[ i ];
  15977. }
  15978. return texture;
  15979. },
  15980. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  15981. var images = [];
  15982. images.loadCount = 0;
  15983. var texture = new THREE.CompressedTexture();
  15984. texture.image = images;
  15985. if ( mapping !== undefined ) texture.mapping = mapping;
  15986. // no flipping for cube textures
  15987. // (also flipping doesn't work for compressed textures )
  15988. texture.flipY = false;
  15989. // can't generate mipmaps for compressed textures
  15990. // mips must be embedded in DDS files
  15991. texture.generateMipmaps = false;
  15992. var generateCubeFaceCallback = function ( rq, img ) {
  15993. return function () {
  15994. var buffer = rq.response;
  15995. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15996. img.format = dds.format;
  15997. img.mipmaps = dds.mipmaps;
  15998. img.width = dds.width;
  15999. img.height = dds.height;
  16000. images.loadCount += 1;
  16001. if ( images.loadCount === 6 ) {
  16002. texture.format = dds.format;
  16003. texture.needsUpdate = true;
  16004. if ( onLoad ) onLoad( texture );
  16005. }
  16006. }
  16007. }
  16008. // compressed cubemap textures as 6 separate DDS files
  16009. if ( array instanceof Array ) {
  16010. for ( var i = 0, il = array.length; i < il; ++ i ) {
  16011. var cubeImage = {};
  16012. images[ i ] = cubeImage;
  16013. var request = new XMLHttpRequest();
  16014. request.onload = generateCubeFaceCallback( request, cubeImage );
  16015. request.onerror = onError;
  16016. var url = array[ i ];
  16017. request.open( 'GET', url, true );
  16018. request.responseType = "arraybuffer";
  16019. request.send( null );
  16020. }
  16021. // compressed cubemap texture stored in a single DDS file
  16022. } else {
  16023. var url = array;
  16024. var request = new XMLHttpRequest();
  16025. request.onload = function( ) {
  16026. var buffer = request.response;
  16027. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16028. if ( dds.isCubemap ) {
  16029. var faces = dds.mipmaps.length / dds.mipmapCount;
  16030. for ( var f = 0; f < faces; f ++ ) {
  16031. images[ f ] = { mipmaps : [] };
  16032. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16033. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  16034. images[ f ].format = dds.format;
  16035. images[ f ].width = dds.width;
  16036. images[ f ].height = dds.height;
  16037. }
  16038. }
  16039. texture.format = dds.format;
  16040. texture.needsUpdate = true;
  16041. if ( onLoad ) onLoad( texture );
  16042. }
  16043. }
  16044. request.onerror = onError;
  16045. request.open( 'GET', url, true );
  16046. request.responseType = "arraybuffer";
  16047. request.send( null );
  16048. }
  16049. return texture;
  16050. },
  16051. loadDDSTexture: function ( url, mapping, onLoad, onError ) {
  16052. var images = [];
  16053. images.loadCount = 0;
  16054. var texture = new THREE.CompressedTexture();
  16055. texture.image = images;
  16056. if ( mapping !== undefined ) texture.mapping = mapping;
  16057. // no flipping for cube textures
  16058. // (also flipping doesn't work for compressed textures )
  16059. texture.flipY = false;
  16060. // can't generate mipmaps for compressed textures
  16061. // mips must be embedded in DDS files
  16062. texture.generateMipmaps = false;
  16063. {
  16064. var request = new XMLHttpRequest();
  16065. request.onload = function( ) {
  16066. var buffer = request.response;
  16067. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16068. if ( dds.isCubemap ) {
  16069. var faces = dds.mipmaps.length / dds.mipmapCount;
  16070. for ( var f = 0; f < faces; f ++ ) {
  16071. images[ f ] = { mipmaps : [] };
  16072. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16073. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  16074. images[ f ].format = dds.format;
  16075. images[ f ].width = dds.width;
  16076. images[ f ].height = dds.height;
  16077. }
  16078. }
  16079. } else {
  16080. texture.image.width = dds.width;
  16081. texture.image.height = dds.height;
  16082. texture.mipmaps = dds.mipmaps;
  16083. }
  16084. texture.format = dds.format;
  16085. texture.needsUpdate = true;
  16086. if ( onLoad ) onLoad( texture );
  16087. }
  16088. request.onerror = onError;
  16089. request.open( 'GET', url, true );
  16090. request.responseType = "arraybuffer";
  16091. request.send( null );
  16092. }
  16093. return texture;
  16094. },
  16095. parseDDS: function ( buffer, loadMipmaps ) {
  16096. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  16097. // Adapted from @toji's DDS utils
  16098. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  16099. // All values and structures referenced from:
  16100. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  16101. var DDS_MAGIC = 0x20534444;
  16102. var DDSD_CAPS = 0x1,
  16103. DDSD_HEIGHT = 0x2,
  16104. DDSD_WIDTH = 0x4,
  16105. DDSD_PITCH = 0x8,
  16106. DDSD_PIXELFORMAT = 0x1000,
  16107. DDSD_MIPMAPCOUNT = 0x20000,
  16108. DDSD_LINEARSIZE = 0x80000,
  16109. DDSD_DEPTH = 0x800000;
  16110. var DDSCAPS_COMPLEX = 0x8,
  16111. DDSCAPS_MIPMAP = 0x400000,
  16112. DDSCAPS_TEXTURE = 0x1000;
  16113. var DDSCAPS2_CUBEMAP = 0x200,
  16114. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  16115. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  16116. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  16117. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  16118. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  16119. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  16120. DDSCAPS2_VOLUME = 0x200000;
  16121. var DDPF_ALPHAPIXELS = 0x1,
  16122. DDPF_ALPHA = 0x2,
  16123. DDPF_FOURCC = 0x4,
  16124. DDPF_RGB = 0x40,
  16125. DDPF_YUV = 0x200,
  16126. DDPF_LUMINANCE = 0x20000;
  16127. function fourCCToInt32( value ) {
  16128. return value.charCodeAt(0) +
  16129. (value.charCodeAt(1) << 8) +
  16130. (value.charCodeAt(2) << 16) +
  16131. (value.charCodeAt(3) << 24);
  16132. }
  16133. function int32ToFourCC( value ) {
  16134. return String.fromCharCode(
  16135. value & 0xff,
  16136. (value >> 8) & 0xff,
  16137. (value >> 16) & 0xff,
  16138. (value >> 24) & 0xff
  16139. );
  16140. }
  16141. function loadARGBMip( buffer, dataOffset, width, height ) {
  16142. var dataLength = width*height*4;
  16143. var srcBuffer = new Uint8Array( buffer, dataOffset, dataLength );
  16144. var byteArray = new Uint8Array( dataLength );
  16145. var dst = 0;
  16146. var src = 0;
  16147. for ( var y = 0; y < height; y++ ) {
  16148. for ( var x = 0; x < width; x++ ) {
  16149. var b = srcBuffer[src]; src++;
  16150. var g = srcBuffer[src]; src++;
  16151. var r = srcBuffer[src]; src++;
  16152. var a = srcBuffer[src]; src++;
  16153. byteArray[dst] = r; dst++; //r
  16154. byteArray[dst] = g; dst++; //g
  16155. byteArray[dst] = b; dst++; //b
  16156. byteArray[dst] = a; dst++; //a
  16157. }
  16158. }
  16159. return byteArray;
  16160. }
  16161. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  16162. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  16163. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  16164. var headerLengthInt = 31; // The header length in 32 bit ints
  16165. // Offsets into the header array
  16166. var off_magic = 0;
  16167. var off_size = 1;
  16168. var off_flags = 2;
  16169. var off_height = 3;
  16170. var off_width = 4;
  16171. var off_mipmapCount = 7;
  16172. var off_pfFlags = 20;
  16173. var off_pfFourCC = 21;
  16174. var off_RGBBitCount = 22;
  16175. var off_RBitMask = 23;
  16176. var off_GBitMask = 24;
  16177. var off_BBitMask = 25;
  16178. var off_ABitMask = 26;
  16179. var off_caps = 27;
  16180. var off_caps2 = 28;
  16181. var off_caps3 = 29;
  16182. var off_caps4 = 30;
  16183. // Parse header
  16184. var header = new Int32Array( buffer, 0, headerLengthInt );
  16185. if ( header[ off_magic ] !== DDS_MAGIC ) {
  16186. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  16187. return dds;
  16188. }
  16189. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  16190. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  16191. return dds;
  16192. }
  16193. var blockBytes;
  16194. var fourCC = header[ off_pfFourCC ];
  16195. var isRGBAUncompressed = false;
  16196. switch ( fourCC ) {
  16197. case FOURCC_DXT1:
  16198. blockBytes = 8;
  16199. dds.format = THREE.RGB_S3TC_DXT1_Format;
  16200. break;
  16201. case FOURCC_DXT3:
  16202. blockBytes = 16;
  16203. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  16204. break;
  16205. case FOURCC_DXT5:
  16206. blockBytes = 16;
  16207. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  16208. break;
  16209. default:
  16210. if( header[off_RGBBitCount] ==32
  16211. && header[off_RBitMask]&0xff0000
  16212. && header[off_GBitMask]&0xff00
  16213. && header[off_BBitMask]&0xff
  16214. && header[off_ABitMask]&0xff000000 ) {
  16215. isRGBAUncompressed = true;
  16216. blockBytes = 64;
  16217. dds.format = THREE.RGBAFormat;
  16218. } else {
  16219. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  16220. return dds;
  16221. }
  16222. }
  16223. dds.mipmapCount = 1;
  16224. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  16225. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  16226. }
  16227. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  16228. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  16229. dds.width = header[ off_width ];
  16230. dds.height = header[ off_height ];
  16231. var dataOffset = header[ off_size ] + 4;
  16232. // Extract mipmaps buffers
  16233. var width = dds.width;
  16234. var height = dds.height;
  16235. var faces = dds.isCubemap ? 6 : 1;
  16236. for ( var face = 0; face < faces; face ++ ) {
  16237. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16238. if( isRGBAUncompressed ) {
  16239. var byteArray = loadARGBMip( buffer, dataOffset, width, height );
  16240. var dataLength = byteArray.length;
  16241. } else {
  16242. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  16243. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  16244. }
  16245. var mipmap = { "data": byteArray, "width": width, "height": height };
  16246. dds.mipmaps.push( mipmap );
  16247. dataOffset += dataLength;
  16248. width = Math.max( width * 0.5, 1 );
  16249. height = Math.max( height * 0.5, 1 );
  16250. }
  16251. width = dds.width;
  16252. height = dds.height;
  16253. }
  16254. return dds;
  16255. },
  16256. getNormalMap: function ( image, depth ) {
  16257. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  16258. var cross = function ( a, b ) {
  16259. 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 ] ];
  16260. }
  16261. var subtract = function ( a, b ) {
  16262. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  16263. }
  16264. var normalize = function ( a ) {
  16265. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  16266. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  16267. }
  16268. depth = depth | 1;
  16269. var width = image.width;
  16270. var height = image.height;
  16271. var canvas = document.createElement( 'canvas' );
  16272. canvas.width = width;
  16273. canvas.height = height;
  16274. var context = canvas.getContext( '2d' );
  16275. context.drawImage( image, 0, 0 );
  16276. var data = context.getImageData( 0, 0, width, height ).data;
  16277. var imageData = context.createImageData( width, height );
  16278. var output = imageData.data;
  16279. for ( var x = 0; x < width; x ++ ) {
  16280. for ( var y = 0; y < height; y ++ ) {
  16281. var ly = y - 1 < 0 ? 0 : y - 1;
  16282. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  16283. var lx = x - 1 < 0 ? 0 : x - 1;
  16284. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  16285. var points = [];
  16286. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  16287. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  16288. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  16289. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  16290. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  16291. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  16292. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  16293. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  16294. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  16295. var normals = [];
  16296. var num_points = points.length;
  16297. for ( var i = 0; i < num_points; i ++ ) {
  16298. var v1 = points[ i ];
  16299. var v2 = points[ ( i + 1 ) % num_points ];
  16300. v1 = subtract( v1, origin );
  16301. v2 = subtract( v2, origin );
  16302. normals.push( normalize( cross( v1, v2 ) ) );
  16303. }
  16304. var normal = [ 0, 0, 0 ];
  16305. for ( var i = 0; i < normals.length; i ++ ) {
  16306. normal[ 0 ] += normals[ i ][ 0 ];
  16307. normal[ 1 ] += normals[ i ][ 1 ];
  16308. normal[ 2 ] += normals[ i ][ 2 ];
  16309. }
  16310. normal[ 0 ] /= normals.length;
  16311. normal[ 1 ] /= normals.length;
  16312. normal[ 2 ] /= normals.length;
  16313. var idx = ( y * width + x ) * 4;
  16314. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16315. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16316. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  16317. output[ idx + 3 ] = 255;
  16318. }
  16319. }
  16320. context.putImageData( imageData, 0, 0 );
  16321. return canvas;
  16322. },
  16323. generateDataTexture: function ( width, height, color ) {
  16324. var size = width * height;
  16325. var data = new Uint8Array( 3 * size );
  16326. var r = Math.floor( color.r * 255 );
  16327. var g = Math.floor( color.g * 255 );
  16328. var b = Math.floor( color.b * 255 );
  16329. for ( var i = 0; i < size; i ++ ) {
  16330. data[ i * 3 ] = r;
  16331. data[ i * 3 + 1 ] = g;
  16332. data[ i * 3 + 2 ] = b;
  16333. }
  16334. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  16335. texture.needsUpdate = true;
  16336. return texture;
  16337. }
  16338. };
  16339. /**
  16340. * @author alteredq / http://alteredqualia.com/
  16341. */
  16342. THREE.SceneUtils = {
  16343. createMultiMaterialObject: function ( geometry, materials ) {
  16344. var group = new THREE.Object3D();
  16345. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  16346. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  16347. }
  16348. return group;
  16349. },
  16350. detach : function ( child, parent, scene ) {
  16351. child.applyMatrix( parent.matrixWorld );
  16352. parent.remove( child );
  16353. scene.add( child );
  16354. },
  16355. attach: function ( child, scene, parent ) {
  16356. var matrixWorldInverse = new THREE.Matrix4();
  16357. matrixWorldInverse.getInverse( parent.matrixWorld );
  16358. child.applyMatrix( matrixWorldInverse );
  16359. scene.remove( child );
  16360. parent.add( child );
  16361. }
  16362. };
  16363. /**
  16364. * @author zz85 / http://www.lab4games.net/zz85/blog
  16365. * @author alteredq / http://alteredqualia.com/
  16366. *
  16367. * For Text operations in three.js (See TextGeometry)
  16368. *
  16369. * It uses techniques used in:
  16370. *
  16371. * typeface.js and canvastext
  16372. * For converting fonts and rendering with javascript
  16373. * http://typeface.neocracy.org
  16374. *
  16375. * Triangulation ported from AS3
  16376. * Simple Polygon Triangulation
  16377. * http://actionsnippet.com/?p=1462
  16378. *
  16379. * A Method to triangulate shapes with holes
  16380. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  16381. *
  16382. */
  16383. THREE.FontUtils = {
  16384. faces : {},
  16385. // Just for now. face[weight][style]
  16386. face : "helvetiker",
  16387. weight: "normal",
  16388. style : "normal",
  16389. size : 150,
  16390. divisions : 10,
  16391. getFace : function() {
  16392. return this.faces[ this.face ][ this.weight ][ this.style ];
  16393. },
  16394. loadFace : function( data ) {
  16395. var family = data.familyName.toLowerCase();
  16396. var ThreeFont = this;
  16397. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  16398. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  16399. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16400. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16401. return data;
  16402. },
  16403. drawText : function( text ) {
  16404. var characterPts = [], allPts = [];
  16405. // RenderText
  16406. var i, p,
  16407. face = this.getFace(),
  16408. scale = this.size / face.resolution,
  16409. offset = 0,
  16410. chars = String( text ).split( '' ),
  16411. length = chars.length;
  16412. var fontPaths = [];
  16413. for ( i = 0; i < length; i ++ ) {
  16414. var path = new THREE.Path();
  16415. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  16416. offset += ret.offset;
  16417. fontPaths.push( ret.path );
  16418. }
  16419. // get the width
  16420. var width = offset / 2;
  16421. //
  16422. // for ( p = 0; p < allPts.length; p++ ) {
  16423. //
  16424. // allPts[ p ].x -= width;
  16425. //
  16426. // }
  16427. //var extract = this.extractPoints( allPts, characterPts );
  16428. //extract.contour = allPts;
  16429. //extract.paths = fontPaths;
  16430. //extract.offset = width;
  16431. return { paths : fontPaths, offset : width };
  16432. },
  16433. extractGlyphPoints : function( c, face, scale, offset, path ) {
  16434. var pts = [];
  16435. var i, i2, divisions,
  16436. outline, action, length,
  16437. scaleX, scaleY,
  16438. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16439. laste,
  16440. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16441. if ( !glyph ) return;
  16442. if ( glyph.o ) {
  16443. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16444. length = outline.length;
  16445. scaleX = scale;
  16446. scaleY = scale;
  16447. for ( i = 0; i < length; ) {
  16448. action = outline[ i ++ ];
  16449. //console.log( action );
  16450. switch( action ) {
  16451. case 'm':
  16452. // Move To
  16453. x = outline[ i++ ] * scaleX + offset;
  16454. y = outline[ i++ ] * scaleY;
  16455. path.moveTo( x, y );
  16456. break;
  16457. case 'l':
  16458. // Line To
  16459. x = outline[ i++ ] * scaleX + offset;
  16460. y = outline[ i++ ] * scaleY;
  16461. path.lineTo(x,y);
  16462. break;
  16463. case 'q':
  16464. // QuadraticCurveTo
  16465. cpx = outline[ i++ ] * scaleX + offset;
  16466. cpy = outline[ i++ ] * scaleY;
  16467. cpx1 = outline[ i++ ] * scaleX + offset;
  16468. cpy1 = outline[ i++ ] * scaleY;
  16469. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  16470. laste = pts[ pts.length - 1 ];
  16471. if ( laste ) {
  16472. cpx0 = laste.x;
  16473. cpy0 = laste.y;
  16474. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16475. var t = i2 / divisions;
  16476. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16477. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16478. }
  16479. }
  16480. break;
  16481. case 'b':
  16482. // Cubic Bezier Curve
  16483. cpx = outline[ i++ ] * scaleX + offset;
  16484. cpy = outline[ i++ ] * scaleY;
  16485. cpx1 = outline[ i++ ] * scaleX + offset;
  16486. cpy1 = outline[ i++ ] * -scaleY;
  16487. cpx2 = outline[ i++ ] * scaleX + offset;
  16488. cpy2 = outline[ i++ ] * -scaleY;
  16489. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  16490. laste = pts[ pts.length - 1 ];
  16491. if ( laste ) {
  16492. cpx0 = laste.x;
  16493. cpy0 = laste.y;
  16494. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16495. var t = i2 / divisions;
  16496. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16497. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16498. }
  16499. }
  16500. break;
  16501. }
  16502. }
  16503. }
  16504. return { offset: glyph.ha*scale, path:path};
  16505. }
  16506. };
  16507. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16508. // Parameters
  16509. parameters = parameters || {};
  16510. var size = parameters.size !== undefined ? parameters.size : 100;
  16511. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16512. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16513. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16514. var style = parameters.style !== undefined ? parameters.style : "normal";
  16515. THREE.FontUtils.size = size;
  16516. THREE.FontUtils.divisions = curveSegments;
  16517. THREE.FontUtils.face = font;
  16518. THREE.FontUtils.weight = weight;
  16519. THREE.FontUtils.style = style;
  16520. // Get a Font data json object
  16521. var data = THREE.FontUtils.drawText( text );
  16522. var paths = data.paths;
  16523. var shapes = [];
  16524. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16525. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16526. }
  16527. return shapes;
  16528. };
  16529. /**
  16530. * This code is a quick port of code written in C++ which was submitted to
  16531. * flipcode.com by John W. Ratcliff // July 22, 2000
  16532. * See original code and more information here:
  16533. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16534. *
  16535. * ported to actionscript by Zevan Rosser
  16536. * www.actionsnippet.com
  16537. *
  16538. * ported to javascript by Joshua Koo
  16539. * http://www.lab4games.net/zz85/blog
  16540. *
  16541. */
  16542. ( function( namespace ) {
  16543. var EPSILON = 0.0000000001;
  16544. // takes in an contour array and returns
  16545. var process = function( contour, indices ) {
  16546. var n = contour.length;
  16547. if ( n < 3 ) return null;
  16548. var result = [],
  16549. verts = [],
  16550. vertIndices = [];
  16551. /* we want a counter-clockwise polygon in verts */
  16552. var u, v, w;
  16553. if ( area( contour ) > 0.0 ) {
  16554. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16555. } else {
  16556. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16557. }
  16558. var nv = n;
  16559. /* remove nv - 2 vertices, creating 1 triangle every time */
  16560. var count = 2 * nv; /* error detection */
  16561. for( v = nv - 1; nv > 2; ) {
  16562. /* if we loop, it is probably a non-simple polygon */
  16563. if ( ( count-- ) <= 0 ) {
  16564. //** Triangulate: ERROR - probable bad polygon!
  16565. //throw ( "Warning, unable to triangulate polygon!" );
  16566. //return null;
  16567. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16568. console.log( "Warning, unable to triangulate polygon!" );
  16569. if ( indices ) return vertIndices;
  16570. return result;
  16571. }
  16572. /* three consecutive vertices in current polygon, <u,v,w> */
  16573. u = v; if ( nv <= u ) u = 0; /* previous */
  16574. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16575. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16576. if ( snip( contour, u, v, w, nv, verts ) ) {
  16577. var a, b, c, s, t;
  16578. /* true names of the vertices */
  16579. a = verts[ u ];
  16580. b = verts[ v ];
  16581. c = verts[ w ];
  16582. /* output Triangle */
  16583. result.push( [ contour[ a ],
  16584. contour[ b ],
  16585. contour[ c ] ] );
  16586. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16587. /* remove v from the remaining polygon */
  16588. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  16589. verts[ s ] = verts[ t ];
  16590. }
  16591. nv--;
  16592. /* reset error detection counter */
  16593. count = 2 * nv;
  16594. }
  16595. }
  16596. if ( indices ) return vertIndices;
  16597. return result;
  16598. };
  16599. // calculate area of the contour polygon
  16600. var area = function ( contour ) {
  16601. var n = contour.length;
  16602. var a = 0.0;
  16603. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16604. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16605. }
  16606. return a * 0.5;
  16607. };
  16608. var snip = function ( contour, u, v, w, n, verts ) {
  16609. var p;
  16610. var ax, ay, bx, by;
  16611. var cx, cy, px, py;
  16612. ax = contour[ verts[ u ] ].x;
  16613. ay = contour[ verts[ u ] ].y;
  16614. bx = contour[ verts[ v ] ].x;
  16615. by = contour[ verts[ v ] ].y;
  16616. cx = contour[ verts[ w ] ].x;
  16617. cy = contour[ verts[ w ] ].y;
  16618. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16619. var aX, aY, bX, bY, cX, cY;
  16620. var apx, apy, bpx, bpy, cpx, cpy;
  16621. var cCROSSap, bCROSScp, aCROSSbp;
  16622. aX = cx - bx; aY = cy - by;
  16623. bX = ax - cx; bY = ay - cy;
  16624. cX = bx - ax; cY = by - ay;
  16625. for ( p = 0; p < n; p++ ) {
  16626. px = contour[ verts[ p ] ].x
  16627. py = contour[ verts[ p ] ].y
  16628. if ( ( (px === ax) && (py === ay) ) ||
  16629. ( (px === bx) && (py === by) ) ||
  16630. ( (px === cx) && (py === cy) ) ) continue;
  16631. apx = px - ax; apy = py - ay;
  16632. bpx = px - bx; bpy = py - by;
  16633. cpx = px - cx; cpy = py - cy;
  16634. // see if p is inside triangle abc
  16635. aCROSSbp = aX*bpy - aY*bpx;
  16636. cCROSSap = cX*apy - cY*apx;
  16637. bCROSScp = bX*cpy - bY*cpx;
  16638. if ( (aCROSSbp >= -EPSILON) && (bCROSScp >= -EPSILON) && (cCROSSap >= -EPSILON) ) return false;
  16639. }
  16640. return true;
  16641. };
  16642. namespace.Triangulate = process;
  16643. namespace.Triangulate.area = area;
  16644. return namespace;
  16645. })(THREE.FontUtils);
  16646. // To use the typeface.js face files, hook up the API
  16647. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  16648. THREE.typeface_js = self._typeface_js;
  16649. /**
  16650. * @author zz85 / http://www.lab4games.net/zz85/blog
  16651. * Extensible curve object
  16652. *
  16653. * Some common of Curve methods
  16654. * .getPoint(t), getTangent(t)
  16655. * .getPointAt(u), getTagentAt(u)
  16656. * .getPoints(), .getSpacedPoints()
  16657. * .getLength()
  16658. * .updateArcLengths()
  16659. *
  16660. * This following classes subclasses THREE.Curve:
  16661. *
  16662. * -- 2d classes --
  16663. * THREE.LineCurve
  16664. * THREE.QuadraticBezierCurve
  16665. * THREE.CubicBezierCurve
  16666. * THREE.SplineCurve
  16667. * THREE.ArcCurve
  16668. * THREE.EllipseCurve
  16669. *
  16670. * -- 3d classes --
  16671. * THREE.LineCurve3
  16672. * THREE.QuadraticBezierCurve3
  16673. * THREE.CubicBezierCurve3
  16674. * THREE.SplineCurve3
  16675. * THREE.ClosedSplineCurve3
  16676. *
  16677. * A series of curves can be represented as a THREE.CurvePath
  16678. *
  16679. **/
  16680. /**************************************************************
  16681. * Abstract Curve base class
  16682. **************************************************************/
  16683. THREE.Curve = function () {
  16684. };
  16685. // Virtual base class method to overwrite and implement in subclasses
  16686. // - t [0 .. 1]
  16687. THREE.Curve.prototype.getPoint = function ( t ) {
  16688. console.log( "Warning, getPoint() not implemented!" );
  16689. return null;
  16690. };
  16691. // Get point at relative position in curve according to arc length
  16692. // - u [0 .. 1]
  16693. THREE.Curve.prototype.getPointAt = function ( u ) {
  16694. var t = this.getUtoTmapping( u );
  16695. return this.getPoint( t );
  16696. };
  16697. // Get sequence of points using getPoint( t )
  16698. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16699. if ( !divisions ) divisions = 5;
  16700. var d, pts = [];
  16701. for ( d = 0; d <= divisions; d ++ ) {
  16702. pts.push( this.getPoint( d / divisions ) );
  16703. }
  16704. return pts;
  16705. };
  16706. // Get sequence of points using getPointAt( u )
  16707. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16708. if ( !divisions ) divisions = 5;
  16709. var d, pts = [];
  16710. for ( d = 0; d <= divisions; d ++ ) {
  16711. pts.push( this.getPointAt( d / divisions ) );
  16712. }
  16713. return pts;
  16714. };
  16715. // Get total curve arc length
  16716. THREE.Curve.prototype.getLength = function () {
  16717. var lengths = this.getLengths();
  16718. return lengths[ lengths.length - 1 ];
  16719. };
  16720. // Get list of cumulative segment lengths
  16721. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16722. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16723. if ( this.cacheArcLengths
  16724. && ( this.cacheArcLengths.length == divisions + 1 )
  16725. && !this.needsUpdate) {
  16726. //console.log( "cached", this.cacheArcLengths );
  16727. return this.cacheArcLengths;
  16728. }
  16729. this.needsUpdate = false;
  16730. var cache = [];
  16731. var current, last = this.getPoint( 0 );
  16732. var p, sum = 0;
  16733. cache.push( 0 );
  16734. for ( p = 1; p <= divisions; p ++ ) {
  16735. current = this.getPoint ( p / divisions );
  16736. sum += current.distanceTo( last );
  16737. cache.push( sum );
  16738. last = current;
  16739. }
  16740. this.cacheArcLengths = cache;
  16741. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16742. };
  16743. THREE.Curve.prototype.updateArcLengths = function() {
  16744. this.needsUpdate = true;
  16745. this.getLengths();
  16746. };
  16747. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16748. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16749. var arcLengths = this.getLengths();
  16750. var i = 0, il = arcLengths.length;
  16751. var targetArcLength; // The targeted u distance value to get
  16752. if ( distance ) {
  16753. targetArcLength = distance;
  16754. } else {
  16755. targetArcLength = u * arcLengths[ il - 1 ];
  16756. }
  16757. //var time = Date.now();
  16758. // binary search for the index with largest value smaller than target u distance
  16759. var low = 0, high = il - 1, comparison;
  16760. while ( low <= high ) {
  16761. 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
  16762. comparison = arcLengths[ i ] - targetArcLength;
  16763. if ( comparison < 0 ) {
  16764. low = i + 1;
  16765. continue;
  16766. } else if ( comparison > 0 ) {
  16767. high = i - 1;
  16768. continue;
  16769. } else {
  16770. high = i;
  16771. break;
  16772. // DONE
  16773. }
  16774. }
  16775. i = high;
  16776. //console.log('b' , i, low, high, Date.now()- time);
  16777. if ( arcLengths[ i ] == targetArcLength ) {
  16778. var t = i / ( il - 1 );
  16779. return t;
  16780. }
  16781. // we could get finer grain at lengths, or use simple interpolatation between two points
  16782. var lengthBefore = arcLengths[ i ];
  16783. var lengthAfter = arcLengths[ i + 1 ];
  16784. var segmentLength = lengthAfter - lengthBefore;
  16785. // determine where we are between the 'before' and 'after' points
  16786. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16787. // add that fractional amount to t
  16788. var t = ( i + segmentFraction ) / ( il -1 );
  16789. return t;
  16790. };
  16791. // Returns a unit vector tangent at t
  16792. // In case any sub curve does not implement its tangent derivation,
  16793. // 2 points a small delta apart will be used to find its gradient
  16794. // which seems to give a reasonable approximation
  16795. THREE.Curve.prototype.getTangent = function( t ) {
  16796. var delta = 0.0001;
  16797. var t1 = t - delta;
  16798. var t2 = t + delta;
  16799. // Capping in case of danger
  16800. if ( t1 < 0 ) t1 = 0;
  16801. if ( t2 > 1 ) t2 = 1;
  16802. var pt1 = this.getPoint( t1 );
  16803. var pt2 = this.getPoint( t2 );
  16804. var vec = pt2.clone().sub(pt1);
  16805. return vec.normalize();
  16806. };
  16807. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16808. var t = this.getUtoTmapping( u );
  16809. return this.getTangent( t );
  16810. };
  16811. /**************************************************************
  16812. * Utils
  16813. **************************************************************/
  16814. THREE.Curve.Utils = {
  16815. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16816. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16817. },
  16818. // Puay Bing, thanks for helping with this derivative!
  16819. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16820. return -3 * p0 * (1 - t) * (1 - t) +
  16821. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  16822. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  16823. 3 * t * t * p3;
  16824. },
  16825. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16826. // To check if my formulas are correct
  16827. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16828. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16829. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  16830. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16831. return h00 + h10 + h01 + h11;
  16832. },
  16833. // Catmull-Rom
  16834. interpolate: function( p0, p1, p2, p3, t ) {
  16835. var v0 = ( p2 - p0 ) * 0.5;
  16836. var v1 = ( p3 - p1 ) * 0.5;
  16837. var t2 = t * t;
  16838. var t3 = t * t2;
  16839. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16840. }
  16841. };
  16842. // TODO: Transformation for Curves?
  16843. /**************************************************************
  16844. * 3D Curves
  16845. **************************************************************/
  16846. // A Factory method for creating new curve subclasses
  16847. THREE.Curve.create = function ( constructor, getPointFunc ) {
  16848. constructor.prototype = Object.create( THREE.Curve.prototype );
  16849. constructor.prototype.getPoint = getPointFunc;
  16850. return constructor;
  16851. };
  16852. /**
  16853. * @author zz85 / http://www.lab4games.net/zz85/blog
  16854. *
  16855. **/
  16856. /**************************************************************
  16857. * Curved Path - a curve path is simply a array of connected
  16858. * curves, but retains the api of a curve
  16859. **************************************************************/
  16860. THREE.CurvePath = function () {
  16861. this.curves = [];
  16862. this.bends = [];
  16863. this.autoClose = false; // Automatically closes the path
  16864. };
  16865. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16866. THREE.CurvePath.prototype.add = function ( curve ) {
  16867. this.curves.push( curve );
  16868. };
  16869. THREE.CurvePath.prototype.checkConnection = function() {
  16870. // TODO
  16871. // If the ending of curve is not connected to the starting
  16872. // or the next curve, then, this is not a real path
  16873. };
  16874. THREE.CurvePath.prototype.closePath = function() {
  16875. // TODO Test
  16876. // and verify for vector3 (needs to implement equals)
  16877. // Add a line curve if start and end of lines are not connected
  16878. var startPoint = this.curves[0].getPoint(0);
  16879. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  16880. if (!startPoint.equals(endPoint)) {
  16881. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16882. }
  16883. };
  16884. // To get accurate point with reference to
  16885. // entire path distance at time t,
  16886. // following has to be done:
  16887. // 1. Length of each sub path have to be known
  16888. // 2. Locate and identify type of curve
  16889. // 3. Get t for the curve
  16890. // 4. Return curve.getPointAt(t')
  16891. THREE.CurvePath.prototype.getPoint = function( t ) {
  16892. var d = t * this.getLength();
  16893. var curveLengths = this.getCurveLengths();
  16894. var i = 0, diff, curve;
  16895. // To think about boundaries points.
  16896. while ( i < curveLengths.length ) {
  16897. if ( curveLengths[ i ] >= d ) {
  16898. diff = curveLengths[ i ] - d;
  16899. curve = this.curves[ i ];
  16900. var u = 1 - diff / curve.getLength();
  16901. return curve.getPointAt( u );
  16902. break;
  16903. }
  16904. i ++;
  16905. }
  16906. return null;
  16907. // loop where sum != 0, sum > d , sum+1 <d
  16908. };
  16909. /*
  16910. THREE.CurvePath.prototype.getTangent = function( t ) {
  16911. };*/
  16912. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16913. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16914. // getPoint() depends on getLength
  16915. THREE.CurvePath.prototype.getLength = function() {
  16916. var lens = this.getCurveLengths();
  16917. return lens[ lens.length - 1 ];
  16918. };
  16919. // Compute lengths and cache them
  16920. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16921. THREE.CurvePath.prototype.getCurveLengths = function() {
  16922. // We use cache values if curves and cache array are same length
  16923. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16924. return this.cacheLengths;
  16925. };
  16926. // Get length of subsurve
  16927. // Push sums into cached array
  16928. var lengths = [], sums = 0;
  16929. var i, il = this.curves.length;
  16930. for ( i = 0; i < il; i ++ ) {
  16931. sums += this.curves[ i ].getLength();
  16932. lengths.push( sums );
  16933. }
  16934. this.cacheLengths = lengths;
  16935. return lengths;
  16936. };
  16937. // Returns min and max coordinates, as well as centroid
  16938. THREE.CurvePath.prototype.getBoundingBox = function () {
  16939. var points = this.getPoints();
  16940. var maxX, maxY, maxZ;
  16941. var minX, minY, minZ;
  16942. maxX = maxY = Number.NEGATIVE_INFINITY;
  16943. minX = minY = Number.POSITIVE_INFINITY;
  16944. var p, i, il, sum;
  16945. var v3 = points[0] instanceof THREE.Vector3;
  16946. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16947. for ( i = 0, il = points.length; i < il; i ++ ) {
  16948. p = points[ i ];
  16949. if ( p.x > maxX ) maxX = p.x;
  16950. else if ( p.x < minX ) minX = p.x;
  16951. if ( p.y > maxY ) maxY = p.y;
  16952. else if ( p.y < minY ) minY = p.y;
  16953. if ( v3 ) {
  16954. if ( p.z > maxZ ) maxZ = p.z;
  16955. else if ( p.z < minZ ) minZ = p.z;
  16956. }
  16957. sum.add( p );
  16958. }
  16959. var ret = {
  16960. minX: minX,
  16961. minY: minY,
  16962. maxX: maxX,
  16963. maxY: maxY,
  16964. centroid: sum.divideScalar( il )
  16965. };
  16966. if ( v3 ) {
  16967. ret.maxZ = maxZ;
  16968. ret.minZ = minZ;
  16969. }
  16970. return ret;
  16971. };
  16972. /**************************************************************
  16973. * Create Geometries Helpers
  16974. **************************************************************/
  16975. /// Generate geometry from path points (for Line or ParticleSystem objects)
  16976. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16977. var pts = this.getPoints( divisions, true );
  16978. return this.createGeometry( pts );
  16979. };
  16980. // Generate geometry from equidistance sampling along the path
  16981. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16982. var pts = this.getSpacedPoints( divisions, true );
  16983. return this.createGeometry( pts );
  16984. };
  16985. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16986. var geometry = new THREE.Geometry();
  16987. for ( var i = 0; i < points.length; i ++ ) {
  16988. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16989. }
  16990. return geometry;
  16991. };
  16992. /**************************************************************
  16993. * Bend / Wrap Helper Methods
  16994. **************************************************************/
  16995. // Wrap path / Bend modifiers?
  16996. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16997. this.bends.push( bendpath );
  16998. };
  16999. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  17000. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  17001. var i, il;
  17002. if ( !bends ) {
  17003. bends = this.bends;
  17004. }
  17005. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17006. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17007. }
  17008. return oldPts;
  17009. };
  17010. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  17011. var oldPts = this.getSpacedPoints( segments );
  17012. var i, il;
  17013. if ( !bends ) {
  17014. bends = this.bends;
  17015. }
  17016. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17017. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17018. }
  17019. return oldPts;
  17020. };
  17021. // This returns getPoints() bend/wrapped around the contour of a path.
  17022. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  17023. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  17024. var bounds = this.getBoundingBox();
  17025. var i, il, p, oldX, oldY, xNorm;
  17026. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  17027. p = oldPts[ i ];
  17028. oldX = p.x;
  17029. oldY = p.y;
  17030. xNorm = oldX / bounds.maxX;
  17031. // If using actual distance, for length > path, requires line extrusions
  17032. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  17033. xNorm = path.getUtoTmapping( xNorm, oldX );
  17034. // check for out of bounds?
  17035. var pathPt = path.getPoint( xNorm );
  17036. var normal = path.getTangent( xNorm );
  17037. normal.set( -normal.y, normal.x ).multiplyScalar( oldY );
  17038. p.x = pathPt.x + normal.x;
  17039. p.y = pathPt.y + normal.y;
  17040. }
  17041. return oldPts;
  17042. };
  17043. /**
  17044. * @author alteredq / http://alteredqualia.com/
  17045. */
  17046. THREE.Gyroscope = function () {
  17047. THREE.Object3D.call( this );
  17048. };
  17049. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  17050. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  17051. this.matrixAutoUpdate && this.updateMatrix();
  17052. // update matrixWorld
  17053. if ( this.matrixWorldNeedsUpdate || force ) {
  17054. if ( this.parent ) {
  17055. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  17056. this.matrixWorld.decompose( this.translationWorld, this.quaternionWorld, this.scaleWorld );
  17057. this.matrix.decompose( this.translationObject, this.quaternionObject, this.scaleObject );
  17058. this.matrixWorld.compose( this.translationWorld, this.quaternionObject, this.scaleWorld );
  17059. } else {
  17060. this.matrixWorld.copy( this.matrix );
  17061. }
  17062. this.matrixWorldNeedsUpdate = false;
  17063. force = true;
  17064. }
  17065. // update children
  17066. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  17067. this.children[ i ].updateMatrixWorld( force );
  17068. }
  17069. };
  17070. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  17071. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  17072. THREE.Gyroscope.prototype.quaternionWorld = new THREE.Quaternion();
  17073. THREE.Gyroscope.prototype.quaternionObject = new THREE.Quaternion();
  17074. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  17075. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  17076. /**
  17077. * @author zz85 / http://www.lab4games.net/zz85/blog
  17078. * Creates free form 2d path using series of points, lines or curves.
  17079. *
  17080. **/
  17081. THREE.Path = function ( points ) {
  17082. THREE.CurvePath.call(this);
  17083. this.actions = [];
  17084. if ( points ) {
  17085. this.fromPoints( points );
  17086. }
  17087. };
  17088. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  17089. THREE.PathActions = {
  17090. MOVE_TO: 'moveTo',
  17091. LINE_TO: 'lineTo',
  17092. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  17093. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  17094. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  17095. ARC: 'arc', // Circle
  17096. ELLIPSE: 'ellipse'
  17097. };
  17098. // TODO Clean up PATH API
  17099. // Create path using straight lines to connect all points
  17100. // - vectors: array of Vector2
  17101. THREE.Path.prototype.fromPoints = function ( vectors ) {
  17102. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  17103. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  17104. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  17105. };
  17106. };
  17107. // startPath() endPath()?
  17108. THREE.Path.prototype.moveTo = function ( x, y ) {
  17109. var args = Array.prototype.slice.call( arguments );
  17110. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  17111. };
  17112. THREE.Path.prototype.lineTo = function ( x, y ) {
  17113. var args = Array.prototype.slice.call( arguments );
  17114. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17115. var x0 = lastargs[ lastargs.length - 2 ];
  17116. var y0 = lastargs[ lastargs.length - 1 ];
  17117. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  17118. this.curves.push( curve );
  17119. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  17120. };
  17121. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  17122. var args = Array.prototype.slice.call( arguments );
  17123. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17124. var x0 = lastargs[ lastargs.length - 2 ];
  17125. var y0 = lastargs[ lastargs.length - 1 ];
  17126. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  17127. new THREE.Vector2( aCPx, aCPy ),
  17128. new THREE.Vector2( aX, aY ) );
  17129. this.curves.push( curve );
  17130. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  17131. };
  17132. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  17133. aCP2x, aCP2y,
  17134. aX, aY ) {
  17135. var args = Array.prototype.slice.call( arguments );
  17136. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17137. var x0 = lastargs[ lastargs.length - 2 ];
  17138. var y0 = lastargs[ lastargs.length - 1 ];
  17139. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  17140. new THREE.Vector2( aCP1x, aCP1y ),
  17141. new THREE.Vector2( aCP2x, aCP2y ),
  17142. new THREE.Vector2( aX, aY ) );
  17143. this.curves.push( curve );
  17144. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  17145. };
  17146. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  17147. var args = Array.prototype.slice.call( arguments );
  17148. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17149. var x0 = lastargs[ lastargs.length - 2 ];
  17150. var y0 = lastargs[ lastargs.length - 1 ];
  17151. //---
  17152. var npts = [ new THREE.Vector2( x0, y0 ) ];
  17153. Array.prototype.push.apply( npts, pts );
  17154. var curve = new THREE.SplineCurve( npts );
  17155. this.curves.push( curve );
  17156. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  17157. };
  17158. // FUTURE: Change the API or follow canvas API?
  17159. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  17160. aStartAngle, aEndAngle, aClockwise ) {
  17161. var lastargs = this.actions[ this.actions.length - 1].args;
  17162. var x0 = lastargs[ lastargs.length - 2 ];
  17163. var y0 = lastargs[ lastargs.length - 1 ];
  17164. this.absarc(aX + x0, aY + y0, aRadius,
  17165. aStartAngle, aEndAngle, aClockwise );
  17166. };
  17167. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  17168. aStartAngle, aEndAngle, aClockwise ) {
  17169. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  17170. };
  17171. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  17172. aStartAngle, aEndAngle, aClockwise ) {
  17173. var lastargs = this.actions[ this.actions.length - 1].args;
  17174. var x0 = lastargs[ lastargs.length - 2 ];
  17175. var y0 = lastargs[ lastargs.length - 1 ];
  17176. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  17177. aStartAngle, aEndAngle, aClockwise );
  17178. };
  17179. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  17180. aStartAngle, aEndAngle, aClockwise ) {
  17181. var args = Array.prototype.slice.call( arguments );
  17182. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  17183. aStartAngle, aEndAngle, aClockwise );
  17184. this.curves.push( curve );
  17185. var lastPoint = curve.getPoint(1);
  17186. args.push(lastPoint.x);
  17187. args.push(lastPoint.y);
  17188. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  17189. };
  17190. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  17191. if ( ! divisions ) divisions = 40;
  17192. var points = [];
  17193. for ( var i = 0; i < divisions; i ++ ) {
  17194. points.push( this.getPoint( i / divisions ) );
  17195. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  17196. }
  17197. // if ( closedPath ) {
  17198. //
  17199. // points.push( points[ 0 ] );
  17200. //
  17201. // }
  17202. return points;
  17203. };
  17204. /* Return an array of vectors based on contour of the path */
  17205. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  17206. if (this.useSpacedPoints) {
  17207. console.log('tata');
  17208. return this.getSpacedPoints( divisions, closedPath );
  17209. }
  17210. divisions = divisions || 12;
  17211. var points = [];
  17212. var i, il, item, action, args;
  17213. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  17214. laste, j,
  17215. t, tx, ty;
  17216. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17217. item = this.actions[ i ];
  17218. action = item.action;
  17219. args = item.args;
  17220. switch( action ) {
  17221. case THREE.PathActions.MOVE_TO:
  17222. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17223. break;
  17224. case THREE.PathActions.LINE_TO:
  17225. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17226. break;
  17227. case THREE.PathActions.QUADRATIC_CURVE_TO:
  17228. cpx = args[ 2 ];
  17229. cpy = args[ 3 ];
  17230. cpx1 = args[ 0 ];
  17231. cpy1 = args[ 1 ];
  17232. if ( points.length > 0 ) {
  17233. laste = points[ points.length - 1 ];
  17234. cpx0 = laste.x;
  17235. cpy0 = laste.y;
  17236. } else {
  17237. laste = this.actions[ i - 1 ].args;
  17238. cpx0 = laste[ laste.length - 2 ];
  17239. cpy0 = laste[ laste.length - 1 ];
  17240. }
  17241. for ( j = 1; j <= divisions; j ++ ) {
  17242. t = j / divisions;
  17243. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17244. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17245. points.push( new THREE.Vector2( tx, ty ) );
  17246. }
  17247. break;
  17248. case THREE.PathActions.BEZIER_CURVE_TO:
  17249. cpx = args[ 4 ];
  17250. cpy = args[ 5 ];
  17251. cpx1 = args[ 0 ];
  17252. cpy1 = args[ 1 ];
  17253. cpx2 = args[ 2 ];
  17254. cpy2 = args[ 3 ];
  17255. if ( points.length > 0 ) {
  17256. laste = points[ points.length - 1 ];
  17257. cpx0 = laste.x;
  17258. cpy0 = laste.y;
  17259. } else {
  17260. laste = this.actions[ i - 1 ].args;
  17261. cpx0 = laste[ laste.length - 2 ];
  17262. cpy0 = laste[ laste.length - 1 ];
  17263. }
  17264. for ( j = 1; j <= divisions; j ++ ) {
  17265. t = j / divisions;
  17266. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17267. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17268. points.push( new THREE.Vector2( tx, ty ) );
  17269. }
  17270. break;
  17271. case THREE.PathActions.CSPLINE_THRU:
  17272. laste = this.actions[ i - 1 ].args;
  17273. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17274. var spts = [ last ];
  17275. var n = divisions * args[ 0 ].length;
  17276. spts = spts.concat( args[ 0 ] );
  17277. var spline = new THREE.SplineCurve( spts );
  17278. for ( j = 1; j <= n; j ++ ) {
  17279. points.push( spline.getPointAt( j / n ) ) ;
  17280. }
  17281. break;
  17282. case THREE.PathActions.ARC:
  17283. var aX = args[ 0 ], aY = args[ 1 ],
  17284. aRadius = args[ 2 ],
  17285. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17286. aClockwise = !!args[ 5 ];
  17287. var deltaAngle = aEndAngle - aStartAngle;
  17288. var angle;
  17289. var tdivisions = divisions * 2;
  17290. for ( j = 1; j <= tdivisions; j ++ ) {
  17291. t = j / tdivisions;
  17292. if ( ! aClockwise ) {
  17293. t = 1 - t;
  17294. }
  17295. angle = aStartAngle + t * deltaAngle;
  17296. tx = aX + aRadius * Math.cos( angle );
  17297. ty = aY + aRadius * Math.sin( angle );
  17298. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17299. points.push( new THREE.Vector2( tx, ty ) );
  17300. }
  17301. //console.log(points);
  17302. break;
  17303. case THREE.PathActions.ELLIPSE:
  17304. var aX = args[ 0 ], aY = args[ 1 ],
  17305. xRadius = args[ 2 ],
  17306. yRadius = args[ 3 ],
  17307. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17308. aClockwise = !!args[ 6 ];
  17309. var deltaAngle = aEndAngle - aStartAngle;
  17310. var angle;
  17311. var tdivisions = divisions * 2;
  17312. for ( j = 1; j <= tdivisions; j ++ ) {
  17313. t = j / tdivisions;
  17314. if ( ! aClockwise ) {
  17315. t = 1 - t;
  17316. }
  17317. angle = aStartAngle + t * deltaAngle;
  17318. tx = aX + xRadius * Math.cos( angle );
  17319. ty = aY + yRadius * Math.sin( angle );
  17320. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17321. points.push( new THREE.Vector2( tx, ty ) );
  17322. }
  17323. //console.log(points);
  17324. break;
  17325. } // end switch
  17326. }
  17327. // Normalize to remove the closing point by default.
  17328. var lastPoint = points[ points.length - 1];
  17329. var EPSILON = 0.0000000001;
  17330. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17331. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17332. points.splice( points.length - 1, 1);
  17333. if ( closedPath ) {
  17334. points.push( points[ 0 ] );
  17335. }
  17336. return points;
  17337. };
  17338. // Breaks path into shapes
  17339. THREE.Path.prototype.toShapes = function( isCCW ) {
  17340. var i, il, item, action, args;
  17341. var subPaths = [], lastPath = new THREE.Path();
  17342. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17343. item = this.actions[ i ];
  17344. args = item.args;
  17345. action = item.action;
  17346. if ( action == THREE.PathActions.MOVE_TO ) {
  17347. if ( lastPath.actions.length != 0 ) {
  17348. subPaths.push( lastPath );
  17349. lastPath = new THREE.Path();
  17350. }
  17351. }
  17352. lastPath[ action ].apply( lastPath, args );
  17353. }
  17354. if ( lastPath.actions.length != 0 ) {
  17355. subPaths.push( lastPath );
  17356. }
  17357. // console.log(subPaths);
  17358. if ( subPaths.length == 0 ) return [];
  17359. var solid, tmpPath, tmpShape, shapes = [];
  17360. if ( subPaths.length == 1) {
  17361. tmpPath = subPaths[0];
  17362. tmpShape = new THREE.Shape();
  17363. tmpShape.actions = tmpPath.actions;
  17364. tmpShape.curves = tmpPath.curves;
  17365. shapes.push( tmpShape );
  17366. return shapes;
  17367. }
  17368. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17369. holesFirst = isCCW ? !holesFirst : holesFirst;
  17370. // console.log("Holes first", holesFirst);
  17371. if ( holesFirst ) {
  17372. tmpShape = new THREE.Shape();
  17373. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17374. tmpPath = subPaths[ i ];
  17375. solid = THREE.Shape.Utils.isClockWise( tmpPath.getPoints() );
  17376. solid = isCCW ? !solid : solid;
  17377. if ( solid ) {
  17378. tmpShape.actions = tmpPath.actions;
  17379. tmpShape.curves = tmpPath.curves;
  17380. shapes.push( tmpShape );
  17381. tmpShape = new THREE.Shape();
  17382. //console.log('cw', i);
  17383. } else {
  17384. tmpShape.holes.push( tmpPath );
  17385. //console.log('ccw', i);
  17386. }
  17387. }
  17388. } else {
  17389. // Shapes first
  17390. tmpShape = undefined;
  17391. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17392. tmpPath = subPaths[ i ];
  17393. solid = THREE.Shape.Utils.isClockWise( tmpPath.getPoints() );
  17394. solid = isCCW ? !solid : solid;
  17395. if ( solid ) {
  17396. if ( tmpShape ) shapes.push( tmpShape );
  17397. tmpShape = new THREE.Shape();
  17398. tmpShape.actions = tmpPath.actions;
  17399. tmpShape.curves = tmpPath.curves;
  17400. } else {
  17401. tmpShape.holes.push( tmpPath );
  17402. }
  17403. }
  17404. shapes.push( tmpShape );
  17405. }
  17406. //console.log("shape", shapes);
  17407. return shapes;
  17408. };
  17409. /**
  17410. * @author zz85 / http://www.lab4games.net/zz85/blog
  17411. * Defines a 2d shape plane using paths.
  17412. **/
  17413. // STEP 1 Create a path.
  17414. // STEP 2 Turn path into shape.
  17415. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17416. // STEP 3a - Extract points from each shape, turn to vertices
  17417. // STEP 3b - Triangulate each shape, add faces.
  17418. THREE.Shape = function () {
  17419. THREE.Path.apply( this, arguments );
  17420. this.holes = [];
  17421. };
  17422. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17423. // Convenience method to return ExtrudeGeometry
  17424. THREE.Shape.prototype.extrude = function ( options ) {
  17425. var extruded = new THREE.ExtrudeGeometry( this, options );
  17426. return extruded;
  17427. };
  17428. // Convenience method to return ShapeGeometry
  17429. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17430. var geometry = new THREE.ShapeGeometry( this, options );
  17431. return geometry;
  17432. };
  17433. // Get points of holes
  17434. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17435. var i, il = this.holes.length, holesPts = [];
  17436. for ( i = 0; i < il; i ++ ) {
  17437. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17438. }
  17439. return holesPts;
  17440. };
  17441. // Get points of holes (spaced by regular distance)
  17442. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17443. var i, il = this.holes.length, holesPts = [];
  17444. for ( i = 0; i < il; i ++ ) {
  17445. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17446. }
  17447. return holesPts;
  17448. };
  17449. // Get points of shape and holes (keypoints based on segments parameter)
  17450. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17451. return {
  17452. shape: this.getTransformedPoints( divisions ),
  17453. holes: this.getPointsHoles( divisions )
  17454. };
  17455. };
  17456. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17457. if (this.useSpacedPoints) {
  17458. return this.extractAllSpacedPoints(divisions);
  17459. }
  17460. return this.extractAllPoints(divisions);
  17461. };
  17462. //
  17463. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17464. //
  17465. // return {
  17466. //
  17467. // shape: this.transform( bend, divisions ),
  17468. // holes: this.getPointsHoles( divisions, bend )
  17469. //
  17470. // };
  17471. //
  17472. // };
  17473. // Get points of shape and holes (spaced by regular distance)
  17474. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17475. return {
  17476. shape: this.getTransformedSpacedPoints( divisions ),
  17477. holes: this.getSpacedPointsHoles( divisions )
  17478. };
  17479. };
  17480. /**************************************************************
  17481. * Utils
  17482. **************************************************************/
  17483. THREE.Shape.Utils = {
  17484. triangulateShape: function ( contour, holes ) {
  17485. function point_in_segment_2D( inSegPt1, inSegPt2, inOtherPt ) {
  17486. // inOtherPt needs to be colinear to the inSegment
  17487. if ( inSegPt1.x != inSegPt2.x ) {
  17488. if ( inSegPt1.x < inSegPt2.x ) {
  17489. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  17490. } else {
  17491. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  17492. }
  17493. } else {
  17494. if ( inSegPt1.y < inSegPt2.y ) {
  17495. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  17496. } else {
  17497. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  17498. }
  17499. }
  17500. }
  17501. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  17502. var EPSILON = 0.0000000001;
  17503. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  17504. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  17505. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  17506. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  17507. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  17508. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  17509. if ( Math.abs(limit) > EPSILON ) { // not parallel
  17510. var perpSeg2;
  17511. if ( limit > 0 ) {
  17512. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  17513. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17514. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  17515. } else {
  17516. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  17517. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  17518. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  17519. }
  17520. // intersection at endpoint ?
  17521. if ( perpSeg2 == 0 ) {
  17522. if ( ( inExcludeAdjacentSegs ) &&
  17523. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  17524. return [ inSeg1Pt1 ];
  17525. }
  17526. if ( perpSeg2 == limit ) {
  17527. if ( ( inExcludeAdjacentSegs ) &&
  17528. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  17529. return [ inSeg1Pt2 ];
  17530. }
  17531. // return real intersection point
  17532. var factorSeg1 = perpSeg2 / limit;
  17533. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  17534. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  17535. } else { // parallel or colinear
  17536. if ( perpSeg1 != 0 ) return [];
  17537. // they are collinear or degenerate
  17538. var seg1Pt = ( (seg1dx == 0) && (seg1dy == 0) ); // segment1 ist just a point?
  17539. var seg2Pt = ( (seg2dx == 0) && (seg2dy == 0) ); // segment2 ist just a point?
  17540. // both segments are points
  17541. if ( seg1Pt && seg2Pt ) {
  17542. if ( (inSeg1Pt1.x != inSeg2Pt1.x) ||
  17543. (inSeg1Pt1.y != inSeg2Pt1.y) ) return []; // they are distinct points
  17544. return [ inSeg1Pt1 ]; // they are the same point
  17545. }
  17546. // segment#1 is a single point
  17547. if ( seg1Pt ) {
  17548. if (! point_in_segment_2D( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  17549. return [ inSeg1Pt1 ];
  17550. }
  17551. // segment#2 is a single point
  17552. if ( seg2Pt ) {
  17553. if (! point_in_segment_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  17554. return [ inSeg2Pt1 ];
  17555. }
  17556. // they are collinear segments, which might overlap
  17557. var seg1min, seg1max, seg1minVal, seg1maxVal;
  17558. var seg2min, seg2max, seg2minVal, seg2maxVal;
  17559. if (seg1dx != 0) { // the segments are NOT on a vertical line
  17560. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  17561. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  17562. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  17563. } else {
  17564. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  17565. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  17566. }
  17567. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  17568. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  17569. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  17570. } else {
  17571. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  17572. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  17573. }
  17574. } else { // the segments are on a vertical line
  17575. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  17576. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  17577. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  17578. } else {
  17579. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  17580. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  17581. }
  17582. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  17583. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  17584. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  17585. } else {
  17586. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  17587. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  17588. }
  17589. }
  17590. if ( seg1minVal <= seg2minVal ) {
  17591. if ( seg1maxVal < seg2minVal ) return [];
  17592. if ( seg1maxVal == seg2minVal ) {
  17593. if ( inExcludeAdjacentSegs ) return [];
  17594. return [ seg2min ];
  17595. }
  17596. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  17597. return [ seg2min, seg2max ];
  17598. } else {
  17599. if ( seg1minVal > seg2maxVal ) return [];
  17600. if ( seg1minVal == seg2maxVal ) {
  17601. if ( inExcludeAdjacentSegs ) return [];
  17602. return [ seg1min ];
  17603. }
  17604. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  17605. return [ seg1min, seg2max ];
  17606. }
  17607. }
  17608. }
  17609. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  17610. // The order of legs is important
  17611. var EPSILON = 0.0000000001;
  17612. // translation of all points, so that Vertex is at (0,0)
  17613. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  17614. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  17615. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  17616. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  17617. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  17618. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  17619. if ( Math.abs(from2toAngle) > EPSILON ) { // angle != 180 deg.
  17620. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  17621. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  17622. if ( from2toAngle > 0 ) { // main angle < 180 deg.
  17623. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  17624. } else { // main angle > 180 deg.
  17625. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  17626. }
  17627. } else { // angle == 180 deg.
  17628. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  17629. return ( from2otherAngle > 0 );
  17630. }
  17631. }
  17632. function removeHoles( contour, holes ) {
  17633. var shape = contour.concat(); // work on this shape
  17634. var hole;
  17635. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  17636. // Check if hole point lies within angle around shape point
  17637. var lastShapeIdx = shape.length - 1;
  17638. var prevShapeIdx = inShapeIdx - 1;
  17639. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  17640. var nextShapeIdx = inShapeIdx + 1;
  17641. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  17642. var insideAngle = isPointInsideAngle( shape[inShapeIdx], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[inHoleIdx] );
  17643. if (! insideAngle ) {
  17644. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  17645. return false;
  17646. }
  17647. // Check if shape point lies within angle around hole point
  17648. var lastHoleIdx = hole.length - 1;
  17649. var prevHoleIdx = inHoleIdx - 1;
  17650. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  17651. var nextHoleIdx = inHoleIdx + 1;
  17652. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  17653. insideAngle = isPointInsideAngle( hole[inHoleIdx], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[inShapeIdx] );
  17654. if (! insideAngle ) {
  17655. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  17656. return false;
  17657. }
  17658. return true;
  17659. }
  17660. function intersectsShapeEdge( inShapePt, inHolePt ) {
  17661. // checks for intersections with shape edges
  17662. var sIdx, nextIdx, intersection;
  17663. for ( sIdx = 0; sIdx < shape.length; sIdx++ ) {
  17664. nextIdx = sIdx+1; nextIdx %= shape.length;
  17665. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[sIdx], shape[nextIdx], true );
  17666. if ( intersection.length > 0 ) return true;
  17667. }
  17668. return false;
  17669. }
  17670. var indepHoles = [];
  17671. function intersectsHoleEdge( inShapePt, inHolePt ) {
  17672. // checks for intersections with hole edges
  17673. var ihIdx, chkHole,
  17674. hIdx, nextIdx, intersection;
  17675. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx++ ) {
  17676. chkHole = holes[indepHoles[ihIdx]];
  17677. for ( hIdx = 0; hIdx < chkHole.length; hIdx++ ) {
  17678. nextIdx = hIdx+1; nextIdx %= chkHole.length;
  17679. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[hIdx], chkHole[nextIdx], true );
  17680. if ( intersection.length > 0 ) return true;
  17681. }
  17682. }
  17683. return false;
  17684. }
  17685. var holeIndex, shapeIndex,
  17686. shapePt, h, h2, holePt,
  17687. holeIdx, cutKey, failedCuts = [],
  17688. tmpShape1, tmpShape2,
  17689. tmpHole1, tmpHole2;
  17690. for (h in holes) { indepHoles.push( h ); }
  17691. var counter = indepHoles.length * 2;
  17692. while ( indepHoles.length > 0 ) {
  17693. counter --;
  17694. if ( counter < 0 ) {
  17695. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  17696. break;
  17697. }
  17698. // search for shape-vertex and hole-vertex,
  17699. // which can be connected without intersections
  17700. for ( shapeIndex = 0; shapeIndex < shape.length; shapeIndex++ ) {
  17701. shapePt = shape[ shapeIndex ];
  17702. holeIndex = -1;
  17703. // search for hole which can be reached without intersections
  17704. for ( h = 0; h < indepHoles.length; h++ ) {
  17705. holeIdx = indepHoles[h];
  17706. // prevent multiple checks
  17707. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  17708. if ( failedCuts[cutKey] !== undefined ) continue;
  17709. hole = holes[holeIdx];
  17710. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  17711. holePt = hole[ h2 ];
  17712. if (! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  17713. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  17714. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  17715. holeIndex = h2;
  17716. indepHoles.splice(h,1);
  17717. tmpShape1 = shape.slice( 0, shapeIndex+1 );
  17718. tmpShape2 = shape.slice( shapeIndex );
  17719. tmpHole1 = hole.slice( holeIndex );
  17720. tmpHole2 = hole.slice( 0, holeIndex+1 );
  17721. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17722. // Debug only, to show the selected cuts
  17723. // glob_CutLines.push( [ shapePt, holePt ] );
  17724. break;
  17725. }
  17726. if ( holeIndex >= 0 ) break; // hole-vertex found
  17727. failedCuts[cutKey] = true; // remember failure
  17728. }
  17729. if ( holeIndex >= 0 ) break; // hole-vertex found
  17730. }
  17731. }
  17732. return shape; /* shape with no holes */
  17733. }
  17734. var i, il, f, face,
  17735. key, index,
  17736. allPointsMap = {};
  17737. // 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.
  17738. var allpoints = contour.concat();
  17739. for (var h in holes) { Array.prototype.push.apply( allpoints, holes[h] ); }
  17740. //console.log( "allpoints",allpoints, allpoints.length );
  17741. // prepare all points map
  17742. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17743. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17744. if ( allPointsMap[ key ] !== undefined ) {
  17745. console.log( "Duplicate point", key );
  17746. }
  17747. allPointsMap[ key ] = i;
  17748. }
  17749. // remove holes by cutting paths to holes and adding them to the shape
  17750. var shapeWithoutHoles = removeHoles( contour, holes );
  17751. var triangles = THREE.FontUtils.Triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  17752. //console.log( "triangles",triangles, triangles.length );
  17753. // check all face vertices against all points map
  17754. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17755. face = triangles[ i ];
  17756. for ( f = 0; f < 3; f ++ ) {
  17757. key = face[ f ].x + ":" + face[ f ].y;
  17758. index = allPointsMap[ key ];
  17759. if ( index !== undefined ) {
  17760. face[ f ] = index;
  17761. }
  17762. }
  17763. }
  17764. return triangles.concat();
  17765. },
  17766. isClockWise: function ( pts ) {
  17767. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17768. },
  17769. // Bezier Curves formulas obtained from
  17770. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17771. // Quad Bezier Functions
  17772. b2p0: function ( t, p ) {
  17773. var k = 1 - t;
  17774. return k * k * p;
  17775. },
  17776. b2p1: function ( t, p ) {
  17777. return 2 * ( 1 - t ) * t * p;
  17778. },
  17779. b2p2: function ( t, p ) {
  17780. return t * t * p;
  17781. },
  17782. b2: function ( t, p0, p1, p2 ) {
  17783. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17784. },
  17785. // Cubic Bezier Functions
  17786. b3p0: function ( t, p ) {
  17787. var k = 1 - t;
  17788. return k * k * k * p;
  17789. },
  17790. b3p1: function ( t, p ) {
  17791. var k = 1 - t;
  17792. return 3 * k * k * t * p;
  17793. },
  17794. b3p2: function ( t, p ) {
  17795. var k = 1 - t;
  17796. return 3 * k * t * t * p;
  17797. },
  17798. b3p3: function ( t, p ) {
  17799. return t * t * t * p;
  17800. },
  17801. b3: function ( t, p0, p1, p2, p3 ) {
  17802. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17803. }
  17804. };
  17805. /**************************************************************
  17806. * Line
  17807. **************************************************************/
  17808. THREE.LineCurve = function ( v1, v2 ) {
  17809. this.v1 = v1;
  17810. this.v2 = v2;
  17811. };
  17812. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  17813. THREE.LineCurve.prototype.getPoint = function ( t ) {
  17814. var point = this.v2.clone().sub(this.v1);
  17815. point.multiplyScalar( t ).add( this.v1 );
  17816. return point;
  17817. };
  17818. // Line curve is linear, so we can overwrite default getPointAt
  17819. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  17820. return this.getPoint( u );
  17821. };
  17822. THREE.LineCurve.prototype.getTangent = function( t ) {
  17823. var tangent = this.v2.clone().sub(this.v1);
  17824. return tangent.normalize();
  17825. };
  17826. /**************************************************************
  17827. * Quadratic Bezier curve
  17828. **************************************************************/
  17829. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  17830. this.v0 = v0;
  17831. this.v1 = v1;
  17832. this.v2 = v2;
  17833. };
  17834. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17835. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  17836. var tx, ty;
  17837. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17838. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17839. return new THREE.Vector2( tx, ty );
  17840. };
  17841. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  17842. var tx, ty;
  17843. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  17844. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  17845. // returns unit vector
  17846. var tangent = new THREE.Vector2( tx, ty );
  17847. tangent.normalize();
  17848. return tangent;
  17849. };
  17850. /**************************************************************
  17851. * Cubic Bezier curve
  17852. **************************************************************/
  17853. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  17854. this.v0 = v0;
  17855. this.v1 = v1;
  17856. this.v2 = v2;
  17857. this.v3 = v3;
  17858. };
  17859. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17860. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  17861. var tx, ty;
  17862. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17863. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17864. return new THREE.Vector2( tx, ty );
  17865. };
  17866. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  17867. var tx, ty;
  17868. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17869. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17870. var tangent = new THREE.Vector2( tx, ty );
  17871. tangent.normalize();
  17872. return tangent;
  17873. };
  17874. /**************************************************************
  17875. * Spline curve
  17876. **************************************************************/
  17877. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  17878. this.points = (points == undefined) ? [] : points;
  17879. };
  17880. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  17881. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  17882. var v = new THREE.Vector2();
  17883. var c = [];
  17884. var points = this.points, point, intPoint, weight;
  17885. point = ( points.length - 1 ) * t;
  17886. intPoint = Math.floor( point );
  17887. weight = point - intPoint;
  17888. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17889. c[ 1 ] = intPoint;
  17890. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  17891. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  17892. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  17893. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  17894. return v;
  17895. };
  17896. /**************************************************************
  17897. * Ellipse curve
  17898. **************************************************************/
  17899. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise ) {
  17900. this.aX = aX;
  17901. this.aY = aY;
  17902. this.xRadius = xRadius;
  17903. this.yRadius = yRadius;
  17904. this.aStartAngle = aStartAngle;
  17905. this.aEndAngle = aEndAngle;
  17906. this.aClockwise = aClockwise;
  17907. };
  17908. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  17909. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  17910. var angle;
  17911. var deltaAngle = this.aEndAngle - this.aStartAngle;
  17912. if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2;
  17913. if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2;
  17914. if ( this.aClockwise === true ) {
  17915. angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle );
  17916. } else {
  17917. angle = this.aStartAngle + t * deltaAngle;
  17918. }
  17919. var tx = this.aX + this.xRadius * Math.cos( angle );
  17920. var ty = this.aY + this.yRadius * Math.sin( angle );
  17921. return new THREE.Vector2( tx, ty );
  17922. };
  17923. /**************************************************************
  17924. * Arc curve
  17925. **************************************************************/
  17926. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  17927. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  17928. };
  17929. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  17930. /**************************************************************
  17931. * Line3D
  17932. **************************************************************/
  17933. THREE.LineCurve3 = THREE.Curve.create(
  17934. function ( v1, v2 ) {
  17935. this.v1 = v1;
  17936. this.v2 = v2;
  17937. },
  17938. function ( t ) {
  17939. var r = new THREE.Vector3();
  17940. r.subVectors( this.v2, this.v1 ); // diff
  17941. r.multiplyScalar( t );
  17942. r.add( this.v1 );
  17943. return r;
  17944. }
  17945. );
  17946. /**************************************************************
  17947. * Quadratic Bezier 3D curve
  17948. **************************************************************/
  17949. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  17950. function ( v0, v1, v2 ) {
  17951. this.v0 = v0;
  17952. this.v1 = v1;
  17953. this.v2 = v2;
  17954. },
  17955. function ( t ) {
  17956. var tx, ty, tz;
  17957. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17958. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17959. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  17960. return new THREE.Vector3( tx, ty, tz );
  17961. }
  17962. );
  17963. /**************************************************************
  17964. * Cubic Bezier 3D curve
  17965. **************************************************************/
  17966. THREE.CubicBezierCurve3 = THREE.Curve.create(
  17967. function ( v0, v1, v2, v3 ) {
  17968. this.v0 = v0;
  17969. this.v1 = v1;
  17970. this.v2 = v2;
  17971. this.v3 = v3;
  17972. },
  17973. function ( t ) {
  17974. var tx, ty, tz;
  17975. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17976. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17977. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  17978. return new THREE.Vector3( tx, ty, tz );
  17979. }
  17980. );
  17981. /**************************************************************
  17982. * Spline 3D curve
  17983. **************************************************************/
  17984. THREE.SplineCurve3 = THREE.Curve.create(
  17985. function ( points /* array of Vector3 */) {
  17986. this.points = (points == undefined) ? [] : points;
  17987. },
  17988. function ( t ) {
  17989. var v = new THREE.Vector3();
  17990. var c = [];
  17991. var points = this.points, point, intPoint, weight;
  17992. point = ( points.length - 1 ) * t;
  17993. intPoint = Math.floor( point );
  17994. weight = point - intPoint;
  17995. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  17996. c[ 1 ] = intPoint;
  17997. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  17998. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  17999. var pt0 = points[ c[0] ],
  18000. pt1 = points[ c[1] ],
  18001. pt2 = points[ c[2] ],
  18002. pt3 = points[ c[3] ];
  18003. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  18004. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  18005. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  18006. return v;
  18007. }
  18008. );
  18009. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  18010. // var v = new THREE.Vector3();
  18011. // var c = [];
  18012. // var points = this.points, point, intPoint, weight;
  18013. // point = ( points.length - 1 ) * t;
  18014. // intPoint = Math.floor( point );
  18015. // weight = point - intPoint;
  18016. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18017. // c[ 1 ] = intPoint;
  18018. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  18019. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  18020. // var pt0 = points[ c[0] ],
  18021. // pt1 = points[ c[1] ],
  18022. // pt2 = points[ c[2] ],
  18023. // pt3 = points[ c[3] ];
  18024. // // t = weight;
  18025. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  18026. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  18027. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  18028. // return v;
  18029. // }
  18030. /**************************************************************
  18031. * Closed Spline 3D curve
  18032. **************************************************************/
  18033. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  18034. function ( points /* array of Vector3 */) {
  18035. this.points = (points == undefined) ? [] : points;
  18036. },
  18037. function ( t ) {
  18038. var v = new THREE.Vector3();
  18039. var c = [];
  18040. var points = this.points, point, intPoint, weight;
  18041. point = ( points.length - 0 ) * t;
  18042. // This needs to be from 0-length +1
  18043. intPoint = Math.floor( point );
  18044. weight = point - intPoint;
  18045. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  18046. c[ 0 ] = ( intPoint - 1 ) % points.length;
  18047. c[ 1 ] = ( intPoint ) % points.length;
  18048. c[ 2 ] = ( intPoint + 1 ) % points.length;
  18049. c[ 3 ] = ( intPoint + 2 ) % points.length;
  18050. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  18051. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  18052. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  18053. return v;
  18054. }
  18055. );
  18056. /**
  18057. * @author mikael emtinger / http://gomo.se/
  18058. */
  18059. THREE.AnimationHandler = (function() {
  18060. var playing = [];
  18061. var library = {};
  18062. var that = {};
  18063. //--- update ---
  18064. that.update = function( deltaTimeMS ) {
  18065. for( var i = 0; i < playing.length; i ++ )
  18066. playing[ i ].update( deltaTimeMS );
  18067. };
  18068. //--- add ---
  18069. that.addToUpdate = function( animation ) {
  18070. if ( playing.indexOf( animation ) === -1 )
  18071. playing.push( animation );
  18072. };
  18073. //--- remove ---
  18074. that.removeFromUpdate = function( animation ) {
  18075. var index = playing.indexOf( animation );
  18076. if( index !== -1 )
  18077. playing.splice( index, 1 );
  18078. };
  18079. //--- add ---
  18080. that.add = function( data ) {
  18081. if ( library[ data.name ] !== undefined )
  18082. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  18083. library[ data.name ] = data;
  18084. initData( data );
  18085. };
  18086. //--- get ---
  18087. that.get = function( name ) {
  18088. if ( typeof name === "string" ) {
  18089. if ( library[ name ] ) {
  18090. return library[ name ];
  18091. } else {
  18092. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  18093. return null;
  18094. }
  18095. } else {
  18096. // todo: add simple tween library
  18097. }
  18098. };
  18099. //--- parse ---
  18100. that.parse = function( root ) {
  18101. // setup hierarchy
  18102. var hierarchy = [];
  18103. if ( root instanceof THREE.SkinnedMesh ) {
  18104. for( var b = 0; b < root.bones.length; b++ ) {
  18105. hierarchy.push( root.bones[ b ] );
  18106. }
  18107. } else {
  18108. parseRecurseHierarchy( root, hierarchy );
  18109. }
  18110. return hierarchy;
  18111. };
  18112. var parseRecurseHierarchy = function( root, hierarchy ) {
  18113. hierarchy.push( root );
  18114. for( var c = 0; c < root.children.length; c++ )
  18115. parseRecurseHierarchy( root.children[ c ], hierarchy );
  18116. }
  18117. //--- init data ---
  18118. var initData = function( data ) {
  18119. if( data.initialized === true )
  18120. return;
  18121. // loop through all keys
  18122. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  18123. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18124. // remove minus times
  18125. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  18126. data.hierarchy[ h ].keys[ k ].time = 0;
  18127. // create quaternions
  18128. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  18129. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  18130. var quat = data.hierarchy[ h ].keys[ k ].rot;
  18131. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  18132. }
  18133. }
  18134. // prepare morph target keys
  18135. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  18136. // get all used
  18137. var usedMorphTargets = {};
  18138. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18139. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18140. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  18141. usedMorphTargets[ morphTargetName ] = -1;
  18142. }
  18143. }
  18144. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  18145. // set all used on all frames
  18146. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18147. var influences = {};
  18148. for ( var morphTargetName in usedMorphTargets ) {
  18149. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18150. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  18151. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  18152. break;
  18153. }
  18154. }
  18155. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  18156. influences[ morphTargetName ] = 0;
  18157. }
  18158. }
  18159. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  18160. }
  18161. }
  18162. // remove all keys that are on the same time
  18163. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18164. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  18165. data.hierarchy[ h ].keys.splice( k, 1 );
  18166. k --;
  18167. }
  18168. }
  18169. // set index
  18170. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18171. data.hierarchy[ h ].keys[ k ].index = k;
  18172. }
  18173. }
  18174. // JIT
  18175. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  18176. data.JIT = {};
  18177. data.JIT.hierarchy = [];
  18178. for( var h = 0; h < data.hierarchy.length; h ++ )
  18179. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  18180. // done
  18181. data.initialized = true;
  18182. };
  18183. // interpolation types
  18184. that.LINEAR = 0;
  18185. that.CATMULLROM = 1;
  18186. that.CATMULLROM_FORWARD = 2;
  18187. return that;
  18188. }());
  18189. /**
  18190. * @author mikael emtinger / http://gomo.se/
  18191. * @author mrdoob / http://mrdoob.com/
  18192. * @author alteredq / http://alteredqualia.com/
  18193. */
  18194. THREE.Animation = function ( root, name, interpolationType ) {
  18195. this.root = root;
  18196. this.data = THREE.AnimationHandler.get( name );
  18197. this.hierarchy = THREE.AnimationHandler.parse( root );
  18198. this.currentTime = 0;
  18199. this.timeScale = 1;
  18200. this.isPlaying = false;
  18201. this.isPaused = true;
  18202. this.loop = true;
  18203. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  18204. this.points = [];
  18205. this.target = new THREE.Vector3();
  18206. };
  18207. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  18208. if ( this.isPlaying === false ) {
  18209. this.isPlaying = true;
  18210. this.loop = loop !== undefined ? loop : true;
  18211. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  18212. // reset key cache
  18213. var h, hl = this.hierarchy.length,
  18214. object;
  18215. for ( h = 0; h < hl; h ++ ) {
  18216. object = this.hierarchy[ h ];
  18217. object.matrixAutoUpdate = true;
  18218. if ( object.animationCache === undefined ) {
  18219. object.animationCache = {};
  18220. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  18221. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  18222. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18223. }
  18224. var prevKey = object.animationCache.prevKey;
  18225. var nextKey = object.animationCache.nextKey;
  18226. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  18227. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  18228. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  18229. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  18230. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  18231. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  18232. }
  18233. this.update( 0 );
  18234. }
  18235. this.isPaused = false;
  18236. THREE.AnimationHandler.addToUpdate( this );
  18237. };
  18238. THREE.Animation.prototype.pause = function() {
  18239. if ( this.isPaused === true ) {
  18240. THREE.AnimationHandler.addToUpdate( this );
  18241. } else {
  18242. THREE.AnimationHandler.removeFromUpdate( this );
  18243. }
  18244. this.isPaused = !this.isPaused;
  18245. };
  18246. THREE.Animation.prototype.stop = function() {
  18247. this.isPlaying = false;
  18248. this.isPaused = false;
  18249. THREE.AnimationHandler.removeFromUpdate( this );
  18250. };
  18251. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  18252. // early out
  18253. if ( this.isPlaying === false ) return;
  18254. // vars
  18255. var types = [ "pos", "rot", "scl" ];
  18256. var type;
  18257. var scale;
  18258. var vector;
  18259. var prevXYZ, nextXYZ;
  18260. var prevKey, nextKey;
  18261. var object;
  18262. var animationCache;
  18263. var frame;
  18264. var JIThierarchy = this.data.JIT.hierarchy;
  18265. var currentTime, unloopedCurrentTime;
  18266. var currentPoint, forwardPoint, angle;
  18267. this.currentTime += deltaTimeMS * this.timeScale;
  18268. unloopedCurrentTime = this.currentTime;
  18269. // Mod operation fails on floats
  18270. // was this supposed to be in frames?
  18271. while ( this.currentTime > this.data.length ) {
  18272. this.currentTime -= this.data.length;
  18273. }
  18274. currentTime = this.currentTime = this.currentTime % this.data.length;
  18275. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18276. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18277. object = this.hierarchy[ h ];
  18278. animationCache = object.animationCache;
  18279. // loop through pos/rot/scl
  18280. for ( var t = 0; t < 3; t ++ ) {
  18281. // get keys
  18282. type = types[ t ];
  18283. prevKey = animationCache.prevKey[ type ];
  18284. nextKey = animationCache.nextKey[ type ];
  18285. // switch keys?
  18286. if ( nextKey.time <= unloopedCurrentTime ) {
  18287. // did we loop?
  18288. if ( currentTime <= unloopedCurrentTime ) {
  18289. if ( this.loop ) {
  18290. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  18291. nextKey = this.getNextKeyWith( type, h, 1 );
  18292. // if ( nextKey.index < prevKey.index ) then we have wrapped over the end, and nextKey.time < currentTime will loop forever
  18293. while ( nextKey !== null && nextKey.time < currentTime && nextKey.index > prevKey.index) {
  18294. prevKey = nextKey;
  18295. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18296. }
  18297. } else {
  18298. this.stop();
  18299. return;
  18300. }
  18301. } else {
  18302. do {
  18303. prevKey = nextKey;
  18304. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18305. } while ( nextKey !== null && nextKey.time < currentTime && nextKey.index > prevKey.index )
  18306. // if ( nextKey.index < prevKey.index ) then we have wrapped over the end, and nextKey.time < currentTime will loop forever
  18307. }
  18308. animationCache.prevKey[ type ] = prevKey;
  18309. animationCache.nextKey[ type ] = nextKey;
  18310. }
  18311. object.matrixAutoUpdate = true;
  18312. object.matrixWorldNeedsUpdate = true;
  18313. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  18314. prevXYZ = prevKey[ type ];
  18315. nextXYZ = nextKey[ type ];
  18316. // check scale error
  18317. if ( scale < 0 || scale > 1 ) {
  18318. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  18319. scale = scale < 0 ? 0 : 1;
  18320. }
  18321. // interpolate
  18322. if ( type === "pos" ) {
  18323. vector = object.position;
  18324. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  18325. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18326. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18327. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18328. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18329. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18330. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  18331. this.points[ 1 ] = prevXYZ;
  18332. this.points[ 2 ] = nextXYZ;
  18333. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  18334. scale = scale * 0.33 + 0.33;
  18335. currentPoint = this.interpolateCatmullRom( this.points, scale );
  18336. vector.x = currentPoint[ 0 ];
  18337. vector.y = currentPoint[ 1 ];
  18338. vector.z = currentPoint[ 2 ];
  18339. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18340. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  18341. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  18342. this.target.sub( vector );
  18343. this.target.y = 0;
  18344. this.target.normalize();
  18345. angle = Math.atan2( this.target.x, this.target.z );
  18346. object.rotation.set( 0, angle, 0 );
  18347. }
  18348. }
  18349. } else if ( type === "rot" ) {
  18350. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  18351. } else if ( type === "scl" ) {
  18352. vector = object.scale;
  18353. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18354. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18355. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18356. }
  18357. }
  18358. }
  18359. };
  18360. // Catmull-Rom spline
  18361. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  18362. var c = [], v3 = [],
  18363. point, intPoint, weight, w2, w3,
  18364. pa, pb, pc, pd;
  18365. point = ( points.length - 1 ) * scale;
  18366. intPoint = Math.floor( point );
  18367. weight = point - intPoint;
  18368. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  18369. c[ 1 ] = intPoint;
  18370. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  18371. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  18372. pa = points[ c[ 0 ] ];
  18373. pb = points[ c[ 1 ] ];
  18374. pc = points[ c[ 2 ] ];
  18375. pd = points[ c[ 3 ] ];
  18376. w2 = weight * weight;
  18377. w3 = weight * w2;
  18378. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  18379. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  18380. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  18381. return v3;
  18382. };
  18383. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  18384. var v0 = ( p2 - p0 ) * 0.5,
  18385. v1 = ( p3 - p1 ) * 0.5;
  18386. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18387. };
  18388. // Get next key with
  18389. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  18390. var keys = this.data.hierarchy[ h ].keys;
  18391. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18392. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18393. key = key < keys.length - 1 ? key : keys.length - 1;
  18394. } else {
  18395. key = key % keys.length;
  18396. }
  18397. for ( ; key < keys.length; key++ ) {
  18398. if ( keys[ key ][ type ] !== undefined ) {
  18399. return keys[ key ];
  18400. }
  18401. }
  18402. return this.data.hierarchy[ h ].keys[ 0 ];
  18403. };
  18404. // Get previous key with
  18405. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  18406. var keys = this.data.hierarchy[ h ].keys;
  18407. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18408. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18409. key = key > 0 ? key : 0;
  18410. } else {
  18411. key = key >= 0 ? key : key + keys.length;
  18412. }
  18413. for ( ; key >= 0; key -- ) {
  18414. if ( keys[ key ][ type ] !== undefined ) {
  18415. return keys[ key ];
  18416. }
  18417. }
  18418. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  18419. };
  18420. /**
  18421. * @author mikael emtinger / http://gomo.se/
  18422. * @author mrdoob / http://mrdoob.com/
  18423. * @author alteredq / http://alteredqualia.com/
  18424. * @author khang duong
  18425. * @author erik kitson
  18426. */
  18427. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  18428. this.root = root;
  18429. this.data = THREE.AnimationHandler.get( data );
  18430. this.hierarchy = THREE.AnimationHandler.parse( root );
  18431. this.currentTime = 0;
  18432. this.timeScale = 0.001;
  18433. this.isPlaying = false;
  18434. this.isPaused = true;
  18435. this.loop = true;
  18436. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  18437. // initialize to first keyframes
  18438. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18439. var keys = this.data.hierarchy[h].keys,
  18440. sids = this.data.hierarchy[h].sids,
  18441. obj = this.hierarchy[h];
  18442. if ( keys.length && sids ) {
  18443. for ( var s = 0; s < sids.length; s++ ) {
  18444. var sid = sids[ s ],
  18445. next = this.getNextKeyWith( sid, h, 0 );
  18446. if ( next ) {
  18447. next.apply( sid );
  18448. }
  18449. }
  18450. obj.matrixAutoUpdate = false;
  18451. this.data.hierarchy[h].node.updateMatrix();
  18452. obj.matrixWorldNeedsUpdate = true;
  18453. }
  18454. }
  18455. };
  18456. // Play
  18457. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  18458. if( !this.isPlaying ) {
  18459. this.isPlaying = true;
  18460. this.loop = loop !== undefined ? loop : true;
  18461. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  18462. this.startTimeMs = startTimeMS;
  18463. this.startTime = 10000000;
  18464. this.endTime = -this.startTime;
  18465. // reset key cache
  18466. var h, hl = this.hierarchy.length,
  18467. object,
  18468. node;
  18469. for ( h = 0; h < hl; h++ ) {
  18470. object = this.hierarchy[ h ];
  18471. node = this.data.hierarchy[ h ];
  18472. if ( node.animationCache === undefined ) {
  18473. node.animationCache = {};
  18474. node.animationCache.prevKey = null;
  18475. node.animationCache.nextKey = null;
  18476. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18477. }
  18478. var keys = this.data.hierarchy[h].keys;
  18479. if (keys.length) {
  18480. node.animationCache.prevKey = keys[ 0 ];
  18481. node.animationCache.nextKey = keys[ 1 ];
  18482. this.startTime = Math.min( keys[0].time, this.startTime );
  18483. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18484. }
  18485. }
  18486. this.update( 0 );
  18487. }
  18488. this.isPaused = false;
  18489. THREE.AnimationHandler.addToUpdate( this );
  18490. };
  18491. // Pause
  18492. THREE.KeyFrameAnimation.prototype.pause = function() {
  18493. if( this.isPaused ) {
  18494. THREE.AnimationHandler.addToUpdate( this );
  18495. } else {
  18496. THREE.AnimationHandler.removeFromUpdate( this );
  18497. }
  18498. this.isPaused = !this.isPaused;
  18499. };
  18500. // Stop
  18501. THREE.KeyFrameAnimation.prototype.stop = function() {
  18502. this.isPlaying = false;
  18503. this.isPaused = false;
  18504. THREE.AnimationHandler.removeFromUpdate( this );
  18505. // reset JIT matrix and remove cache
  18506. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  18507. var obj = this.hierarchy[ h ];
  18508. var node = this.data.hierarchy[ h ];
  18509. if ( node.animationCache !== undefined ) {
  18510. var original = node.animationCache.originalMatrix;
  18511. if( obj instanceof THREE.Bone ) {
  18512. original.copy( obj.skinMatrix );
  18513. obj.skinMatrix = original;
  18514. } else {
  18515. original.copy( obj.matrix );
  18516. obj.matrix = original;
  18517. }
  18518. delete node.animationCache;
  18519. }
  18520. }
  18521. };
  18522. // Update
  18523. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  18524. // early out
  18525. if( !this.isPlaying ) return;
  18526. // vars
  18527. var prevKey, nextKey;
  18528. var object;
  18529. var node;
  18530. var frame;
  18531. var JIThierarchy = this.data.JIT.hierarchy;
  18532. var currentTime, unloopedCurrentTime;
  18533. var looped;
  18534. // update
  18535. this.currentTime += deltaTimeMS * this.timeScale;
  18536. unloopedCurrentTime = this.currentTime;
  18537. currentTime = this.currentTime = this.currentTime % this.data.length;
  18538. // if looped around, the current time should be based on the startTime
  18539. if ( currentTime < this.startTimeMs ) {
  18540. currentTime = this.currentTime = this.startTimeMs + currentTime;
  18541. }
  18542. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18543. looped = currentTime < unloopedCurrentTime;
  18544. if ( looped && !this.loop ) {
  18545. // Set the animation to the last keyframes and stop
  18546. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18547. var keys = this.data.hierarchy[h].keys,
  18548. sids = this.data.hierarchy[h].sids,
  18549. end = keys.length-1,
  18550. obj = this.hierarchy[h];
  18551. if ( keys.length ) {
  18552. for ( var s = 0; s < sids.length; s++ ) {
  18553. var sid = sids[ s ],
  18554. prev = this.getPrevKeyWith( sid, h, end );
  18555. if ( prev ) {
  18556. prev.apply( sid );
  18557. }
  18558. }
  18559. this.data.hierarchy[h].node.updateMatrix();
  18560. obj.matrixWorldNeedsUpdate = true;
  18561. }
  18562. }
  18563. this.stop();
  18564. return;
  18565. }
  18566. // check pre-infinity
  18567. if ( currentTime < this.startTime ) {
  18568. return;
  18569. }
  18570. // update
  18571. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18572. object = this.hierarchy[ h ];
  18573. node = this.data.hierarchy[ h ];
  18574. var keys = node.keys,
  18575. animationCache = node.animationCache;
  18576. // use JIT?
  18577. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  18578. if( object instanceof THREE.Bone ) {
  18579. object.skinMatrix = JIThierarchy[ h ][ frame ];
  18580. object.matrixWorldNeedsUpdate = false;
  18581. } else {
  18582. object.matrix = JIThierarchy[ h ][ frame ];
  18583. object.matrixWorldNeedsUpdate = true;
  18584. }
  18585. // use interpolation
  18586. } else if ( keys.length ) {
  18587. // make sure so original matrix and not JIT matrix is set
  18588. if ( this.JITCompile && animationCache ) {
  18589. if( object instanceof THREE.Bone ) {
  18590. object.skinMatrix = animationCache.originalMatrix;
  18591. } else {
  18592. object.matrix = animationCache.originalMatrix;
  18593. }
  18594. }
  18595. prevKey = animationCache.prevKey;
  18596. nextKey = animationCache.nextKey;
  18597. if ( prevKey && nextKey ) {
  18598. // switch keys?
  18599. if ( nextKey.time <= unloopedCurrentTime ) {
  18600. // did we loop?
  18601. if ( looped && this.loop ) {
  18602. prevKey = keys[ 0 ];
  18603. nextKey = keys[ 1 ];
  18604. while ( nextKey.time < currentTime ) {
  18605. prevKey = nextKey;
  18606. nextKey = keys[ prevKey.index + 1 ];
  18607. }
  18608. } else if ( !looped ) {
  18609. var lastIndex = keys.length - 1;
  18610. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  18611. prevKey = nextKey;
  18612. nextKey = keys[ prevKey.index + 1 ];
  18613. }
  18614. }
  18615. animationCache.prevKey = prevKey;
  18616. animationCache.nextKey = nextKey;
  18617. }
  18618. if(nextKey.time >= currentTime)
  18619. prevKey.interpolate( nextKey, currentTime );
  18620. else
  18621. prevKey.interpolate( nextKey, nextKey.time);
  18622. }
  18623. this.data.hierarchy[h].node.updateMatrix();
  18624. object.matrixWorldNeedsUpdate = true;
  18625. }
  18626. }
  18627. // update JIT?
  18628. if ( this.JITCompile ) {
  18629. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  18630. this.hierarchy[ 0 ].updateMatrixWorld( true );
  18631. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  18632. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  18633. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  18634. } else {
  18635. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  18636. }
  18637. }
  18638. }
  18639. }
  18640. };
  18641. // Get next key with
  18642. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18643. var keys = this.data.hierarchy[ h ].keys;
  18644. key = key % keys.length;
  18645. for ( ; key < keys.length; key++ ) {
  18646. if ( keys[ key ].hasTarget( sid ) ) {
  18647. return keys[ key ];
  18648. }
  18649. }
  18650. return keys[ 0 ];
  18651. };
  18652. // Get previous key with
  18653. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18654. var keys = this.data.hierarchy[ h ].keys;
  18655. key = key >= 0 ? key : key + keys.length;
  18656. for ( ; key >= 0; key-- ) {
  18657. if ( keys[ key ].hasTarget( sid ) ) {
  18658. return keys[ key ];
  18659. }
  18660. }
  18661. return keys[ keys.length - 1 ];
  18662. };
  18663. /**
  18664. * Camera for rendering cube maps
  18665. * - renders scene into axis-aligned cube
  18666. *
  18667. * @author alteredq / http://alteredqualia.com/
  18668. */
  18669. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  18670. THREE.Object3D.call( this );
  18671. var fov = 90, aspect = 1;
  18672. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18673. cameraPX.up.set( 0, -1, 0 );
  18674. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  18675. this.add( cameraPX );
  18676. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18677. cameraNX.up.set( 0, -1, 0 );
  18678. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  18679. this.add( cameraNX );
  18680. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18681. cameraPY.up.set( 0, 0, 1 );
  18682. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  18683. this.add( cameraPY );
  18684. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18685. cameraNY.up.set( 0, 0, -1 );
  18686. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  18687. this.add( cameraNY );
  18688. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18689. cameraPZ.up.set( 0, -1, 0 );
  18690. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  18691. this.add( cameraPZ );
  18692. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18693. cameraNZ.up.set( 0, -1, 0 );
  18694. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  18695. this.add( cameraNZ );
  18696. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  18697. this.updateCubeMap = function ( renderer, scene ) {
  18698. var renderTarget = this.renderTarget;
  18699. var generateMipmaps = renderTarget.generateMipmaps;
  18700. renderTarget.generateMipmaps = false;
  18701. renderTarget.activeCubeFace = 0;
  18702. renderer.render( scene, cameraPX, renderTarget );
  18703. renderTarget.activeCubeFace = 1;
  18704. renderer.render( scene, cameraNX, renderTarget );
  18705. renderTarget.activeCubeFace = 2;
  18706. renderer.render( scene, cameraPY, renderTarget );
  18707. renderTarget.activeCubeFace = 3;
  18708. renderer.render( scene, cameraNY, renderTarget );
  18709. renderTarget.activeCubeFace = 4;
  18710. renderer.render( scene, cameraPZ, renderTarget );
  18711. renderTarget.generateMipmaps = generateMipmaps;
  18712. renderTarget.activeCubeFace = 5;
  18713. renderer.render( scene, cameraNZ, renderTarget );
  18714. };
  18715. };
  18716. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  18717. /**
  18718. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  18719. *
  18720. * A general perpose camera, for setting FOV, Lens Focal Length,
  18721. * and switching between perspective and orthographic views easily.
  18722. * Use this only if you do not wish to manage
  18723. * both a Orthographic and Perspective Camera
  18724. *
  18725. */
  18726. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  18727. THREE.Camera.call( this );
  18728. this.fov = fov;
  18729. this.left = -width / 2;
  18730. this.right = width / 2
  18731. this.top = height / 2;
  18732. this.bottom = -height / 2;
  18733. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  18734. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  18735. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  18736. this.zoom = 1;
  18737. this.toPerspective();
  18738. var aspect = width/height;
  18739. };
  18740. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  18741. THREE.CombinedCamera.prototype.toPerspective = function () {
  18742. // Switches to the Perspective Camera
  18743. this.near = this.cameraP.near;
  18744. this.far = this.cameraP.far;
  18745. this.cameraP.fov = this.fov / this.zoom ;
  18746. this.cameraP.updateProjectionMatrix();
  18747. this.projectionMatrix = this.cameraP.projectionMatrix;
  18748. this.inPerspectiveMode = true;
  18749. this.inOrthographicMode = false;
  18750. };
  18751. THREE.CombinedCamera.prototype.toOrthographic = function () {
  18752. // Switches to the Orthographic camera estimating viewport from Perspective
  18753. var fov = this.fov;
  18754. var aspect = this.cameraP.aspect;
  18755. var near = this.cameraP.near;
  18756. var far = this.cameraP.far;
  18757. // The size that we set is the mid plane of the viewing frustum
  18758. var hyperfocus = ( near + far ) / 2;
  18759. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  18760. var planeHeight = 2 * halfHeight;
  18761. var planeWidth = planeHeight * aspect;
  18762. var halfWidth = planeWidth / 2;
  18763. halfHeight /= this.zoom;
  18764. halfWidth /= this.zoom;
  18765. this.cameraO.left = -halfWidth;
  18766. this.cameraO.right = halfWidth;
  18767. this.cameraO.top = halfHeight;
  18768. this.cameraO.bottom = -halfHeight;
  18769. // this.cameraO.left = -farHalfWidth;
  18770. // this.cameraO.right = farHalfWidth;
  18771. // this.cameraO.top = farHalfHeight;
  18772. // this.cameraO.bottom = -farHalfHeight;
  18773. // this.cameraO.left = this.left / this.zoom;
  18774. // this.cameraO.right = this.right / this.zoom;
  18775. // this.cameraO.top = this.top / this.zoom;
  18776. // this.cameraO.bottom = this.bottom / this.zoom;
  18777. this.cameraO.updateProjectionMatrix();
  18778. this.near = this.cameraO.near;
  18779. this.far = this.cameraO.far;
  18780. this.projectionMatrix = this.cameraO.projectionMatrix;
  18781. this.inPerspectiveMode = false;
  18782. this.inOrthographicMode = true;
  18783. };
  18784. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  18785. this.cameraP.aspect = width / height;
  18786. this.left = -width / 2;
  18787. this.right = width / 2
  18788. this.top = height / 2;
  18789. this.bottom = -height / 2;
  18790. };
  18791. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  18792. this.fov = fov;
  18793. if ( this.inPerspectiveMode ) {
  18794. this.toPerspective();
  18795. } else {
  18796. this.toOrthographic();
  18797. }
  18798. };
  18799. // For mantaining similar API with PerspectiveCamera
  18800. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  18801. if ( this.inPerspectiveMode ) {
  18802. this.toPerspective();
  18803. } else {
  18804. this.toPerspective();
  18805. this.toOrthographic();
  18806. }
  18807. };
  18808. /*
  18809. * Uses Focal Length (in mm) to estimate and set FOV
  18810. * 35mm (fullframe) camera is used if frame size is not specified;
  18811. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  18812. */
  18813. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  18814. if ( frameHeight === undefined ) frameHeight = 24;
  18815. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  18816. this.setFov( fov );
  18817. return fov;
  18818. };
  18819. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  18820. this.zoom = zoom;
  18821. if ( this.inPerspectiveMode ) {
  18822. this.toPerspective();
  18823. } else {
  18824. this.toOrthographic();
  18825. }
  18826. };
  18827. THREE.CombinedCamera.prototype.toFrontView = function() {
  18828. this.rotation.x = 0;
  18829. this.rotation.y = 0;
  18830. this.rotation.z = 0;
  18831. // should we be modifing the matrix instead?
  18832. this.rotationAutoUpdate = false;
  18833. };
  18834. THREE.CombinedCamera.prototype.toBackView = function() {
  18835. this.rotation.x = 0;
  18836. this.rotation.y = Math.PI;
  18837. this.rotation.z = 0;
  18838. this.rotationAutoUpdate = false;
  18839. };
  18840. THREE.CombinedCamera.prototype.toLeftView = function() {
  18841. this.rotation.x = 0;
  18842. this.rotation.y = - Math.PI / 2;
  18843. this.rotation.z = 0;
  18844. this.rotationAutoUpdate = false;
  18845. };
  18846. THREE.CombinedCamera.prototype.toRightView = function() {
  18847. this.rotation.x = 0;
  18848. this.rotation.y = Math.PI / 2;
  18849. this.rotation.z = 0;
  18850. this.rotationAutoUpdate = false;
  18851. };
  18852. THREE.CombinedCamera.prototype.toTopView = function() {
  18853. this.rotation.x = - Math.PI / 2;
  18854. this.rotation.y = 0;
  18855. this.rotation.z = 0;
  18856. this.rotationAutoUpdate = false;
  18857. };
  18858. THREE.CombinedCamera.prototype.toBottomView = function() {
  18859. this.rotation.x = Math.PI / 2;
  18860. this.rotation.y = 0;
  18861. this.rotation.z = 0;
  18862. this.rotationAutoUpdate = false;
  18863. };
  18864. /**
  18865. * @author hughes
  18866. */
  18867. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18868. THREE.Geometry.call( this );
  18869. this.radius = radius = radius || 50;
  18870. this.segments = segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18871. this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18872. this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18873. var i, uvs = [],
  18874. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18875. this.vertices.push(center);
  18876. uvs.push( centerUV );
  18877. for ( i = 0; i <= segments; i ++ ) {
  18878. var vertex = new THREE.Vector3();
  18879. var segment = thetaStart + i / segments * thetaLength;
  18880. vertex.x = radius * Math.cos( segment );
  18881. vertex.y = radius * Math.sin( segment );
  18882. this.vertices.push( vertex );
  18883. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, ( vertex.y / radius + 1 ) / 2 ) );
  18884. }
  18885. var n = new THREE.Vector3( 0, 0, 1 );
  18886. for ( i = 1; i <= segments; i ++ ) {
  18887. var v1 = i;
  18888. var v2 = i + 1 ;
  18889. var v3 = 0;
  18890. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  18891. this.faceVertexUvs[ 0 ].push( [ uvs[ i ].clone(), uvs[ i + 1 ].clone(), centerUV.clone() ] );
  18892. }
  18893. this.computeCentroids();
  18894. this.computeFaceNormals();
  18895. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  18896. };
  18897. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18898. /**
  18899. * @author mrdoob / http://mrdoob.com/
  18900. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18901. */
  18902. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18903. THREE.Geometry.call( this );
  18904. var scope = this;
  18905. this.width = width;
  18906. this.height = height;
  18907. this.depth = depth;
  18908. this.widthSegments = widthSegments || 1;
  18909. this.heightSegments = heightSegments || 1;
  18910. this.depthSegments = depthSegments || 1;
  18911. var width_half = this.width / 2;
  18912. var height_half = this.height / 2;
  18913. var depth_half = this.depth / 2;
  18914. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  18915. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  18916. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  18917. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  18918. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  18919. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  18920. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18921. var w, ix, iy,
  18922. gridX = scope.widthSegments,
  18923. gridY = scope.heightSegments,
  18924. width_half = width / 2,
  18925. height_half = height / 2,
  18926. offset = scope.vertices.length;
  18927. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18928. w = 'z';
  18929. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18930. w = 'y';
  18931. gridY = scope.depthSegments;
  18932. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18933. w = 'x';
  18934. gridX = scope.depthSegments;
  18935. }
  18936. var gridX1 = gridX + 1,
  18937. gridY1 = gridY + 1,
  18938. segment_width = width / gridX,
  18939. segment_height = height / gridY,
  18940. normal = new THREE.Vector3();
  18941. normal[ w ] = depth > 0 ? 1 : - 1;
  18942. for ( iy = 0; iy < gridY1; iy ++ ) {
  18943. for ( ix = 0; ix < gridX1; ix ++ ) {
  18944. var vector = new THREE.Vector3();
  18945. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18946. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18947. vector[ w ] = depth;
  18948. scope.vertices.push( vector );
  18949. }
  18950. }
  18951. for ( iy = 0; iy < gridY; iy++ ) {
  18952. for ( ix = 0; ix < gridX; ix++ ) {
  18953. var a = ix + gridX1 * iy;
  18954. var b = ix + gridX1 * ( iy + 1 );
  18955. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18956. var d = ( ix + 1 ) + gridX1 * iy;
  18957. var uva = new THREE.Vector2( ix / gridX, 1 - iy / gridY );
  18958. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY );
  18959. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iy + 1 ) / gridY );
  18960. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY );
  18961. var face = new THREE.Face3( a + offset, b + offset, d + offset );
  18962. face.normal.copy( normal );
  18963. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18964. face.materialIndex = materialIndex;
  18965. scope.faces.push( face );
  18966. scope.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  18967. face = new THREE.Face3( b + offset, c + offset, d + offset );
  18968. face.normal.copy( normal );
  18969. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  18970. face.materialIndex = materialIndex;
  18971. scope.faces.push( face );
  18972. scope.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  18973. }
  18974. }
  18975. }
  18976. this.computeCentroids();
  18977. this.mergeVertices();
  18978. };
  18979. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18980. /**
  18981. * @author mrdoob / http://mrdoob.com/
  18982. */
  18983. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded ) {
  18984. THREE.Geometry.call( this );
  18985. this.radiusTop = radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18986. this.radiusBottom = radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18987. this.height = height = height !== undefined ? height : 100;
  18988. this.radialSegments = radialSegments = radialSegments || 8;
  18989. this.heightSegments = heightSegments = heightSegments || 1;
  18990. this.openEnded = openEnded = openEnded !== undefined ? openEnded : false;
  18991. var heightHalf = height / 2;
  18992. var x, y, vertices = [], uvs = [];
  18993. for ( y = 0; y <= heightSegments; y ++ ) {
  18994. var verticesRow = [];
  18995. var uvsRow = [];
  18996. var v = y / heightSegments;
  18997. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18998. for ( x = 0; x <= radialSegments; x ++ ) {
  18999. var u = x / radialSegments;
  19000. var vertex = new THREE.Vector3();
  19001. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  19002. vertex.y = - v * height + heightHalf;
  19003. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  19004. this.vertices.push( vertex );
  19005. verticesRow.push( this.vertices.length - 1 );
  19006. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19007. }
  19008. vertices.push( verticesRow );
  19009. uvs.push( uvsRow );
  19010. }
  19011. var tanTheta = ( radiusBottom - radiusTop ) / height;
  19012. var na, nb;
  19013. for ( x = 0; x < radialSegments; x ++ ) {
  19014. if ( radiusTop !== 0 ) {
  19015. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  19016. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  19017. } else {
  19018. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  19019. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  19020. }
  19021. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  19022. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  19023. for ( y = 0; y < heightSegments; y ++ ) {
  19024. var v1 = vertices[ y ][ x ];
  19025. var v2 = vertices[ y + 1 ][ x ];
  19026. var v3 = vertices[ y + 1 ][ x + 1 ];
  19027. var v4 = vertices[ y ][ x + 1 ];
  19028. var n1 = na.clone();
  19029. var n2 = na.clone();
  19030. var n3 = nb.clone();
  19031. var n4 = nb.clone();
  19032. var uv1 = uvs[ y ][ x ].clone();
  19033. var uv2 = uvs[ y + 1 ][ x ].clone();
  19034. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  19035. var uv4 = uvs[ y ][ x + 1 ].clone();
  19036. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  19037. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  19038. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  19039. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  19040. }
  19041. }
  19042. // top cap
  19043. if ( openEnded === false && radiusTop > 0 ) {
  19044. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  19045. for ( x = 0; x < radialSegments; x ++ ) {
  19046. var v1 = vertices[ 0 ][ x ];
  19047. var v2 = vertices[ 0 ][ x + 1 ];
  19048. var v3 = this.vertices.length - 1;
  19049. var n1 = new THREE.Vector3( 0, 1, 0 );
  19050. var n2 = new THREE.Vector3( 0, 1, 0 );
  19051. var n3 = new THREE.Vector3( 0, 1, 0 );
  19052. var uv1 = uvs[ 0 ][ x ].clone();
  19053. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  19054. var uv3 = new THREE.Vector2( uv2.x, 0 );
  19055. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19056. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19057. }
  19058. }
  19059. // bottom cap
  19060. if ( openEnded === false && radiusBottom > 0 ) {
  19061. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  19062. for ( x = 0; x < radialSegments; x ++ ) {
  19063. var v1 = vertices[ y ][ x + 1 ];
  19064. var v2 = vertices[ y ][ x ];
  19065. var v3 = this.vertices.length - 1;
  19066. var n1 = new THREE.Vector3( 0, - 1, 0 );
  19067. var n2 = new THREE.Vector3( 0, - 1, 0 );
  19068. var n3 = new THREE.Vector3( 0, - 1, 0 );
  19069. var uv1 = uvs[ y ][ x + 1 ].clone();
  19070. var uv2 = uvs[ y ][ x ].clone();
  19071. var uv3 = new THREE.Vector2( uv2.x, 1 );
  19072. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19073. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19074. }
  19075. }
  19076. this.computeCentroids();
  19077. this.computeFaceNormals();
  19078. }
  19079. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19080. /**
  19081. * @author zz85 / http://www.lab4games.net/zz85/blog
  19082. *
  19083. * Creates extruded geometry from a path shape.
  19084. *
  19085. * parameters = {
  19086. *
  19087. * curveSegments: <int>, // number of points on the curves
  19088. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  19089. * amount: <int>, // Depth to extrude the shape
  19090. *
  19091. * bevelEnabled: <bool>, // turn on bevel
  19092. * bevelThickness: <float>, // how deep into the original shape bevel goes
  19093. * bevelSize: <float>, // how far from shape outline is bevel
  19094. * bevelSegments: <int>, // number of bevel layers
  19095. *
  19096. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  19097. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  19098. *
  19099. * material: <int> // material index for front and back faces
  19100. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  19101. * uvGenerator: <Object> // object that provides UV generator functions
  19102. *
  19103. * }
  19104. **/
  19105. THREE.ExtrudeGeometry = function ( shapes, options ) {
  19106. if ( typeof( shapes ) === "undefined" ) {
  19107. shapes = [];
  19108. return;
  19109. }
  19110. THREE.Geometry.call( this );
  19111. shapes = shapes instanceof Array ? shapes : [ shapes ];
  19112. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19113. this.addShapeList( shapes, options );
  19114. this.computeCentroids();
  19115. this.computeFaceNormals();
  19116. // can't really use automatic vertex normals
  19117. // as then front and back sides get smoothed too
  19118. // should do separate smoothing just for sides
  19119. //this.computeVertexNormals();
  19120. //console.log( "took", ( Date.now() - startTime ) );
  19121. };
  19122. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19123. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19124. var sl = shapes.length;
  19125. for ( var s = 0; s < sl; s ++ ) {
  19126. var shape = shapes[ s ];
  19127. this.addShape( shape, options );
  19128. }
  19129. };
  19130. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  19131. var amount = options.amount !== undefined ? options.amount : 100;
  19132. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  19133. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  19134. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19135. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  19136. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19137. var steps = options.steps !== undefined ? options.steps : 1;
  19138. var extrudePath = options.extrudePath;
  19139. var extrudePts, extrudeByPath = false;
  19140. var material = options.material;
  19141. var extrudeMaterial = options.extrudeMaterial;
  19142. // Use default WorldUVGenerator if no UV generators are specified.
  19143. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  19144. var shapebb = this.shapebb;
  19145. //shapebb = shape.getBoundingBox();
  19146. var splineTube, binormal, normal, position2;
  19147. if ( extrudePath ) {
  19148. extrudePts = extrudePath.getSpacedPoints( steps );
  19149. extrudeByPath = true;
  19150. bevelEnabled = false; // bevels not supported for path extrusion
  19151. // SETUP TNB variables
  19152. // Reuse TNB from TubeGeomtry for now.
  19153. // TODO1 - have a .isClosed in spline?
  19154. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  19155. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19156. binormal = new THREE.Vector3();
  19157. normal = new THREE.Vector3();
  19158. position2 = new THREE.Vector3();
  19159. }
  19160. // Safeguards if bevels are not enabled
  19161. if ( ! bevelEnabled ) {
  19162. bevelSegments = 0;
  19163. bevelThickness = 0;
  19164. bevelSize = 0;
  19165. }
  19166. // Variables initalization
  19167. var ahole, h, hl; // looping of holes
  19168. var scope = this;
  19169. var bevelPoints = [];
  19170. var shapesOffset = this.vertices.length;
  19171. var shapePoints = shape.extractPoints( curveSegments );
  19172. var vertices = shapePoints.shape;
  19173. var holes = shapePoints.holes;
  19174. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  19175. if ( reverse ) {
  19176. vertices = vertices.reverse();
  19177. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19178. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19179. ahole = holes[ h ];
  19180. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  19181. holes[ h ] = ahole.reverse();
  19182. }
  19183. }
  19184. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  19185. }
  19186. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  19187. /* Vertices */
  19188. var contour = vertices; // vertices has all points but contour has only points of circumference
  19189. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19190. ahole = holes[ h ];
  19191. vertices = vertices.concat( ahole );
  19192. }
  19193. function scalePt2 ( pt, vec, size ) {
  19194. if ( !vec ) console.log( "die" );
  19195. return vec.clone().multiplyScalar( size ).add( pt );
  19196. }
  19197. var b, bs, t, z,
  19198. vert, vlen = vertices.length,
  19199. face, flen = faces.length,
  19200. cont, clen = contour.length;
  19201. // Find directions for point movement
  19202. var RAD_TO_DEGREES = 180 / Math.PI;
  19203. function getBevelVec( pt_i, pt_j, pt_k ) {
  19204. // Algorithm 2
  19205. return getBevelVec2( pt_i, pt_j, pt_k );
  19206. }
  19207. function getBevelVec1( pt_i, pt_j, pt_k ) {
  19208. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  19209. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  19210. if ( anglea > angleb ) {
  19211. angleb += Math.PI * 2;
  19212. }
  19213. var anglec = ( anglea + angleb ) / 2;
  19214. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  19215. var x = - Math.cos( anglec );
  19216. var y = - Math.sin( anglec );
  19217. var vec = new THREE.Vector2( x, y ); //.normalize();
  19218. return vec;
  19219. }
  19220. function getBevelVec2( pt_i, pt_j, pt_k ) {
  19221. var a = THREE.ExtrudeGeometry.__v1,
  19222. b = THREE.ExtrudeGeometry.__v2,
  19223. v_hat = THREE.ExtrudeGeometry.__v3,
  19224. w_hat = THREE.ExtrudeGeometry.__v4,
  19225. p = THREE.ExtrudeGeometry.__v5,
  19226. q = THREE.ExtrudeGeometry.__v6,
  19227. v, w,
  19228. v_dot_w_hat, q_sub_p_dot_w_hat,
  19229. s, intersection;
  19230. // good reading for line-line intersection
  19231. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  19232. // define a as vector j->i
  19233. // define b as vectot k->i
  19234. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  19235. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  19236. // get unit vectors
  19237. v = a.normalize();
  19238. w = b.normalize();
  19239. // normals from pt i
  19240. v_hat.set( -v.y, v.x );
  19241. w_hat.set( w.y, -w.x );
  19242. // pts from i
  19243. p.copy( pt_i ).add( v_hat );
  19244. q.copy( pt_i ).add( w_hat );
  19245. if ( p.equals( q ) ) {
  19246. //console.log("Warning: lines are straight");
  19247. return w_hat.clone();
  19248. }
  19249. // Points from j, k. helps prevents points cross overover most of the time
  19250. p.copy( pt_j ).add( v_hat );
  19251. q.copy( pt_k ).add( w_hat );
  19252. v_dot_w_hat = v.dot( w_hat );
  19253. q_sub_p_dot_w_hat = q.sub( p ).dot( w_hat );
  19254. // We should not reach these conditions
  19255. if ( v_dot_w_hat === 0 ) {
  19256. console.log( "Either infinite or no solutions!" );
  19257. if ( q_sub_p_dot_w_hat === 0 ) {
  19258. console.log( "Its finite solutions." );
  19259. } else {
  19260. console.log( "Too bad, no solutions." );
  19261. }
  19262. }
  19263. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  19264. if ( s < 0 ) {
  19265. // in case of emergecy, revert to algorithm 1.
  19266. return getBevelVec1( pt_i, pt_j, pt_k );
  19267. }
  19268. intersection = v.multiplyScalar( s ).add( p );
  19269. return intersection.sub( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  19270. }
  19271. var contourMovements = [];
  19272. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19273. if ( j === il ) j = 0;
  19274. if ( k === il ) k = 0;
  19275. // (j)---(i)---(k)
  19276. // console.log('i,j,k', i, j , k)
  19277. var pt_i = contour[ i ];
  19278. var pt_j = contour[ j ];
  19279. var pt_k = contour[ k ];
  19280. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  19281. }
  19282. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  19283. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19284. ahole = holes[ h ];
  19285. oneHoleMovements = [];
  19286. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19287. if ( j === il ) j = 0;
  19288. if ( k === il ) k = 0;
  19289. // (j)---(i)---(k)
  19290. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  19291. }
  19292. holesMovements.push( oneHoleMovements );
  19293. verticesMovements = verticesMovements.concat( oneHoleMovements );
  19294. }
  19295. // Loop bevelSegments, 1 for the front, 1 for the back
  19296. for ( b = 0; b < bevelSegments; b ++ ) {
  19297. //for ( b = bevelSegments; b > 0; b -- ) {
  19298. t = b / bevelSegments;
  19299. z = bevelThickness * ( 1 - t );
  19300. //z = bevelThickness * t;
  19301. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  19302. //bs = bevelSize * t ; // linear
  19303. // contract shape
  19304. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19305. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19306. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  19307. v( vert.x, vert.y, - z );
  19308. }
  19309. // expand holes
  19310. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  19311. ahole = holes[ h ];
  19312. oneHoleMovements = holesMovements[ h ];
  19313. for ( i = 0, il = ahole.length; i < il; i++ ) {
  19314. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19315. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  19316. v( vert.x, vert.y, -z );
  19317. }
  19318. }
  19319. }
  19320. bs = bevelSize;
  19321. // Back facing vertices
  19322. for ( i = 0; i < vlen; i ++ ) {
  19323. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19324. if ( !extrudeByPath ) {
  19325. v( vert.x, vert.y, 0 );
  19326. } else {
  19327. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19328. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  19329. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  19330. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  19331. v( position2.x, position2.y, position2.z );
  19332. }
  19333. }
  19334. // Add stepped vertices...
  19335. // Including front facing vertices
  19336. var s;
  19337. for ( s = 1; s <= steps; s ++ ) {
  19338. for ( i = 0; i < vlen; i ++ ) {
  19339. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19340. if ( !extrudeByPath ) {
  19341. v( vert.x, vert.y, amount / steps * s );
  19342. } else {
  19343. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19344. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  19345. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  19346. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  19347. v( position2.x, position2.y, position2.z );
  19348. }
  19349. }
  19350. }
  19351. // Add bevel segments planes
  19352. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19353. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  19354. t = b / bevelSegments;
  19355. z = bevelThickness * ( 1 - t );
  19356. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  19357. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  19358. // contract shape
  19359. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19360. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19361. v( vert.x, vert.y, amount + z );
  19362. }
  19363. // expand holes
  19364. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19365. ahole = holes[ h ];
  19366. oneHoleMovements = holesMovements[ h ];
  19367. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  19368. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19369. if ( !extrudeByPath ) {
  19370. v( vert.x, vert.y, amount + z );
  19371. } else {
  19372. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19373. }
  19374. }
  19375. }
  19376. }
  19377. /* Faces */
  19378. // Top and bottom faces
  19379. buildLidFaces();
  19380. // Sides faces
  19381. buildSideFaces();
  19382. ///// Internal functions
  19383. function buildLidFaces() {
  19384. if ( bevelEnabled ) {
  19385. var layer = 0 ; // steps + 1
  19386. var offset = vlen * layer;
  19387. // Bottom faces
  19388. for ( i = 0; i < flen; i ++ ) {
  19389. face = faces[ i ];
  19390. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  19391. }
  19392. layer = steps + bevelSegments * 2;
  19393. offset = vlen * layer;
  19394. // Top faces
  19395. for ( i = 0; i < flen; i ++ ) {
  19396. face = faces[ i ];
  19397. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  19398. }
  19399. } else {
  19400. // Bottom faces
  19401. for ( i = 0; i < flen; i++ ) {
  19402. face = faces[ i ];
  19403. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  19404. }
  19405. // Top faces
  19406. for ( i = 0; i < flen; i ++ ) {
  19407. face = faces[ i ];
  19408. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  19409. }
  19410. }
  19411. }
  19412. // Create faces for the z-sides of the shape
  19413. function buildSideFaces() {
  19414. var layeroffset = 0;
  19415. sidewalls( contour, layeroffset );
  19416. layeroffset += contour.length;
  19417. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19418. ahole = holes[ h ];
  19419. sidewalls( ahole, layeroffset );
  19420. //, true
  19421. layeroffset += ahole.length;
  19422. }
  19423. }
  19424. function sidewalls( contour, layeroffset ) {
  19425. var j, k;
  19426. i = contour.length;
  19427. while ( --i >= 0 ) {
  19428. j = i;
  19429. k = i - 1;
  19430. if ( k < 0 ) k = contour.length - 1;
  19431. //console.log('b', i,j, i-1, k,vertices.length);
  19432. var s = 0, sl = steps + bevelSegments * 2;
  19433. for ( s = 0; s < sl; s ++ ) {
  19434. var slen1 = vlen * s;
  19435. var slen2 = vlen * ( s + 1 );
  19436. var a = layeroffset + j + slen1,
  19437. b = layeroffset + k + slen1,
  19438. c = layeroffset + k + slen2,
  19439. d = layeroffset + j + slen2;
  19440. f4( a, b, c, d, contour, s, sl, j, k );
  19441. }
  19442. }
  19443. }
  19444. function v( x, y, z ) {
  19445. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  19446. }
  19447. function f3( a, b, c, isBottom ) {
  19448. a += shapesOffset;
  19449. b += shapesOffset;
  19450. c += shapesOffset;
  19451. // normal, color, material
  19452. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19453. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  19454. scope.faceVertexUvs[ 0 ].push( uvs );
  19455. }
  19456. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19457. a += shapesOffset;
  19458. b += shapesOffset;
  19459. c += shapesOffset;
  19460. d += shapesOffset;
  19461. scope.faces.push( new THREE.Face3( a, b, d, null, null, extrudeMaterial ) );
  19462. scope.faces.push( new THREE.Face3( b, c, d, null, null, extrudeMaterial ) );
  19463. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  19464. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  19465. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  19466. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  19467. }
  19468. };
  19469. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19470. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19471. var ax = geometry.vertices[ indexA ].x,
  19472. ay = geometry.vertices[ indexA ].y,
  19473. bx = geometry.vertices[ indexB ].x,
  19474. by = geometry.vertices[ indexB ].y,
  19475. cx = geometry.vertices[ indexC ].x,
  19476. cy = geometry.vertices[ indexC ].y;
  19477. return [
  19478. new THREE.Vector2( ax, ay ),
  19479. new THREE.Vector2( bx, by ),
  19480. new THREE.Vector2( cx, cy )
  19481. ];
  19482. },
  19483. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19484. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19485. },
  19486. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19487. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19488. contourIndex1, contourIndex2 ) {
  19489. var ax = geometry.vertices[ indexA ].x,
  19490. ay = geometry.vertices[ indexA ].y,
  19491. az = geometry.vertices[ indexA ].z,
  19492. bx = geometry.vertices[ indexB ].x,
  19493. by = geometry.vertices[ indexB ].y,
  19494. bz = geometry.vertices[ indexB ].z,
  19495. cx = geometry.vertices[ indexC ].x,
  19496. cy = geometry.vertices[ indexC ].y,
  19497. cz = geometry.vertices[ indexC ].z,
  19498. dx = geometry.vertices[ indexD ].x,
  19499. dy = geometry.vertices[ indexD ].y,
  19500. dz = geometry.vertices[ indexD ].z;
  19501. if ( Math.abs( ay - by ) < 0.01 ) {
  19502. return [
  19503. new THREE.Vector2( ax, 1 - az ),
  19504. new THREE.Vector2( bx, 1 - bz ),
  19505. new THREE.Vector2( cx, 1 - cz ),
  19506. new THREE.Vector2( dx, 1 - dz )
  19507. ];
  19508. } else {
  19509. return [
  19510. new THREE.Vector2( ay, 1 - az ),
  19511. new THREE.Vector2( by, 1 - bz ),
  19512. new THREE.Vector2( cy, 1 - cz ),
  19513. new THREE.Vector2( dy, 1 - dz )
  19514. ];
  19515. }
  19516. }
  19517. };
  19518. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19519. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19520. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19521. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19522. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19523. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19524. /**
  19525. * @author jonobr1 / http://jonobr1.com
  19526. *
  19527. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19528. * ExtrudeGeometry.
  19529. *
  19530. * parameters = {
  19531. *
  19532. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19533. *
  19534. * material: <int> // material index for front and back faces
  19535. * uvGenerator: <Object> // object that provides UV generator functions
  19536. *
  19537. * }
  19538. **/
  19539. THREE.ShapeGeometry = function ( shapes, options ) {
  19540. THREE.Geometry.call( this );
  19541. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19542. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19543. this.addShapeList( shapes, options );
  19544. this.computeCentroids();
  19545. this.computeFaceNormals();
  19546. };
  19547. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19548. /**
  19549. * Add an array of shapes to THREE.ShapeGeometry.
  19550. */
  19551. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19552. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19553. this.addShape( shapes[ i ], options );
  19554. }
  19555. return this;
  19556. };
  19557. /**
  19558. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19559. */
  19560. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19561. if ( options === undefined ) options = {};
  19562. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19563. var material = options.material;
  19564. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19565. var shapebb = this.shapebb;
  19566. //
  19567. var i, l, hole, s;
  19568. var shapesOffset = this.vertices.length;
  19569. var shapePoints = shape.extractPoints( curveSegments );
  19570. var vertices = shapePoints.shape;
  19571. var holes = shapePoints.holes;
  19572. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19573. if ( reverse ) {
  19574. vertices = vertices.reverse();
  19575. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19576. for ( i = 0, l = holes.length; i < l; i++ ) {
  19577. hole = holes[ i ];
  19578. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19579. holes[ i ] = hole.reverse();
  19580. }
  19581. }
  19582. reverse = false;
  19583. }
  19584. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19585. // Vertices
  19586. var contour = vertices;
  19587. for ( i = 0, l = holes.length; i < l; i++ ) {
  19588. hole = holes[ i ];
  19589. vertices = vertices.concat( hole );
  19590. }
  19591. //
  19592. var vert, vlen = vertices.length;
  19593. var face, flen = faces.length;
  19594. var cont, clen = contour.length;
  19595. for ( i = 0; i < vlen; i++ ) {
  19596. vert = vertices[ i ];
  19597. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19598. }
  19599. for ( i = 0; i < flen; i++ ) {
  19600. face = faces[ i ];
  19601. var a = face[ 0 ] + shapesOffset;
  19602. var b = face[ 1 ] + shapesOffset;
  19603. var c = face[ 2 ] + shapesOffset;
  19604. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19605. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19606. }
  19607. };
  19608. /**
  19609. * @author astrodud / http://astrodud.isgreat.org/
  19610. * @author zz85 / https://github.com/zz85
  19611. * @author bhouston / http://exocortex.com
  19612. */
  19613. // points - to create a closed torus, one must use a set of points
  19614. // like so: [ a, b, c, d, a ], see first is the same as last.
  19615. // segments - the number of circumference segments to create
  19616. // phiStart - the starting radian
  19617. // phiLength - the radian (0 to 2*PI) range of the lathed section
  19618. // 2*pi is a closed lathe, less than 2PI is a portion.
  19619. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  19620. THREE.Geometry.call( this );
  19621. segments = segments || 12;
  19622. phiStart = phiStart || 0;
  19623. phiLength = phiLength || 2 * Math.PI;
  19624. var inversePointLength = 1.0 / ( points.length - 1 );
  19625. var inverseSegments = 1.0 / segments;
  19626. for ( var i = 0, il = segments; i <= il; i ++ ) {
  19627. var phi = phiStart + i * inverseSegments * phiLength;
  19628. var c = Math.cos( phi ),
  19629. s = Math.sin( phi );
  19630. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  19631. var pt = points[ j ];
  19632. var vertex = new THREE.Vector3();
  19633. vertex.x = c * pt.x - s * pt.y;
  19634. vertex.y = s * pt.x + c * pt.y;
  19635. vertex.z = pt.z;
  19636. this.vertices.push( vertex );
  19637. }
  19638. }
  19639. var np = points.length;
  19640. for ( var i = 0, il = segments; i < il; i ++ ) {
  19641. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  19642. var base = j + np * i;
  19643. var a = base;
  19644. var b = base + np;
  19645. var c = base + 1 + np;
  19646. var d = base + 1;
  19647. var u0 = i * inverseSegments;
  19648. var v0 = j * inversePointLength;
  19649. var u1 = u0 + inverseSegments;
  19650. var v1 = v0 + inversePointLength;
  19651. this.faces.push( new THREE.Face3( a, b, d ) );
  19652. this.faceVertexUvs[ 0 ].push( [
  19653. new THREE.Vector2( u0, v0 ),
  19654. new THREE.Vector2( u1, v0 ),
  19655. new THREE.Vector2( u0, v1 )
  19656. ] );
  19657. this.faces.push( new THREE.Face3( b, c, d ) );
  19658. this.faceVertexUvs[ 0 ].push( [
  19659. new THREE.Vector2( u1, v0 ),
  19660. new THREE.Vector2( u1, v1 ),
  19661. new THREE.Vector2( u0, v1 )
  19662. ] );
  19663. }
  19664. }
  19665. this.mergeVertices();
  19666. this.computeCentroids();
  19667. this.computeFaceNormals();
  19668. this.computeVertexNormals();
  19669. };
  19670. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19671. /**
  19672. * @author mrdoob / http://mrdoob.com/
  19673. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19674. */
  19675. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19676. THREE.Geometry.call( this );
  19677. this.width = width;
  19678. this.height = height;
  19679. this.widthSegments = widthSegments || 1;
  19680. this.heightSegments = heightSegments || 1;
  19681. var ix, iz;
  19682. var width_half = width / 2;
  19683. var height_half = height / 2;
  19684. var gridX = this.widthSegments;
  19685. var gridZ = this.heightSegments;
  19686. var gridX1 = gridX + 1;
  19687. var gridZ1 = gridZ + 1;
  19688. var segment_width = this.width / gridX;
  19689. var segment_height = this.height / gridZ;
  19690. var normal = new THREE.Vector3( 0, 0, 1 );
  19691. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19692. for ( ix = 0; ix < gridX1; ix ++ ) {
  19693. var x = ix * segment_width - width_half;
  19694. var y = iz * segment_height - height_half;
  19695. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19696. }
  19697. }
  19698. for ( iz = 0; iz < gridZ; iz ++ ) {
  19699. for ( ix = 0; ix < gridX; ix ++ ) {
  19700. var a = ix + gridX1 * iz;
  19701. var b = ix + gridX1 * ( iz + 1 );
  19702. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19703. var d = ( ix + 1 ) + gridX1 * iz;
  19704. var uva = new THREE.Vector2( ix / gridX, 1 - iz / gridZ );
  19705. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ );
  19706. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ );
  19707. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ );
  19708. var face = new THREE.Face3( a, b, d );
  19709. face.normal.copy( normal );
  19710. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19711. this.faces.push( face );
  19712. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19713. face = new THREE.Face3( b, c, d );
  19714. face.normal.copy( normal );
  19715. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19716. this.faces.push( face );
  19717. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19718. }
  19719. }
  19720. this.computeCentroids();
  19721. };
  19722. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19723. /**
  19724. * @author Kaleb Murphy
  19725. */
  19726. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19727. THREE.Geometry.call( this );
  19728. innerRadius = innerRadius || 0;
  19729. outerRadius = outerRadius || 50;
  19730. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19731. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19732. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  19733. phiSegments = phiSegments !== undefined ? Math.max( 3, phiSegments ) : 8;
  19734. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19735. for ( i = 0; i <= phiSegments; i ++ ) { // concentric circles inside ring
  19736. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19737. var vertex = new THREE.Vector3();
  19738. var segment = thetaStart + o / thetaSegments * thetaLength;
  19739. vertex.x = radius * Math.cos( segment );
  19740. vertex.y = radius * Math.sin( segment );
  19741. this.vertices.push( vertex );
  19742. uvs.push( new THREE.Vector2( ( vertex.x / outerRadius + 1 ) / 2, ( vertex.y / outerRadius + 1 ) / 2 ) );
  19743. }
  19744. radius += radiusStep;
  19745. }
  19746. var n = new THREE.Vector3( 0, 0, 1 );
  19747. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  19748. var thetaSegment = i * thetaSegments;
  19749. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19750. var segment = o + thetaSegment;
  19751. var v1 = segment + i;
  19752. var v2 = segment + thetaSegments + i;
  19753. var v3 = segment + thetaSegments + 1 + i;
  19754. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19755. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19756. v1 = segment + i;
  19757. v2 = segment + thetaSegments + 1 + i;
  19758. v3 = segment + 1 + i;
  19759. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  19760. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  19761. }
  19762. }
  19763. this.computeCentroids();
  19764. this.computeFaceNormals();
  19765. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19766. };
  19767. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19768. /**
  19769. * @author mrdoob / http://mrdoob.com/
  19770. */
  19771. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19772. THREE.Geometry.call( this );
  19773. this.radius = radius = radius || 50;
  19774. this.widthSegments = widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19775. this.heightSegments = heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19776. this.phiStart = phiStart = phiStart !== undefined ? phiStart : 0;
  19777. this.phiLength = phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19778. this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19779. this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19780. var x, y, vertices = [], uvs = [];
  19781. for ( y = 0; y <= heightSegments; y ++ ) {
  19782. var verticesRow = [];
  19783. var uvsRow = [];
  19784. for ( x = 0; x <= widthSegments; x ++ ) {
  19785. var u = x / widthSegments;
  19786. var v = y / heightSegments;
  19787. var vertex = new THREE.Vector3();
  19788. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19789. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  19790. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19791. this.vertices.push( vertex );
  19792. verticesRow.push( this.vertices.length - 1 );
  19793. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19794. }
  19795. vertices.push( verticesRow );
  19796. uvs.push( uvsRow );
  19797. }
  19798. for ( y = 0; y < this.heightSegments; y ++ ) {
  19799. for ( x = 0; x < this.widthSegments; x ++ ) {
  19800. var v1 = vertices[ y ][ x + 1 ];
  19801. var v2 = vertices[ y ][ x ];
  19802. var v3 = vertices[ y + 1 ][ x ];
  19803. var v4 = vertices[ y + 1 ][ x + 1 ];
  19804. var n1 = this.vertices[ v1 ].clone().normalize();
  19805. var n2 = this.vertices[ v2 ].clone().normalize();
  19806. var n3 = this.vertices[ v3 ].clone().normalize();
  19807. var n4 = this.vertices[ v4 ].clone().normalize();
  19808. var uv1 = uvs[ y ][ x + 1 ].clone();
  19809. var uv2 = uvs[ y ][ x ].clone();
  19810. var uv3 = uvs[ y + 1 ][ x ].clone();
  19811. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19812. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  19813. uv1.x = ( uv1.x + uv2.x ) / 2;
  19814. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19815. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19816. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  19817. uv3.x = ( uv3.x + uv4.x ) / 2;
  19818. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19819. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19820. } else {
  19821. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  19822. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  19823. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  19824. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  19825. }
  19826. }
  19827. }
  19828. this.computeCentroids();
  19829. this.computeFaceNormals();
  19830. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19831. };
  19832. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19833. /**
  19834. * @author zz85 / http://www.lab4games.net/zz85/blog
  19835. * @author alteredq / http://alteredqualia.com/
  19836. *
  19837. * For creating 3D text geometry in three.js
  19838. *
  19839. * Text = 3D Text
  19840. *
  19841. * parameters = {
  19842. * size: <float>, // size of the text
  19843. * height: <float>, // thickness to extrude text
  19844. * curveSegments: <int>, // number of points on the curves
  19845. *
  19846. * font: <string>, // font name
  19847. * weight: <string>, // font weight (normal, bold)
  19848. * style: <string>, // font style (normal, italics)
  19849. *
  19850. * bevelEnabled: <bool>, // turn on bevel
  19851. * bevelThickness: <float>, // how deep into text bevel goes
  19852. * bevelSize: <float>, // how far from text outline is bevel
  19853. * }
  19854. *
  19855. */
  19856. /* Usage Examples
  19857. // TextGeometry wrapper
  19858. var text3d = new TextGeometry( text, options );
  19859. // Complete manner
  19860. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19861. var text3d = new ExtrudeGeometry( textShapes, options );
  19862. */
  19863. THREE.TextGeometry = function ( text, parameters ) {
  19864. parameters = parameters || {};
  19865. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19866. // translate parameters to ExtrudeGeometry API
  19867. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19868. // defaults
  19869. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19870. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19871. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19872. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19873. };
  19874. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19875. /**
  19876. * @author oosmoxiecode
  19877. * @author mrdoob / http://mrdoob.com/
  19878. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19879. */
  19880. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19881. THREE.Geometry.call( this );
  19882. var scope = this;
  19883. this.radius = radius || 100;
  19884. this.tube = tube || 40;
  19885. this.radialSegments = radialSegments || 8;
  19886. this.tubularSegments = tubularSegments || 6;
  19887. this.arc = arc || Math.PI * 2;
  19888. var center = new THREE.Vector3(), uvs = [], normals = [];
  19889. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  19890. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  19891. var u = i / this.tubularSegments * this.arc;
  19892. var v = j / this.radialSegments * Math.PI * 2;
  19893. center.x = this.radius * Math.cos( u );
  19894. center.y = this.radius * Math.sin( u );
  19895. var vertex = new THREE.Vector3();
  19896. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  19897. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  19898. vertex.z = this.tube * Math.sin( v );
  19899. this.vertices.push( vertex );
  19900. uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
  19901. normals.push( vertex.clone().sub( center ).normalize() );
  19902. }
  19903. }
  19904. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  19905. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  19906. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  19907. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19908. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  19909. var d = ( this.tubularSegments + 1 ) * j + i;
  19910. var face = new THREE.Face3( a, b, d, [ normals[ a ].clone(), normals[ b ].clone(), normals[ d ].clone() ] );
  19911. this.faces.push( face );
  19912. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] );
  19913. face = new THREE.Face3( b, c, d, [ normals[ b ].clone(), normals[ c ].clone(), normals[ d ].clone() ] );
  19914. this.faces.push( face );
  19915. this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19916. }
  19917. }
  19918. this.computeCentroids();
  19919. this.computeFaceNormals();
  19920. };
  19921. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19922. /**
  19923. * @author oosmoxiecode
  19924. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19925. */
  19926. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19927. THREE.Geometry.call( this );
  19928. var scope = this;
  19929. this.radius = radius || 100;
  19930. this.tube = tube || 40;
  19931. this.radialSegments = radialSegments || 64;
  19932. this.tubularSegments = tubularSegments || 8;
  19933. this.p = p || 2;
  19934. this.q = q || 3;
  19935. this.heightScale = heightScale || 1;
  19936. this.grid = new Array( this.radialSegments );
  19937. var tang = new THREE.Vector3();
  19938. var n = new THREE.Vector3();
  19939. var bitan = new THREE.Vector3();
  19940. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19941. this.grid[ i ] = new Array( this.tubularSegments );
  19942. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  19943. var p1 = getPos( u, this.q, this.p, this.radius, this.heightScale );
  19944. var p2 = getPos( u + 0.01, this.q, this.p, this.radius, this.heightScale );
  19945. tang.subVectors( p2, p1 );
  19946. n.addVectors( p2, p1 );
  19947. bitan.crossVectors( tang, n );
  19948. n.crossVectors( bitan, tang );
  19949. bitan.normalize();
  19950. n.normalize();
  19951. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19952. var v = j / this.tubularSegments * 2 * Math.PI;
  19953. var cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19954. var cy = this.tube * Math.sin( v );
  19955. var pos = new THREE.Vector3();
  19956. pos.x = p1.x + cx * n.x + cy * bitan.x;
  19957. pos.y = p1.y + cx * n.y + cy * bitan.y;
  19958. pos.z = p1.z + cx * n.z + cy * bitan.z;
  19959. this.grid[ i ][ j ] = scope.vertices.push( pos ) - 1;
  19960. }
  19961. }
  19962. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19963. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19964. var ip = ( i + 1 ) % this.radialSegments;
  19965. var jp = ( j + 1 ) % this.tubularSegments;
  19966. var a = this.grid[ i ][ j ];
  19967. var b = this.grid[ ip ][ j ];
  19968. var c = this.grid[ ip ][ jp ];
  19969. var d = this.grid[ i ][ jp ];
  19970. var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
  19971. var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  19972. var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19973. var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19974. this.faces.push( new THREE.Face3( a, b, d ) );
  19975. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19976. this.faces.push( new THREE.Face3( b, c, d ) );
  19977. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19978. }
  19979. }
  19980. this.computeCentroids();
  19981. this.computeFaceNormals();
  19982. this.computeVertexNormals();
  19983. function getPos( u, in_q, in_p, radius, heightScale ) {
  19984. var cu = Math.cos( u );
  19985. var su = Math.sin( u );
  19986. var quOverP = in_q / in_p * u;
  19987. var cs = Math.cos( quOverP );
  19988. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19989. var ty = radius * ( 2 + cs ) * su * 0.5;
  19990. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19991. return new THREE.Vector3( tx, ty, tz );
  19992. }
  19993. };
  19994. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19995. /**
  19996. * @author WestLangley / https://github.com/WestLangley
  19997. * @author zz85 / https://github.com/zz85
  19998. * @author miningold / https://github.com/miningold
  19999. *
  20000. * Modified from the TorusKnotGeometry by @oosmoxiecode
  20001. *
  20002. * Creates a tube which extrudes along a 3d spline
  20003. *
  20004. * Uses parallel transport frames as described in
  20005. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  20006. */
  20007. THREE.TubeGeometry = function( path, segments, radius, radialSegments, closed ) {
  20008. THREE.Geometry.call( this );
  20009. this.path = path;
  20010. this.segments = segments || 64;
  20011. this.radius = radius || 1;
  20012. this.radialSegments = radialSegments || 8;
  20013. this.closed = closed || false;
  20014. this.grid = [];
  20015. var scope = this,
  20016. tangent,
  20017. normal,
  20018. binormal,
  20019. numpoints = this.segments + 1,
  20020. x, y, z,
  20021. tx, ty, tz,
  20022. u, v,
  20023. cx, cy,
  20024. pos, pos2 = new THREE.Vector3(),
  20025. i, j,
  20026. ip, jp,
  20027. a, b, c, d,
  20028. uva, uvb, uvc, uvd;
  20029. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  20030. tangents = frames.tangents,
  20031. normals = frames.normals,
  20032. binormals = frames.binormals;
  20033. // proxy internals
  20034. this.tangents = tangents;
  20035. this.normals = normals;
  20036. this.binormals = binormals;
  20037. function vert( x, y, z ) {
  20038. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  20039. }
  20040. // consruct the grid
  20041. for ( i = 0; i < numpoints; i++ ) {
  20042. this.grid[ i ] = [];
  20043. u = i / ( numpoints - 1 );
  20044. pos = path.getPointAt( u );
  20045. tangent = tangents[ i ];
  20046. normal = normals[ i ];
  20047. binormal = binormals[ i ];
  20048. for ( j = 0; j < this.radialSegments; j++ ) {
  20049. v = j / this.radialSegments * 2 * Math.PI;
  20050. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  20051. cy = this.radius * Math.sin( v );
  20052. pos2.copy( pos );
  20053. pos2.x += cx * normal.x + cy * binormal.x;
  20054. pos2.y += cx * normal.y + cy * binormal.y;
  20055. pos2.z += cx * normal.z + cy * binormal.z;
  20056. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  20057. }
  20058. }
  20059. // construct the mesh
  20060. for ( i = 0; i < this.segments; i++ ) {
  20061. for ( j = 0; j < this.radialSegments; j++ ) {
  20062. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  20063. jp = (j + 1) % this.radialSegments;
  20064. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  20065. b = this.grid[ ip ][ j ];
  20066. c = this.grid[ ip ][ jp ];
  20067. d = this.grid[ i ][ jp ];
  20068. uva = new THREE.Vector2( i / this.segments, j / this.radialSegments );
  20069. uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radialSegments );
  20070. uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radialSegments );
  20071. uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radialSegments );
  20072. this.faces.push( new THREE.Face3( a, b, d ) );
  20073. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  20074. this.faces.push( new THREE.Face3( b, c, d ) );
  20075. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  20076. }
  20077. }
  20078. this.computeCentroids();
  20079. this.computeFaceNormals();
  20080. this.computeVertexNormals();
  20081. };
  20082. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20083. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  20084. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  20085. var tangent = new THREE.Vector3(),
  20086. normal = new THREE.Vector3(),
  20087. binormal = new THREE.Vector3(),
  20088. tangents = [],
  20089. normals = [],
  20090. binormals = [],
  20091. vec = new THREE.Vector3(),
  20092. mat = new THREE.Matrix4(),
  20093. numpoints = segments + 1,
  20094. theta,
  20095. epsilon = 0.0001,
  20096. smallest,
  20097. tx, ty, tz,
  20098. i, u, v;
  20099. // expose internals
  20100. this.tangents = tangents;
  20101. this.normals = normals;
  20102. this.binormals = binormals;
  20103. // compute the tangent vectors for each segment on the path
  20104. for ( i = 0; i < numpoints; i++ ) {
  20105. u = i / ( numpoints - 1 );
  20106. tangents[ i ] = path.getTangentAt( u );
  20107. tangents[ i ].normalize();
  20108. }
  20109. initialNormal3();
  20110. function initialNormal1(lastBinormal) {
  20111. // fixed start binormal. Has dangers of 0 vectors
  20112. normals[ 0 ] = new THREE.Vector3();
  20113. binormals[ 0 ] = new THREE.Vector3();
  20114. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  20115. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  20116. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20117. }
  20118. function initialNormal2() {
  20119. // This uses the Frenet-Serret formula for deriving binormal
  20120. var t2 = path.getTangentAt( epsilon );
  20121. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  20122. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  20123. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  20124. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20125. }
  20126. function initialNormal3() {
  20127. // select an initial normal vector perpenicular to the first tangent vector,
  20128. // and in the direction of the smallest tangent xyz component
  20129. normals[ 0 ] = new THREE.Vector3();
  20130. binormals[ 0 ] = new THREE.Vector3();
  20131. smallest = Number.MAX_VALUE;
  20132. tx = Math.abs( tangents[ 0 ].x );
  20133. ty = Math.abs( tangents[ 0 ].y );
  20134. tz = Math.abs( tangents[ 0 ].z );
  20135. if ( tx <= smallest ) {
  20136. smallest = tx;
  20137. normal.set( 1, 0, 0 );
  20138. }
  20139. if ( ty <= smallest ) {
  20140. smallest = ty;
  20141. normal.set( 0, 1, 0 );
  20142. }
  20143. if ( tz <= smallest ) {
  20144. normal.set( 0, 0, 1 );
  20145. }
  20146. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  20147. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  20148. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  20149. }
  20150. // compute the slowly-varying normal and binormal vectors for each segment on the path
  20151. for ( i = 1; i < numpoints; i++ ) {
  20152. normals[ i ] = normals[ i-1 ].clone();
  20153. binormals[ i ] = binormals[ i-1 ].clone();
  20154. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  20155. if ( vec.length() > epsilon ) {
  20156. vec.normalize();
  20157. theta = Math.acos( THREE.Math.clamp( tangents[ i-1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  20158. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  20159. }
  20160. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20161. }
  20162. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  20163. if ( closed ) {
  20164. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints-1 ] ), -1, 1 ) );
  20165. theta /= ( numpoints - 1 );
  20166. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  20167. theta = -theta;
  20168. }
  20169. for ( i = 1; i < numpoints; i++ ) {
  20170. // twist a little...
  20171. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  20172. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20173. }
  20174. }
  20175. };
  20176. /**
  20177. * @author clockworkgeek / https://github.com/clockworkgeek
  20178. * @author timothypratley / https://github.com/timothypratley
  20179. * @author WestLangley / http://github.com/WestLangley
  20180. */
  20181. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  20182. THREE.Geometry.call( this );
  20183. radius = radius || 1;
  20184. detail = detail || 0;
  20185. var that = this;
  20186. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  20187. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  20188. }
  20189. var midpoints = [], p = this.vertices;
  20190. var f = [];
  20191. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20192. var v1 = p[ faces[ i ][ 0 ] ];
  20193. var v2 = p[ faces[ i ][ 1 ] ];
  20194. var v3 = p[ faces[ i ][ 2 ] ];
  20195. f[ i ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  20196. }
  20197. for ( var i = 0, l = f.length; i < l; i ++ ) {
  20198. subdivide(f[ i ], detail);
  20199. }
  20200. // Handle case when face straddles the seam
  20201. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  20202. var uvs = this.faceVertexUvs[ 0 ][ i ];
  20203. var x0 = uvs[ 0 ].x;
  20204. var x1 = uvs[ 1 ].x;
  20205. var x2 = uvs[ 2 ].x;
  20206. var max = Math.max( x0, Math.max( x1, x2 ) );
  20207. var min = Math.min( x0, Math.min( x1, x2 ) );
  20208. if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
  20209. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  20210. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  20211. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  20212. }
  20213. }
  20214. // Apply radius
  20215. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  20216. this.vertices[ i ].multiplyScalar( radius );
  20217. }
  20218. // Merge vertices
  20219. this.mergeVertices();
  20220. this.computeCentroids();
  20221. this.computeFaceNormals();
  20222. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  20223. // Project vector onto sphere's surface
  20224. function prepare( vector ) {
  20225. var vertex = vector.normalize().clone();
  20226. vertex.index = that.vertices.push( vertex ) - 1;
  20227. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  20228. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  20229. var v = inclination( vector ) / Math.PI + 0.5;
  20230. vertex.uv = new THREE.Vector2( u, 1 - v );
  20231. return vertex;
  20232. }
  20233. // Approximate a curved face with recursively sub-divided triangles.
  20234. function make( v1, v2, v3 ) {
  20235. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  20236. face.centroid.add( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  20237. that.faces.push( face );
  20238. var azi = azimuth( face.centroid );
  20239. that.faceVertexUvs[ 0 ].push( [
  20240. correctUV( v1.uv, v1, azi ),
  20241. correctUV( v2.uv, v2, azi ),
  20242. correctUV( v3.uv, v3, azi )
  20243. ] );
  20244. }
  20245. // Analytically subdivide a face to the required detail level.
  20246. function subdivide(face, detail ) {
  20247. var cols = Math.pow(2, detail);
  20248. var cells = Math.pow(4, detail);
  20249. var a = prepare( that.vertices[ face.a ] );
  20250. var b = prepare( that.vertices[ face.b ] );
  20251. var c = prepare( that.vertices[ face.c ] );
  20252. var v = [];
  20253. // Construct all of the vertices for this subdivision.
  20254. for ( var i = 0 ; i <= cols; i ++ ) {
  20255. v[ i ] = [];
  20256. var aj = prepare( a.clone().lerp( c, i / cols ) );
  20257. var bj = prepare( b.clone().lerp( c, i / cols ) );
  20258. var rows = cols - i;
  20259. for ( var j = 0; j <= rows; j ++) {
  20260. if ( j == 0 && i == cols ) {
  20261. v[ i ][ j ] = aj;
  20262. } else {
  20263. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  20264. }
  20265. }
  20266. }
  20267. // Construct all of the faces.
  20268. for ( var i = 0; i < cols ; i ++ ) {
  20269. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  20270. var k = Math.floor( j / 2 );
  20271. if ( j % 2 == 0 ) {
  20272. make(
  20273. v[ i ][ k + 1],
  20274. v[ i + 1 ][ k ],
  20275. v[ i ][ k ]
  20276. );
  20277. } else {
  20278. make(
  20279. v[ i ][ k + 1 ],
  20280. v[ i + 1][ k + 1],
  20281. v[ i + 1 ][ k ]
  20282. );
  20283. }
  20284. }
  20285. }
  20286. }
  20287. // Angle around the Y axis, counter-clockwise when looking from above.
  20288. function azimuth( vector ) {
  20289. return Math.atan2( vector.z, -vector.x );
  20290. }
  20291. // Angle above the XZ plane.
  20292. function inclination( vector ) {
  20293. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20294. }
  20295. // Texture fixing helper. Spheres have some odd behaviours.
  20296. function correctUV( uv, vector, azimuth ) {
  20297. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  20298. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  20299. return uv.clone();
  20300. }
  20301. };
  20302. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20303. /**
  20304. * @author timothypratley / https://github.com/timothypratley
  20305. */
  20306. THREE.IcosahedronGeometry = function ( radius, detail ) {
  20307. this.radius = radius;
  20308. this.detail = detail;
  20309. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20310. var vertices = [
  20311. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  20312. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  20313. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  20314. ];
  20315. var faces = [
  20316. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  20317. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  20318. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  20319. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  20320. ];
  20321. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20322. };
  20323. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20324. /**
  20325. * @author timothypratley / https://github.com/timothypratley
  20326. */
  20327. THREE.OctahedronGeometry = function ( radius, detail ) {
  20328. var vertices = [
  20329. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  20330. ];
  20331. var faces = [
  20332. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  20333. ];
  20334. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20335. };
  20336. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20337. /**
  20338. * @author timothypratley / https://github.com/timothypratley
  20339. */
  20340. THREE.TetrahedronGeometry = function ( radius, detail ) {
  20341. var vertices = [
  20342. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  20343. ];
  20344. var faces = [
  20345. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  20346. ];
  20347. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20348. };
  20349. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20350. /**
  20351. * @author zz85 / https://github.com/zz85
  20352. * Parametric Surfaces Geometry
  20353. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  20354. *
  20355. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  20356. *
  20357. */
  20358. THREE.ParametricGeometry = function ( func, slices, stacks ) {
  20359. THREE.Geometry.call( this );
  20360. var verts = this.vertices;
  20361. var faces = this.faces;
  20362. var uvs = this.faceVertexUvs[ 0 ];
  20363. var i, il, j, p;
  20364. var u, v;
  20365. var stackCount = stacks + 1;
  20366. var sliceCount = slices + 1;
  20367. for ( i = 0; i <= stacks; i ++ ) {
  20368. v = i / stacks;
  20369. for ( j = 0; j <= slices; j ++ ) {
  20370. u = j / slices;
  20371. p = func( u, v );
  20372. verts.push( p );
  20373. }
  20374. }
  20375. var a, b, c, d;
  20376. var uva, uvb, uvc, uvd;
  20377. for ( i = 0; i < stacks; i ++ ) {
  20378. for ( j = 0; j < slices; j ++ ) {
  20379. a = i * sliceCount + j;
  20380. b = i * sliceCount + j + 1;
  20381. c = (i + 1) * sliceCount + j + 1;
  20382. d = (i + 1) * sliceCount + j;
  20383. uva = new THREE.Vector2( j / slices, i / stacks );
  20384. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  20385. uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  20386. uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  20387. faces.push( new THREE.Face3( a, b, d ) );
  20388. uvs.push( [ uva, uvb, uvd ] );
  20389. faces.push( new THREE.Face3( b, c, d ) );
  20390. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  20391. }
  20392. }
  20393. // console.log(this);
  20394. // magic bullet
  20395. // var diff = this.mergeVertices();
  20396. // console.log('removed ', diff, ' vertices by merging');
  20397. this.computeCentroids();
  20398. this.computeFaceNormals();
  20399. this.computeVertexNormals();
  20400. };
  20401. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20402. /**
  20403. * @author sroucheray / http://sroucheray.org/
  20404. * @author mrdoob / http://mrdoob.com/
  20405. */
  20406. THREE.AxisHelper = function ( size ) {
  20407. size = size || 1;
  20408. var geometry = new THREE.Geometry();
  20409. geometry.vertices.push(
  20410. new THREE.Vector3(), new THREE.Vector3( size, 0, 0 ),
  20411. new THREE.Vector3(), new THREE.Vector3( 0, size, 0 ),
  20412. new THREE.Vector3(), new THREE.Vector3( 0, 0, size )
  20413. );
  20414. geometry.colors.push(
  20415. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  20416. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  20417. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  20418. );
  20419. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20420. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20421. };
  20422. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20423. /**
  20424. * @author WestLangley / http://github.com/WestLangley
  20425. * @author zz85 / http://github.com/zz85
  20426. * @author bhouston / http://exocortex.com
  20427. *
  20428. * Creates an arrow for visualizing directions
  20429. *
  20430. * Parameters:
  20431. * dir - Vector3
  20432. * origin - Vector3
  20433. * length - Number
  20434. * hex - color in hex value
  20435. * headLength - Number
  20436. * headWidth - Number
  20437. */
  20438. THREE.ArrowHelper = function ( dir, origin, length, hex, headLength, headWidth ) {
  20439. // dir is assumed to be normalized
  20440. THREE.Object3D.call( this );
  20441. if ( hex === undefined ) hex = 0xffff00;
  20442. if ( length === undefined ) length = 1;
  20443. if ( headLength === undefined ) headLength = 0.2 * length;
  20444. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  20445. this.position = origin;
  20446. var lineGeometry = new THREE.Geometry();
  20447. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  20448. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  20449. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  20450. this.line.matrixAutoUpdate = false;
  20451. this.add( this.line );
  20452. var coneGeometry = new THREE.CylinderGeometry( 0, 0.5, 1, 5, 1 );
  20453. coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) );
  20454. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  20455. this.cone.matrixAutoUpdate = false;
  20456. this.add( this.cone );
  20457. this.setDirection( dir );
  20458. this.setLength( length, headLength, headWidth );
  20459. };
  20460. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20461. THREE.ArrowHelper.prototype.setDirection = function () {
  20462. var axis = new THREE.Vector3();
  20463. var radians;
  20464. return function ( dir ) {
  20465. // dir is assumed to be normalized
  20466. if ( dir.y > 0.99999 ) {
  20467. this.quaternion.set( 0, 0, 0, 1 );
  20468. } else if ( dir.y < - 0.99999 ) {
  20469. this.quaternion.set( 1, 0, 0, 0 );
  20470. } else {
  20471. axis.set( dir.z, 0, - dir.x ).normalize();
  20472. radians = Math.acos( dir.y );
  20473. this.quaternion.setFromAxisAngle( axis, radians );
  20474. }
  20475. };
  20476. }();
  20477. THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  20478. if ( headLength === undefined ) headLength = 0.2 * length;
  20479. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  20480. this.line.scale.set( 1, length, 1 );
  20481. this.line.updateMatrix();
  20482. this.cone.scale.set( headWidth, headLength, headWidth );
  20483. this.cone.position.y = length;
  20484. this.cone.updateMatrix();
  20485. };
  20486. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  20487. this.line.material.color.setHex( hex );
  20488. this.cone.material.color.setHex( hex );
  20489. };
  20490. /**
  20491. * @author mrdoob / http://mrdoob.com/
  20492. */
  20493. THREE.BoxHelper = function ( object ) {
  20494. // 5____4
  20495. // 1/___0/|
  20496. // | 6__|_7
  20497. // 2/___3/
  20498. var vertices = [
  20499. new THREE.Vector3( 1, 1, 1 ),
  20500. new THREE.Vector3( - 1, 1, 1 ),
  20501. new THREE.Vector3( - 1, - 1, 1 ),
  20502. new THREE.Vector3( 1, - 1, 1 ),
  20503. new THREE.Vector3( 1, 1, - 1 ),
  20504. new THREE.Vector3( - 1, 1, - 1 ),
  20505. new THREE.Vector3( - 1, - 1, - 1 ),
  20506. new THREE.Vector3( 1, - 1, - 1 )
  20507. ];
  20508. this.vertices = vertices;
  20509. // TODO: Wouldn't be nice if Line had .segments?
  20510. var geometry = new THREE.Geometry();
  20511. geometry.vertices.push(
  20512. vertices[ 0 ], vertices[ 1 ],
  20513. vertices[ 1 ], vertices[ 2 ],
  20514. vertices[ 2 ], vertices[ 3 ],
  20515. vertices[ 3 ], vertices[ 0 ],
  20516. vertices[ 4 ], vertices[ 5 ],
  20517. vertices[ 5 ], vertices[ 6 ],
  20518. vertices[ 6 ], vertices[ 7 ],
  20519. vertices[ 7 ], vertices[ 4 ],
  20520. vertices[ 0 ], vertices[ 4 ],
  20521. vertices[ 1 ], vertices[ 5 ],
  20522. vertices[ 2 ], vertices[ 6 ],
  20523. vertices[ 3 ], vertices[ 7 ]
  20524. );
  20525. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces );
  20526. if ( object !== undefined ) {
  20527. this.update( object );
  20528. }
  20529. };
  20530. THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype );
  20531. THREE.BoxHelper.prototype.update = function ( object ) {
  20532. var geometry = object.geometry;
  20533. if ( geometry.boundingBox === null ) {
  20534. geometry.computeBoundingBox();
  20535. }
  20536. var min = geometry.boundingBox.min;
  20537. var max = geometry.boundingBox.max;
  20538. var vertices = this.vertices;
  20539. vertices[ 0 ].set( max.x, max.y, max.z );
  20540. vertices[ 1 ].set( min.x, max.y, max.z );
  20541. vertices[ 2 ].set( min.x, min.y, max.z );
  20542. vertices[ 3 ].set( max.x, min.y, max.z );
  20543. vertices[ 4 ].set( max.x, max.y, min.z );
  20544. vertices[ 5 ].set( min.x, max.y, min.z );
  20545. vertices[ 6 ].set( min.x, min.y, min.z );
  20546. vertices[ 7 ].set( max.x, min.y, min.z );
  20547. this.geometry.computeBoundingSphere();
  20548. this.geometry.verticesNeedUpdate = true;
  20549. this.matrixAutoUpdate = false;
  20550. this.matrixWorld = object.matrixWorld;
  20551. };
  20552. /**
  20553. * @author WestLangley / http://github.com/WestLangley
  20554. */
  20555. // a helper to show the world-axis-aligned bounding box for an object
  20556. THREE.BoundingBoxHelper = function ( object, hex ) {
  20557. var color = ( hex !== undefined ) ? hex : 0x888888;
  20558. this.object = object;
  20559. this.box = new THREE.Box3();
  20560. THREE.Mesh.call( this, new THREE.CubeGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  20561. };
  20562. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  20563. THREE.BoundingBoxHelper.prototype.update = function () {
  20564. this.box.setFromObject( this.object );
  20565. this.box.size( this.scale );
  20566. this.box.center( this.position );
  20567. };
  20568. /**
  20569. * @author alteredq / http://alteredqualia.com/
  20570. *
  20571. * - shows frustum, line of sight and up of the camera
  20572. * - suitable for fast updates
  20573. * - based on frustum visualization in lightgl.js shadowmap example
  20574. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20575. */
  20576. THREE.CameraHelper = function ( camera ) {
  20577. var geometry = new THREE.Geometry();
  20578. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20579. var pointMap = {};
  20580. // colors
  20581. var hexFrustum = 0xffaa00;
  20582. var hexCone = 0xff0000;
  20583. var hexUp = 0x00aaff;
  20584. var hexTarget = 0xffffff;
  20585. var hexCross = 0x333333;
  20586. // near
  20587. addLine( "n1", "n2", hexFrustum );
  20588. addLine( "n2", "n4", hexFrustum );
  20589. addLine( "n4", "n3", hexFrustum );
  20590. addLine( "n3", "n1", hexFrustum );
  20591. // far
  20592. addLine( "f1", "f2", hexFrustum );
  20593. addLine( "f2", "f4", hexFrustum );
  20594. addLine( "f4", "f3", hexFrustum );
  20595. addLine( "f3", "f1", hexFrustum );
  20596. // sides
  20597. addLine( "n1", "f1", hexFrustum );
  20598. addLine( "n2", "f2", hexFrustum );
  20599. addLine( "n3", "f3", hexFrustum );
  20600. addLine( "n4", "f4", hexFrustum );
  20601. // cone
  20602. addLine( "p", "n1", hexCone );
  20603. addLine( "p", "n2", hexCone );
  20604. addLine( "p", "n3", hexCone );
  20605. addLine( "p", "n4", hexCone );
  20606. // up
  20607. addLine( "u1", "u2", hexUp );
  20608. addLine( "u2", "u3", hexUp );
  20609. addLine( "u3", "u1", hexUp );
  20610. // target
  20611. addLine( "c", "t", hexTarget );
  20612. addLine( "p", "c", hexCross );
  20613. // cross
  20614. addLine( "cn1", "cn2", hexCross );
  20615. addLine( "cn3", "cn4", hexCross );
  20616. addLine( "cf1", "cf2", hexCross );
  20617. addLine( "cf3", "cf4", hexCross );
  20618. function addLine( a, b, hex ) {
  20619. addPoint( a, hex );
  20620. addPoint( b, hex );
  20621. }
  20622. function addPoint( id, hex ) {
  20623. geometry.vertices.push( new THREE.Vector3() );
  20624. geometry.colors.push( new THREE.Color( hex ) );
  20625. if ( pointMap[ id ] === undefined ) {
  20626. pointMap[ id ] = [];
  20627. }
  20628. pointMap[ id ].push( geometry.vertices.length - 1 );
  20629. }
  20630. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20631. this.camera = camera;
  20632. this.matrixWorld = camera.matrixWorld;
  20633. this.matrixAutoUpdate = false;
  20634. this.pointMap = pointMap;
  20635. this.update();
  20636. };
  20637. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20638. THREE.CameraHelper.prototype.update = function () {
  20639. var vector = new THREE.Vector3();
  20640. var camera = new THREE.Camera();
  20641. var projector = new THREE.Projector();
  20642. return function () {
  20643. var scope = this;
  20644. var w = 1, h = 1;
  20645. // we need just camera projection matrix
  20646. // world matrix must be identity
  20647. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  20648. // center / target
  20649. setPoint( "c", 0, 0, -1 );
  20650. setPoint( "t", 0, 0, 1 );
  20651. // near
  20652. setPoint( "n1", -w, -h, -1 );
  20653. setPoint( "n2", w, -h, -1 );
  20654. setPoint( "n3", -w, h, -1 );
  20655. setPoint( "n4", w, h, -1 );
  20656. // far
  20657. setPoint( "f1", -w, -h, 1 );
  20658. setPoint( "f2", w, -h, 1 );
  20659. setPoint( "f3", -w, h, 1 );
  20660. setPoint( "f4", w, h, 1 );
  20661. // up
  20662. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  20663. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  20664. setPoint( "u3", 0, h * 2, -1 );
  20665. // cross
  20666. setPoint( "cf1", -w, 0, 1 );
  20667. setPoint( "cf2", w, 0, 1 );
  20668. setPoint( "cf3", 0, -h, 1 );
  20669. setPoint( "cf4", 0, h, 1 );
  20670. setPoint( "cn1", -w, 0, -1 );
  20671. setPoint( "cn2", w, 0, -1 );
  20672. setPoint( "cn3", 0, -h, -1 );
  20673. setPoint( "cn4", 0, h, -1 );
  20674. function setPoint( point, x, y, z ) {
  20675. vector.set( x, y, z );
  20676. projector.unprojectVector( vector, camera );
  20677. var points = scope.pointMap[ point ];
  20678. if ( points !== undefined ) {
  20679. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20680. scope.geometry.vertices[ points[ i ] ].copy( vector );
  20681. }
  20682. }
  20683. }
  20684. this.geometry.verticesNeedUpdate = true;
  20685. };
  20686. }();
  20687. /**
  20688. * @author alteredq / http://alteredqualia.com/
  20689. * @author mrdoob / http://mrdoob.com/
  20690. * @author WestLangley / http://github.com/WestLangley
  20691. */
  20692. THREE.DirectionalLightHelper = function ( light, size ) {
  20693. THREE.Object3D.call( this );
  20694. this.light = light;
  20695. this.light.updateMatrixWorld();
  20696. this.matrixWorld = light.matrixWorld;
  20697. this.matrixAutoUpdate = false;
  20698. size = size || 1;
  20699. var geometry = new THREE.PlaneGeometry( size, size );
  20700. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20701. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20702. this.lightPlane = new THREE.Mesh( geometry, material );
  20703. this.add( this.lightPlane );
  20704. geometry = new THREE.Geometry();
  20705. geometry.vertices.push( new THREE.Vector3() );
  20706. geometry.vertices.push( new THREE.Vector3() );
  20707. material = new THREE.LineBasicMaterial( { fog: false } );
  20708. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20709. this.targetLine = new THREE.Line( geometry, material );
  20710. this.add( this.targetLine );
  20711. this.update();
  20712. };
  20713. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20714. THREE.DirectionalLightHelper.prototype.dispose = function () {
  20715. this.lightPlane.geometry.dispose();
  20716. this.lightPlane.material.dispose();
  20717. this.targetLine.geometry.dispose();
  20718. this.targetLine.material.dispose();
  20719. };
  20720. THREE.DirectionalLightHelper.prototype.update = function () {
  20721. var v1 = new THREE.Vector3();
  20722. var v2 = new THREE.Vector3();
  20723. var v3 = new THREE.Vector3();
  20724. return function () {
  20725. v1.setFromMatrixPosition( this.light.matrixWorld );
  20726. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  20727. v3.subVectors( v2, v1 );
  20728. this.lightPlane.lookAt( v3 );
  20729. this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20730. this.targetLine.geometry.vertices[ 1 ].copy( v3 );
  20731. this.targetLine.geometry.verticesNeedUpdate = true;
  20732. this.targetLine.material.color.copy( this.lightPlane.material.color );
  20733. }
  20734. }();
  20735. /**
  20736. * @author WestLangley / http://github.com/WestLangley
  20737. */
  20738. THREE.EdgesHelper = function ( object, hex ) {
  20739. var color = ( hex !== undefined ) ? hex : 0xffffff;
  20740. var edge = [ 0, 0 ], hash = {};
  20741. var sortFunction = function ( a, b ) { return a - b };
  20742. var keys = [ 'a', 'b', 'c' ];
  20743. var geometry = new THREE.BufferGeometry();
  20744. var geometry2 = object.geometry.clone();
  20745. geometry2.mergeVertices();
  20746. geometry2.computeFaceNormals();
  20747. var vertices = geometry2.vertices;
  20748. var faces = geometry2.faces;
  20749. var numEdges = 0;
  20750. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20751. var face = faces[ i ];
  20752. for ( var j = 0; j < 3; j ++ ) {
  20753. edge[ 0 ] = face[ keys[ j ] ];
  20754. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  20755. edge.sort( sortFunction );
  20756. var key = edge.toString();
  20757. if ( hash[ key ] === undefined ) {
  20758. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  20759. numEdges ++;
  20760. } else {
  20761. hash[ key ].face2 = i;
  20762. }
  20763. }
  20764. }
  20765. geometry.addAttribute( 'position', Float32Array, 2 * numEdges, 3 );
  20766. var coords = geometry.attributes.position.array;
  20767. var index = 0;
  20768. for ( var key in hash ) {
  20769. var h = hash[ key ];
  20770. if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) < 0.9999 ) { // hardwired const OK
  20771. var vertex = vertices[ h.vert1 ];
  20772. coords[ index ++ ] = vertex.x;
  20773. coords[ index ++ ] = vertex.y;
  20774. coords[ index ++ ] = vertex.z;
  20775. vertex = vertices[ h.vert2 ];
  20776. coords[ index ++ ] = vertex.x;
  20777. coords[ index ++ ] = vertex.y;
  20778. coords[ index ++ ] = vertex.z;
  20779. }
  20780. }
  20781. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  20782. this.matrixAutoUpdate = false;
  20783. this.matrixWorld = object.matrixWorld;
  20784. };
  20785. THREE.EdgesHelper.prototype = Object.create( THREE.Line.prototype );
  20786. /**
  20787. * @author mrdoob / http://mrdoob.com/
  20788. * @author WestLangley / http://github.com/WestLangley
  20789. */
  20790. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  20791. this.object = object;
  20792. this.size = ( size !== undefined ) ? size : 1;
  20793. var color = ( hex !== undefined ) ? hex : 0xffff00;
  20794. var width = ( linewidth !== undefined ) ? linewidth : 1;
  20795. var geometry = new THREE.Geometry();
  20796. var faces = this.object.geometry.faces;
  20797. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20798. geometry.vertices.push( new THREE.Vector3() );
  20799. geometry.vertices.push( new THREE.Vector3() );
  20800. }
  20801. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20802. this.matrixAutoUpdate = false;
  20803. this.normalMatrix = new THREE.Matrix3();
  20804. this.update();
  20805. };
  20806. THREE.FaceNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20807. THREE.FaceNormalsHelper.prototype.update = ( function ( object ) {
  20808. var v1 = new THREE.Vector3();
  20809. return function ( object ) {
  20810. this.object.updateMatrixWorld( true );
  20811. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  20812. var vertices = this.geometry.vertices;
  20813. var faces = this.object.geometry.faces;
  20814. var worldMatrix = this.object.matrixWorld;
  20815. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20816. var face = faces[ i ];
  20817. v1.copy( face.normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  20818. var idx = 2 * i;
  20819. vertices[ idx ].copy( face.centroid ).applyMatrix4( worldMatrix );
  20820. vertices[ idx + 1 ].addVectors( vertices[ idx ], v1 );
  20821. }
  20822. this.geometry.verticesNeedUpdate = true;
  20823. return this;
  20824. }
  20825. }());
  20826. /**
  20827. * @author mrdoob / http://mrdoob.com/
  20828. */
  20829. THREE.GridHelper = function ( size, step ) {
  20830. var geometry = new THREE.Geometry();
  20831. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20832. this.color1 = new THREE.Color( 0x444444 );
  20833. this.color2 = new THREE.Color( 0x888888 );
  20834. for ( var i = - size; i <= size; i += step ) {
  20835. geometry.vertices.push(
  20836. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  20837. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  20838. );
  20839. var color = i === 0 ? this.color1 : this.color2;
  20840. geometry.colors.push( color, color, color, color );
  20841. }
  20842. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20843. };
  20844. THREE.GridHelper.prototype = Object.create( THREE.Line.prototype );
  20845. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  20846. this.color1.set( colorCenterLine );
  20847. this.color2.set( colorGrid );
  20848. this.geometry.colorsNeedUpdate = true;
  20849. }
  20850. /**
  20851. * @author alteredq / http://alteredqualia.com/
  20852. * @author mrdoob / http://mrdoob.com/
  20853. */
  20854. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  20855. THREE.Object3D.call( this );
  20856. this.light = light;
  20857. this.light.updateMatrixWorld();
  20858. this.matrixWorld = light.matrixWorld;
  20859. this.matrixAutoUpdate = false;
  20860. this.colors = [ new THREE.Color(), new THREE.Color() ];
  20861. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20862. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20863. for ( var i = 0, il = 8; i < il; i ++ ) {
  20864. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  20865. }
  20866. var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } );
  20867. this.lightSphere = new THREE.Mesh( geometry, material );
  20868. this.add( this.lightSphere );
  20869. this.update();
  20870. };
  20871. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20872. THREE.HemisphereLightHelper.prototype.dispose = function () {
  20873. this.lightSphere.geometry.dispose();
  20874. this.lightSphere.material.dispose();
  20875. };
  20876. THREE.HemisphereLightHelper.prototype.update = function () {
  20877. var vector = new THREE.Vector3();
  20878. return function () {
  20879. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  20880. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  20881. this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  20882. this.lightSphere.geometry.colorsNeedUpdate = true;
  20883. }
  20884. }();
  20885. /**
  20886. * @author alteredq / http://alteredqualia.com/
  20887. * @author mrdoob / http://mrdoob.com/
  20888. */
  20889. THREE.PointLightHelper = function ( light, sphereSize ) {
  20890. this.light = light;
  20891. this.light.updateMatrixWorld();
  20892. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20893. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20894. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20895. THREE.Mesh.call( this, geometry, material );
  20896. this.matrixWorld = this.light.matrixWorld;
  20897. this.matrixAutoUpdate = false;
  20898. /*
  20899. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20900. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20901. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20902. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20903. var d = light.distance;
  20904. if ( d === 0.0 ) {
  20905. this.lightDistance.visible = false;
  20906. } else {
  20907. this.lightDistance.scale.set( d, d, d );
  20908. }
  20909. this.add( this.lightDistance );
  20910. */
  20911. };
  20912. THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  20913. THREE.PointLightHelper.prototype.dispose = function () {
  20914. this.geometry.dispose();
  20915. this.material.dispose();
  20916. };
  20917. THREE.PointLightHelper.prototype.update = function () {
  20918. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20919. /*
  20920. var d = this.light.distance;
  20921. if ( d === 0.0 ) {
  20922. this.lightDistance.visible = false;
  20923. } else {
  20924. this.lightDistance.visible = true;
  20925. this.lightDistance.scale.set( d, d, d );
  20926. }
  20927. */
  20928. };
  20929. /**
  20930. * @author alteredq / http://alteredqualia.com/
  20931. * @author mrdoob / http://mrdoob.com/
  20932. * @author WestLangley / http://github.com/WestLangley
  20933. */
  20934. THREE.SpotLightHelper = function ( light ) {
  20935. THREE.Object3D.call( this );
  20936. this.light = light;
  20937. this.light.updateMatrixWorld();
  20938. this.matrixWorld = light.matrixWorld;
  20939. this.matrixAutoUpdate = false;
  20940. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  20941. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, -0.5, 0 ) );
  20942. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  20943. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  20944. this.cone = new THREE.Mesh( geometry, material );
  20945. this.add( this.cone );
  20946. this.update();
  20947. };
  20948. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20949. THREE.SpotLightHelper.prototype.dispose = function () {
  20950. this.cone.geometry.dispose();
  20951. this.cone.material.dispose();
  20952. };
  20953. THREE.SpotLightHelper.prototype.update = function () {
  20954. var vector = new THREE.Vector3();
  20955. var vector2 = new THREE.Vector3();
  20956. return function () {
  20957. var coneLength = this.light.distance ? this.light.distance : 10000;
  20958. var coneWidth = coneLength * Math.tan( this.light.angle );
  20959. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  20960. vector.setFromMatrixPosition( this.light.matrixWorld );
  20961. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  20962. this.cone.lookAt( vector2.sub( vector ) );
  20963. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20964. };
  20965. }();
  20966. /**
  20967. * @author mrdoob / http://mrdoob.com/
  20968. * @author WestLangley / http://github.com/WestLangley
  20969. */
  20970. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  20971. this.object = object;
  20972. this.size = ( size !== undefined ) ? size : 1;
  20973. var color = ( hex !== undefined ) ? hex : 0xff0000;
  20974. var width = ( linewidth !== undefined ) ? linewidth : 1;
  20975. var geometry = new THREE.Geometry();
  20976. var vertices = object.geometry.vertices;
  20977. var faces = object.geometry.faces;
  20978. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20979. var face = faces[ i ];
  20980. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  20981. geometry.vertices.push( new THREE.Vector3() );
  20982. geometry.vertices.push( new THREE.Vector3() );
  20983. }
  20984. }
  20985. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20986. this.matrixAutoUpdate = false;
  20987. this.normalMatrix = new THREE.Matrix3();
  20988. this.update();
  20989. };
  20990. THREE.VertexNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20991. THREE.VertexNormalsHelper.prototype.update = ( function ( object ) {
  20992. var v1 = new THREE.Vector3();
  20993. return function( object ) {
  20994. var keys = [ 'a', 'b', 'c', 'd' ];
  20995. this.object.updateMatrixWorld( true );
  20996. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  20997. var vertices = this.geometry.vertices;
  20998. var verts = this.object.geometry.vertices;
  20999. var faces = this.object.geometry.faces;
  21000. var worldMatrix = this.object.matrixWorld;
  21001. var idx = 0;
  21002. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21003. var face = faces[ i ];
  21004. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  21005. var vertexId = face[ keys[ j ] ];
  21006. var vertex = verts[ vertexId ];
  21007. var normal = face.vertexNormals[ j ];
  21008. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  21009. v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  21010. v1.add( vertices[ idx ] );
  21011. idx = idx + 1;
  21012. vertices[ idx ].copy( v1 );
  21013. idx = idx + 1;
  21014. }
  21015. }
  21016. this.geometry.verticesNeedUpdate = true;
  21017. return this;
  21018. }
  21019. }());
  21020. /**
  21021. * @author mrdoob / http://mrdoob.com/
  21022. * @author WestLangley / http://github.com/WestLangley
  21023. */
  21024. THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) {
  21025. this.object = object;
  21026. this.size = ( size !== undefined ) ? size : 1;
  21027. var color = ( hex !== undefined ) ? hex : 0x0000ff;
  21028. var width = ( linewidth !== undefined ) ? linewidth : 1;
  21029. var geometry = new THREE.Geometry();
  21030. var vertices = object.geometry.vertices;
  21031. var faces = object.geometry.faces;
  21032. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21033. var face = faces[ i ];
  21034. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  21035. geometry.vertices.push( new THREE.Vector3() );
  21036. geometry.vertices.push( new THREE.Vector3() );
  21037. }
  21038. }
  21039. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21040. this.matrixAutoUpdate = false;
  21041. this.update();
  21042. };
  21043. THREE.VertexTangentsHelper.prototype = Object.create( THREE.Line.prototype );
  21044. THREE.VertexTangentsHelper.prototype.update = ( function ( object ) {
  21045. var v1 = new THREE.Vector3();
  21046. return function( object ) {
  21047. var keys = [ 'a', 'b', 'c', 'd' ];
  21048. this.object.updateMatrixWorld( true );
  21049. var vertices = this.geometry.vertices;
  21050. var verts = this.object.geometry.vertices;
  21051. var faces = this.object.geometry.faces;
  21052. var worldMatrix = this.object.matrixWorld;
  21053. var idx = 0;
  21054. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21055. var face = faces[ i ];
  21056. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  21057. var vertexId = face[ keys[ j ] ];
  21058. var vertex = verts[ vertexId ];
  21059. var tangent = face.vertexTangents[ j ];
  21060. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  21061. v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size );
  21062. v1.add( vertices[ idx ] );
  21063. idx = idx + 1;
  21064. vertices[ idx ].copy( v1 );
  21065. idx = idx + 1;
  21066. }
  21067. }
  21068. this.geometry.verticesNeedUpdate = true;
  21069. return this;
  21070. }
  21071. }());
  21072. /**
  21073. * @author mrdoob / http://mrdoob.com/
  21074. */
  21075. THREE.WireframeHelper = function ( object, hex ) {
  21076. var color = ( hex !== undefined ) ? hex : 0xffffff;
  21077. var edge = [ 0, 0 ], hash = {};
  21078. var sortFunction = function ( a, b ) { return a - b };
  21079. var keys = [ 'a', 'b', 'c' ];
  21080. var geometry = new THREE.BufferGeometry();
  21081. if ( object.geometry instanceof THREE.Geometry ) {
  21082. var vertices = object.geometry.vertices;
  21083. var faces = object.geometry.faces;
  21084. var numEdges = 0;
  21085. // allocate maximal size
  21086. var edges = new Uint32Array( 6 * faces.length );
  21087. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21088. var face = faces[ i ];
  21089. for ( var j = 0; j < 3; j ++ ) {
  21090. edge[ 0 ] = face[ keys[ j ] ];
  21091. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  21092. edge.sort( sortFunction );
  21093. var key = edge.toString();
  21094. if ( hash[ key ] === undefined ) {
  21095. edges[ 2 * numEdges ] = edge[ 0 ];
  21096. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  21097. hash[ key ] = true;
  21098. numEdges ++;
  21099. }
  21100. }
  21101. }
  21102. geometry.addAttribute( 'position', Float32Array, 2 * numEdges, 3 );
  21103. var coords = geometry.attributes.position.array;
  21104. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  21105. for ( var j = 0; j < 2; j ++ ) {
  21106. var vertex = vertices[ edges [ 2 * i + j] ];
  21107. var index = 6 * i + 3 * j;
  21108. coords[ index + 0 ] = vertex.x;
  21109. coords[ index + 1 ] = vertex.y;
  21110. coords[ index + 2 ] = vertex.z;
  21111. }
  21112. }
  21113. } else if ( object.geometry instanceof THREE.BufferGeometry && object.geometry.attributes.index !== undefined ) { // indexed BufferGeometry
  21114. var vertices = object.geometry.attributes.position.array;
  21115. var indices = object.geometry.attributes.index.array;
  21116. var offsets = object.geometry.offsets;
  21117. var numEdges = 0;
  21118. // allocate maximal size
  21119. var edges = new Uint32Array( 2 * indices.length );
  21120. for ( var o = 0, ol = offsets.length; o < ol; ++ o ) {
  21121. var start = offsets[ o ].start;
  21122. var count = offsets[ o ].count;
  21123. var index = offsets[ o ].index;
  21124. for ( var i = start, il = start + count; i < il; i += 3 ) {
  21125. for ( var j = 0; j < 3; j ++ ) {
  21126. edge[ 0 ] = index + indices[ i + j ];
  21127. edge[ 1 ] = index + indices[ i + ( j + 1 ) % 3 ];
  21128. edge.sort( sortFunction );
  21129. var key = edge.toString();
  21130. if ( hash[ key ] === undefined ) {
  21131. edges[ 2 * numEdges ] = edge[ 0 ];
  21132. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  21133. hash[ key ] = true;
  21134. numEdges ++;
  21135. }
  21136. }
  21137. }
  21138. }
  21139. geometry.addAttribute( 'position', Float32Array, 2 * numEdges, 3 );
  21140. var coords = geometry.attributes.position.array;
  21141. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  21142. for ( var j = 0; j < 2; j ++ ) {
  21143. var index = 6 * i + 3 * j;
  21144. var index2 = 3 * edges[ 2 * i + j];
  21145. coords[ index + 0 ] = vertices[ index2 ];
  21146. coords[ index + 1 ] = vertices[ index2 + 1 ];
  21147. coords[ index + 2 ] = vertices[ index2 + 2 ];
  21148. }
  21149. }
  21150. } else if ( object.geometry instanceof THREE.BufferGeometry ) { // non-indexed BufferGeometry
  21151. var vertices = object.geometry.attributes.position.array;
  21152. var numEdges = vertices.length / 3;
  21153. var numTris = numEdges / 3;
  21154. geometry.addAttribute( 'position', Float32Array, 2 * numEdges, 3 );
  21155. var coords = geometry.attributes.position.array;
  21156. for ( var i = 0, l = numTris; i < l; i ++ ) {
  21157. for ( var j = 0; j < 3; j ++ ) {
  21158. var index = 18 * i + 6 * j;
  21159. var index1 = 9 * i + 3 * j;
  21160. coords[ index + 0 ] = vertices[ index1 ];
  21161. coords[ index + 1 ] = vertices[ index1 + 1 ];
  21162. coords[ index + 2 ] = vertices[ index1 + 2 ];
  21163. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  21164. coords[ index + 3 ] = vertices[ index2 ];
  21165. coords[ index + 4 ] = vertices[ index2 + 1 ];
  21166. coords[ index + 5 ] = vertices[ index2 + 2 ];
  21167. }
  21168. }
  21169. }
  21170. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  21171. this.matrixAutoUpdate = false;
  21172. this.matrixWorld = object.matrixWorld;
  21173. };
  21174. THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype );
  21175. /**
  21176. * @author alteredq / http://alteredqualia.com/
  21177. */
  21178. THREE.ImmediateRenderObject = function () {
  21179. THREE.Object3D.call( this );
  21180. this.render = function ( renderCallback ) { };
  21181. };
  21182. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  21183. /**
  21184. * @author mikael emtinger / http://gomo.se/
  21185. * @author alteredq / http://alteredqualia.com/
  21186. */
  21187. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  21188. THREE.Object3D.call( this );
  21189. this.lensFlares = [];
  21190. this.positionScreen = new THREE.Vector3();
  21191. this.customUpdateCallback = undefined;
  21192. if( texture !== undefined ) {
  21193. this.add( texture, size, distance, blending, color );
  21194. }
  21195. };
  21196. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  21197. /*
  21198. * Add: adds another flare
  21199. */
  21200. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  21201. if( size === undefined ) size = -1;
  21202. if( distance === undefined ) distance = 0;
  21203. if( opacity === undefined ) opacity = 1;
  21204. if( color === undefined ) color = new THREE.Color( 0xffffff );
  21205. if( blending === undefined ) blending = THREE.NormalBlending;
  21206. distance = Math.min( distance, Math.max( 0, distance ) );
  21207. this.lensFlares.push( { texture: texture, // THREE.Texture
  21208. size: size, // size in pixels (-1 = use texture.width)
  21209. distance: distance, // distance (0-1) from light source (0=at light source)
  21210. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  21211. scale: 1, // scale
  21212. rotation: 1, // rotation
  21213. opacity: opacity, // opacity
  21214. color: color, // color
  21215. blending: blending } ); // blending
  21216. };
  21217. /*
  21218. * Update lens flares update positions on all flares based on the screen position
  21219. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  21220. */
  21221. THREE.LensFlare.prototype.updateLensFlares = function () {
  21222. var f, fl = this.lensFlares.length;
  21223. var flare;
  21224. var vecX = -this.positionScreen.x * 2;
  21225. var vecY = -this.positionScreen.y * 2;
  21226. for( f = 0; f < fl; f ++ ) {
  21227. flare = this.lensFlares[ f ];
  21228. flare.x = this.positionScreen.x + vecX * flare.distance;
  21229. flare.y = this.positionScreen.y + vecY * flare.distance;
  21230. flare.wantedRotation = flare.x * Math.PI * 0.25;
  21231. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  21232. }
  21233. };
  21234. /**
  21235. * @author alteredq / http://alteredqualia.com/
  21236. */
  21237. THREE.MorphBlendMesh = function( geometry, material ) {
  21238. THREE.Mesh.call( this, geometry, material );
  21239. this.animationsMap = {};
  21240. this.animationsList = [];
  21241. // prepare default animation
  21242. // (all frames played together in 1 second)
  21243. var numFrames = this.geometry.morphTargets.length;
  21244. var name = "__default";
  21245. var startFrame = 0;
  21246. var endFrame = numFrames - 1;
  21247. var fps = numFrames / 1;
  21248. this.createAnimation( name, startFrame, endFrame, fps );
  21249. this.setAnimationWeight( name, 1 );
  21250. };
  21251. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  21252. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  21253. var animation = {
  21254. startFrame: start,
  21255. endFrame: end,
  21256. length: end - start + 1,
  21257. fps: fps,
  21258. duration: ( end - start ) / fps,
  21259. lastFrame: 0,
  21260. currentFrame: 0,
  21261. active: false,
  21262. time: 0,
  21263. direction: 1,
  21264. weight: 1,
  21265. directionBackwards: false,
  21266. mirroredLoop: false
  21267. };
  21268. this.animationsMap[ name ] = animation;
  21269. this.animationsList.push( animation );
  21270. };
  21271. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  21272. var pattern = /([a-z]+)(\d+)/;
  21273. var firstAnimation, frameRanges = {};
  21274. var geometry = this.geometry;
  21275. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  21276. var morph = geometry.morphTargets[ i ];
  21277. var chunks = morph.name.match( pattern );
  21278. if ( chunks && chunks.length > 1 ) {
  21279. var name = chunks[ 1 ];
  21280. var num = chunks[ 2 ];
  21281. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  21282. var range = frameRanges[ name ];
  21283. if ( i < range.start ) range.start = i;
  21284. if ( i > range.end ) range.end = i;
  21285. if ( ! firstAnimation ) firstAnimation = name;
  21286. }
  21287. }
  21288. for ( var name in frameRanges ) {
  21289. var range = frameRanges[ name ];
  21290. this.createAnimation( name, range.start, range.end, fps );
  21291. }
  21292. this.firstAnimation = firstAnimation;
  21293. };
  21294. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  21295. var animation = this.animationsMap[ name ];
  21296. if ( animation ) {
  21297. animation.direction = 1;
  21298. animation.directionBackwards = false;
  21299. }
  21300. };
  21301. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  21302. var animation = this.animationsMap[ name ];
  21303. if ( animation ) {
  21304. animation.direction = -1;
  21305. animation.directionBackwards = true;
  21306. }
  21307. };
  21308. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  21309. var animation = this.animationsMap[ name ];
  21310. if ( animation ) {
  21311. animation.fps = fps;
  21312. animation.duration = ( animation.end - animation.start ) / animation.fps;
  21313. }
  21314. };
  21315. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  21316. var animation = this.animationsMap[ name ];
  21317. if ( animation ) {
  21318. animation.duration = duration;
  21319. animation.fps = ( animation.end - animation.start ) / animation.duration;
  21320. }
  21321. };
  21322. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  21323. var animation = this.animationsMap[ name ];
  21324. if ( animation ) {
  21325. animation.weight = weight;
  21326. }
  21327. };
  21328. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  21329. var animation = this.animationsMap[ name ];
  21330. if ( animation ) {
  21331. animation.time = time;
  21332. }
  21333. };
  21334. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  21335. var time = 0;
  21336. var animation = this.animationsMap[ name ];
  21337. if ( animation ) {
  21338. time = animation.time;
  21339. }
  21340. return time;
  21341. };
  21342. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  21343. var duration = -1;
  21344. var animation = this.animationsMap[ name ];
  21345. if ( animation ) {
  21346. duration = animation.duration;
  21347. }
  21348. return duration;
  21349. };
  21350. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  21351. var animation = this.animationsMap[ name ];
  21352. if ( animation ) {
  21353. animation.time = 0;
  21354. animation.active = true;
  21355. } else {
  21356. console.warn( "animation[" + name + "] undefined" );
  21357. }
  21358. };
  21359. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  21360. var animation = this.animationsMap[ name ];
  21361. if ( animation ) {
  21362. animation.active = false;
  21363. }
  21364. };
  21365. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  21366. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  21367. var animation = this.animationsList[ i ];
  21368. if ( ! animation.active ) continue;
  21369. var frameTime = animation.duration / animation.length;
  21370. animation.time += animation.direction * delta;
  21371. if ( animation.mirroredLoop ) {
  21372. if ( animation.time > animation.duration || animation.time < 0 ) {
  21373. animation.direction *= -1;
  21374. if ( animation.time > animation.duration ) {
  21375. animation.time = animation.duration;
  21376. animation.directionBackwards = true;
  21377. }
  21378. if ( animation.time < 0 ) {
  21379. animation.time = 0;
  21380. animation.directionBackwards = false;
  21381. }
  21382. }
  21383. } else {
  21384. animation.time = animation.time % animation.duration;
  21385. if ( animation.time < 0 ) animation.time += animation.duration;
  21386. }
  21387. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  21388. var weight = animation.weight;
  21389. if ( keyframe !== animation.currentFrame ) {
  21390. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  21391. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  21392. this.morphTargetInfluences[ keyframe ] = 0;
  21393. animation.lastFrame = animation.currentFrame;
  21394. animation.currentFrame = keyframe;
  21395. }
  21396. var mix = ( animation.time % frameTime ) / frameTime;
  21397. if ( animation.directionBackwards ) mix = 1 - mix;
  21398. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  21399. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  21400. }
  21401. };
  21402. /**
  21403. * @author mikael emtinger / http://gomo.se/
  21404. * @author alteredq / http://alteredqualia.com/
  21405. */
  21406. THREE.LensFlarePlugin = function () {
  21407. var _gl, _renderer, _precision, _lensFlare = {};
  21408. this.init = function ( renderer ) {
  21409. _gl = renderer.context;
  21410. _renderer = renderer;
  21411. _precision = renderer.getPrecision();
  21412. _lensFlare.vertices = new Float32Array( 8 + 8 );
  21413. _lensFlare.faces = new Uint16Array( 6 );
  21414. var i = 0;
  21415. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  21416. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  21417. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  21418. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  21419. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21420. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21421. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  21422. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  21423. i = 0;
  21424. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  21425. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  21426. // buffers
  21427. _lensFlare.vertexBuffer = _gl.createBuffer();
  21428. _lensFlare.elementBuffer = _gl.createBuffer();
  21429. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21430. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  21431. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21432. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  21433. // textures
  21434. _lensFlare.tempTexture = _gl.createTexture();
  21435. _lensFlare.occlusionTexture = _gl.createTexture();
  21436. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21437. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  21438. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21439. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21440. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21441. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21442. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21443. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  21444. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21445. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21446. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21447. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21448. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  21449. _lensFlare.hasVertexTexture = false;
  21450. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  21451. } else {
  21452. _lensFlare.hasVertexTexture = true;
  21453. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  21454. }
  21455. _lensFlare.attributes = {};
  21456. _lensFlare.uniforms = {};
  21457. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  21458. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  21459. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  21460. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  21461. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  21462. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  21463. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  21464. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  21465. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  21466. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  21467. };
  21468. /*
  21469. * Render lens flares
  21470. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  21471. * reads these back and calculates occlusion.
  21472. * Then _lensFlare.update_lensFlares() is called to re-position and
  21473. * update transparency of flares. Then they are rendered.
  21474. *
  21475. */
  21476. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21477. var flares = scene.__webglFlares,
  21478. nFlares = flares.length;
  21479. if ( ! nFlares ) return;
  21480. var tempPosition = new THREE.Vector3();
  21481. var invAspect = viewportHeight / viewportWidth,
  21482. halfViewportWidth = viewportWidth * 0.5,
  21483. halfViewportHeight = viewportHeight * 0.5;
  21484. var size = 16 / viewportHeight,
  21485. scale = new THREE.Vector2( size * invAspect, size );
  21486. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  21487. screenPositionPixels = new THREE.Vector2( 1, 1 );
  21488. var uniforms = _lensFlare.uniforms,
  21489. attributes = _lensFlare.attributes;
  21490. // set _lensFlare program and reset blending
  21491. _gl.useProgram( _lensFlare.program );
  21492. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  21493. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  21494. // loop through all lens flares to update their occlusion and positions
  21495. // setup gl and common used attribs/unforms
  21496. _gl.uniform1i( uniforms.occlusionMap, 0 );
  21497. _gl.uniform1i( uniforms.map, 1 );
  21498. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21499. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21500. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21501. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21502. _gl.disable( _gl.CULL_FACE );
  21503. _gl.depthMask( false );
  21504. var i, j, jl, flare, sprite;
  21505. for ( i = 0; i < nFlares; i ++ ) {
  21506. size = 16 / viewportHeight;
  21507. scale.set( size * invAspect, size );
  21508. // calc object screen position
  21509. flare = flares[ i ];
  21510. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  21511. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  21512. tempPosition.applyProjection( camera.projectionMatrix );
  21513. // setup arrays for gl programs
  21514. screenPosition.copy( tempPosition )
  21515. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  21516. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  21517. // screen cull
  21518. if ( _lensFlare.hasVertexTexture || (
  21519. screenPositionPixels.x > 0 &&
  21520. screenPositionPixels.x < viewportWidth &&
  21521. screenPositionPixels.y > 0 &&
  21522. screenPositionPixels.y < viewportHeight ) ) {
  21523. // save current RGB to temp texture
  21524. _gl.activeTexture( _gl.TEXTURE1 );
  21525. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21526. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21527. // render pink quad
  21528. _gl.uniform1i( uniforms.renderType, 0 );
  21529. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21530. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21531. _gl.disable( _gl.BLEND );
  21532. _gl.enable( _gl.DEPTH_TEST );
  21533. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21534. // copy result to occlusionMap
  21535. _gl.activeTexture( _gl.TEXTURE0 );
  21536. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21537. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21538. // restore graphics
  21539. _gl.uniform1i( uniforms.renderType, 1 );
  21540. _gl.disable( _gl.DEPTH_TEST );
  21541. _gl.activeTexture( _gl.TEXTURE1 );
  21542. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21543. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21544. // update object positions
  21545. flare.positionScreen.copy( screenPosition )
  21546. if ( flare.customUpdateCallback ) {
  21547. flare.customUpdateCallback( flare );
  21548. } else {
  21549. flare.updateLensFlares();
  21550. }
  21551. // render flares
  21552. _gl.uniform1i( uniforms.renderType, 2 );
  21553. _gl.enable( _gl.BLEND );
  21554. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21555. sprite = flare.lensFlares[ j ];
  21556. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21557. screenPosition.x = sprite.x;
  21558. screenPosition.y = sprite.y;
  21559. screenPosition.z = sprite.z;
  21560. size = sprite.size * sprite.scale / viewportHeight;
  21561. scale.x = size * invAspect;
  21562. scale.y = size;
  21563. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21564. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21565. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21566. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21567. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21568. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21569. _renderer.setTexture( sprite.texture, 1 );
  21570. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21571. }
  21572. }
  21573. }
  21574. }
  21575. // restore gl
  21576. _gl.enable( _gl.CULL_FACE );
  21577. _gl.enable( _gl.DEPTH_TEST );
  21578. _gl.depthMask( true );
  21579. };
  21580. function createProgram ( shader, precision ) {
  21581. var program = _gl.createProgram();
  21582. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21583. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21584. var prefix = "precision " + precision + " float;\n";
  21585. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21586. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21587. _gl.compileShader( fragmentShader );
  21588. _gl.compileShader( vertexShader );
  21589. _gl.attachShader( program, fragmentShader );
  21590. _gl.attachShader( program, vertexShader );
  21591. _gl.linkProgram( program );
  21592. return program;
  21593. };
  21594. };
  21595. /**
  21596. * @author alteredq / http://alteredqualia.com/
  21597. */
  21598. THREE.ShadowMapPlugin = function () {
  21599. var _gl,
  21600. _renderer,
  21601. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21602. _frustum = new THREE.Frustum(),
  21603. _projScreenMatrix = new THREE.Matrix4(),
  21604. _min = new THREE.Vector3(),
  21605. _max = new THREE.Vector3(),
  21606. _matrixPosition = new THREE.Vector3();
  21607. this.init = function ( renderer ) {
  21608. _gl = renderer.context;
  21609. _renderer = renderer;
  21610. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21611. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21612. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21613. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21614. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21615. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21616. _depthMaterial._shadowPass = true;
  21617. _depthMaterialMorph._shadowPass = true;
  21618. _depthMaterialSkin._shadowPass = true;
  21619. _depthMaterialMorphSkin._shadowPass = true;
  21620. };
  21621. this.render = function ( scene, camera ) {
  21622. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21623. this.update( scene, camera );
  21624. };
  21625. this.update = function ( scene, camera ) {
  21626. var i, il, j, jl, n,
  21627. shadowMap, shadowMatrix, shadowCamera,
  21628. program, buffer, material,
  21629. webglObject, object, light,
  21630. renderList,
  21631. lights = [],
  21632. k = 0,
  21633. fog = null;
  21634. // set GL state for depth map
  21635. _gl.clearColor( 1, 1, 1, 1 );
  21636. _gl.disable( _gl.BLEND );
  21637. _gl.enable( _gl.CULL_FACE );
  21638. _gl.frontFace( _gl.CCW );
  21639. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21640. _gl.cullFace( _gl.FRONT );
  21641. } else {
  21642. _gl.cullFace( _gl.BACK );
  21643. }
  21644. _renderer.setDepthTest( true );
  21645. // preprocess lights
  21646. // - skip lights that are not casting shadows
  21647. // - create virtual lights for cascaded shadow maps
  21648. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21649. light = scene.__lights[ i ];
  21650. if ( ! light.castShadow ) continue;
  21651. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21652. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21653. var virtualLight;
  21654. if ( ! light.shadowCascadeArray[ n ] ) {
  21655. virtualLight = createVirtualLight( light, n );
  21656. virtualLight.originalCamera = camera;
  21657. var gyro = new THREE.Gyroscope();
  21658. gyro.position = light.shadowCascadeOffset;
  21659. gyro.add( virtualLight );
  21660. gyro.add( virtualLight.target );
  21661. camera.add( gyro );
  21662. light.shadowCascadeArray[ n ] = virtualLight;
  21663. console.log( "Created virtualLight", virtualLight );
  21664. } else {
  21665. virtualLight = light.shadowCascadeArray[ n ];
  21666. }
  21667. updateVirtualLight( light, n );
  21668. lights[ k ] = virtualLight;
  21669. k ++;
  21670. }
  21671. } else {
  21672. lights[ k ] = light;
  21673. k ++;
  21674. }
  21675. }
  21676. // render depth map
  21677. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21678. light = lights[ i ];
  21679. if ( ! light.shadowMap ) {
  21680. var shadowFilter = THREE.LinearFilter;
  21681. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  21682. shadowFilter = THREE.NearestFilter;
  21683. }
  21684. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  21685. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21686. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21687. light.shadowMatrix = new THREE.Matrix4();
  21688. }
  21689. if ( ! light.shadowCamera ) {
  21690. if ( light instanceof THREE.SpotLight ) {
  21691. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21692. } else if ( light instanceof THREE.DirectionalLight ) {
  21693. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21694. } else {
  21695. console.error( "Unsupported light type for shadow" );
  21696. continue;
  21697. }
  21698. scene.add( light.shadowCamera );
  21699. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21700. }
  21701. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21702. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21703. light.shadowCamera.add( light.cameraHelper );
  21704. }
  21705. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21706. updateShadowCamera( camera, light );
  21707. }
  21708. shadowMap = light.shadowMap;
  21709. shadowMatrix = light.shadowMatrix;
  21710. shadowCamera = light.shadowCamera;
  21711. shadowCamera.position.setFromMatrixPosition( light.matrixWorld );
  21712. _matrixPosition.setFromMatrixPosition( light.target.matrixWorld );
  21713. shadowCamera.lookAt( _matrixPosition );
  21714. shadowCamera.updateMatrixWorld();
  21715. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21716. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  21717. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21718. // compute shadow matrix
  21719. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21720. 0.0, 0.5, 0.0, 0.5,
  21721. 0.0, 0.0, 0.5, 0.5,
  21722. 0.0, 0.0, 0.0, 1.0 );
  21723. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  21724. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  21725. // update camera matrices and frustum
  21726. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21727. _frustum.setFromMatrix( _projScreenMatrix );
  21728. // render shadow map
  21729. _renderer.setRenderTarget( shadowMap );
  21730. _renderer.clear();
  21731. // set object matrices & frustum culling
  21732. renderList = scene.__webglObjects;
  21733. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21734. webglObject = renderList[ j ];
  21735. object = webglObject.object;
  21736. webglObject.render = false;
  21737. if ( object.visible && object.castShadow ) {
  21738. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21739. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21740. webglObject.render = true;
  21741. }
  21742. }
  21743. }
  21744. // render regular objects
  21745. var objectMaterial, useMorphing, useSkinning;
  21746. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21747. webglObject = renderList[ j ];
  21748. if ( webglObject.render ) {
  21749. object = webglObject.object;
  21750. buffer = webglObject.buffer;
  21751. // culling is overriden globally for all objects
  21752. // while rendering depth map
  21753. // need to deal with MeshFaceMaterial somehow
  21754. // in that case just use the first of material.materials for now
  21755. // (proper solution would require to break objects by materials
  21756. // similarly to regular rendering and then set corresponding
  21757. // depth materials per each chunk instead of just once per object)
  21758. objectMaterial = getObjectMaterial( object );
  21759. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21760. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21761. if ( object.customDepthMaterial ) {
  21762. material = object.customDepthMaterial;
  21763. } else if ( useSkinning ) {
  21764. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21765. } else if ( useMorphing ) {
  21766. material = _depthMaterialMorph;
  21767. } else {
  21768. material = _depthMaterial;
  21769. }
  21770. if ( buffer instanceof THREE.BufferGeometry ) {
  21771. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21772. } else {
  21773. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21774. }
  21775. }
  21776. }
  21777. // set matrices and render immediate objects
  21778. renderList = scene.__webglObjectsImmediate;
  21779. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21780. webglObject = renderList[ j ];
  21781. object = webglObject.object;
  21782. if ( object.visible && object.castShadow ) {
  21783. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21784. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21785. }
  21786. }
  21787. }
  21788. // restore GL state
  21789. var clearColor = _renderer.getClearColor(),
  21790. clearAlpha = _renderer.getClearAlpha();
  21791. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21792. _gl.enable( _gl.BLEND );
  21793. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21794. _gl.cullFace( _gl.BACK );
  21795. }
  21796. };
  21797. function createVirtualLight( light, cascade ) {
  21798. var virtualLight = new THREE.DirectionalLight();
  21799. virtualLight.isVirtual = true;
  21800. virtualLight.onlyShadow = true;
  21801. virtualLight.castShadow = true;
  21802. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21803. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21804. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21805. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21806. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21807. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21808. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21809. virtualLight.shadowDarkness = light.shadowDarkness;
  21810. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21811. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21812. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21813. virtualLight.pointsWorld = [];
  21814. virtualLight.pointsFrustum = [];
  21815. var pointsWorld = virtualLight.pointsWorld,
  21816. pointsFrustum = virtualLight.pointsFrustum;
  21817. for ( var i = 0; i < 8; i ++ ) {
  21818. pointsWorld[ i ] = new THREE.Vector3();
  21819. pointsFrustum[ i ] = new THREE.Vector3();
  21820. }
  21821. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21822. var farZ = light.shadowCascadeFarZ[ cascade ];
  21823. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21824. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21825. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21826. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21827. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21828. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21829. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21830. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21831. return virtualLight;
  21832. }
  21833. // Synchronize virtual light with the original light
  21834. function updateVirtualLight( light, cascade ) {
  21835. var virtualLight = light.shadowCascadeArray[ cascade ];
  21836. virtualLight.position.copy( light.position );
  21837. virtualLight.target.position.copy( light.target.position );
  21838. virtualLight.lookAt( virtualLight.target );
  21839. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21840. virtualLight.shadowDarkness = light.shadowDarkness;
  21841. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21842. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21843. var farZ = light.shadowCascadeFarZ[ cascade ];
  21844. var pointsFrustum = virtualLight.pointsFrustum;
  21845. pointsFrustum[ 0 ].z = nearZ;
  21846. pointsFrustum[ 1 ].z = nearZ;
  21847. pointsFrustum[ 2 ].z = nearZ;
  21848. pointsFrustum[ 3 ].z = nearZ;
  21849. pointsFrustum[ 4 ].z = farZ;
  21850. pointsFrustum[ 5 ].z = farZ;
  21851. pointsFrustum[ 6 ].z = farZ;
  21852. pointsFrustum[ 7 ].z = farZ;
  21853. }
  21854. // Fit shadow camera's ortho frustum to camera frustum
  21855. function updateShadowCamera( camera, light ) {
  21856. var shadowCamera = light.shadowCamera,
  21857. pointsFrustum = light.pointsFrustum,
  21858. pointsWorld = light.pointsWorld;
  21859. _min.set( Infinity, Infinity, Infinity );
  21860. _max.set( -Infinity, -Infinity, -Infinity );
  21861. for ( var i = 0; i < 8; i ++ ) {
  21862. var p = pointsWorld[ i ];
  21863. p.copy( pointsFrustum[ i ] );
  21864. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21865. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  21866. if ( p.x < _min.x ) _min.x = p.x;
  21867. if ( p.x > _max.x ) _max.x = p.x;
  21868. if ( p.y < _min.y ) _min.y = p.y;
  21869. if ( p.y > _max.y ) _max.y = p.y;
  21870. if ( p.z < _min.z ) _min.z = p.z;
  21871. if ( p.z > _max.z ) _max.z = p.z;
  21872. }
  21873. shadowCamera.left = _min.x;
  21874. shadowCamera.right = _max.x;
  21875. shadowCamera.top = _max.y;
  21876. shadowCamera.bottom = _min.y;
  21877. // can't really fit near/far
  21878. //shadowCamera.near = _min.z;
  21879. //shadowCamera.far = _max.z;
  21880. shadowCamera.updateProjectionMatrix();
  21881. }
  21882. // For the moment just ignore objects that have multiple materials with different animation methods
  21883. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  21884. function getObjectMaterial( object ) {
  21885. return object.material instanceof THREE.MeshFaceMaterial
  21886. ? object.material.materials[ 0 ]
  21887. : object.material;
  21888. };
  21889. };
  21890. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21891. /**
  21892. * @author mikael emtinger / http://gomo.se/
  21893. * @author alteredq / http://alteredqualia.com/
  21894. */
  21895. THREE.SpritePlugin = function () {
  21896. var _gl, _renderer, _texture;
  21897. var vertices, faces, vertexBuffer, elementBuffer;
  21898. var program, attributes, uniforms;
  21899. this.init = function ( renderer ) {
  21900. _gl = renderer.context;
  21901. _renderer = renderer;
  21902. vertices = new Float32Array( [
  21903. - 0.5, - 0.5, 0, 0,
  21904. 0.5, - 0.5, 1, 0,
  21905. 0.5, 0.5, 1, 1,
  21906. - 0.5, 0.5, 0, 1
  21907. ] );
  21908. faces = new Uint16Array( [
  21909. 0, 1, 2,
  21910. 0, 2, 3
  21911. ] );
  21912. vertexBuffer = _gl.createBuffer();
  21913. elementBuffer = _gl.createBuffer();
  21914. _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
  21915. _gl.bufferData( _gl.ARRAY_BUFFER, vertices, _gl.STATIC_DRAW );
  21916. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  21917. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faces, _gl.STATIC_DRAW );
  21918. program = createProgram();
  21919. attributes = {
  21920. position: _gl.getAttribLocation ( program, 'position' ),
  21921. uv: _gl.getAttribLocation ( program, 'uv' )
  21922. };
  21923. uniforms = {
  21924. uvOffset: _gl.getUniformLocation( program, 'uvOffset' ),
  21925. uvScale: _gl.getUniformLocation( program, 'uvScale' ),
  21926. rotation: _gl.getUniformLocation( program, 'rotation' ),
  21927. scale: _gl.getUniformLocation( program, 'scale' ),
  21928. color: _gl.getUniformLocation( program, 'color' ),
  21929. map: _gl.getUniformLocation( program, 'map' ),
  21930. opacity: _gl.getUniformLocation( program, 'opacity' ),
  21931. modelViewMatrix: _gl.getUniformLocation( program, 'modelViewMatrix' ),
  21932. projectionMatrix: _gl.getUniformLocation( program, 'projectionMatrix' ),
  21933. fogType: _gl.getUniformLocation( program, 'fogType' ),
  21934. fogDensity: _gl.getUniformLocation( program, 'fogDensity' ),
  21935. fogNear: _gl.getUniformLocation( program, 'fogNear' ),
  21936. fogFar: _gl.getUniformLocation( program, 'fogFar' ),
  21937. fogColor: _gl.getUniformLocation( program, 'fogColor' ),
  21938. alphaTest: _gl.getUniformLocation( program, 'alphaTest' )
  21939. };
  21940. var canvas = document.createElement( 'canvas' );
  21941. canvas.width = 8;
  21942. canvas.height = 8;
  21943. var context = canvas.getContext( '2d' );
  21944. context.fillStyle = '#ffffff';
  21945. context.fillRect( 0, 0, canvas.width, canvas.height );
  21946. _texture = new THREE.Texture( canvas );
  21947. _texture.needsUpdate = true;
  21948. };
  21949. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21950. var sprites = scene.__webglSprites,
  21951. nSprites = sprites.length;
  21952. if ( ! nSprites ) return;
  21953. // setup gl
  21954. _gl.useProgram( program );
  21955. _gl.enableVertexAttribArray( attributes.position );
  21956. _gl.enableVertexAttribArray( attributes.uv );
  21957. _gl.disable( _gl.CULL_FACE );
  21958. _gl.enable( _gl.BLEND );
  21959. _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
  21960. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21961. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21962. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  21963. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  21964. _gl.activeTexture( _gl.TEXTURE0 );
  21965. _gl.uniform1i( uniforms.map, 0 );
  21966. var oldFogType = 0;
  21967. var sceneFogType = 0;
  21968. var fog = scene.fog;
  21969. if ( fog ) {
  21970. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  21971. if ( fog instanceof THREE.Fog ) {
  21972. _gl.uniform1f( uniforms.fogNear, fog.near );
  21973. _gl.uniform1f( uniforms.fogFar, fog.far );
  21974. _gl.uniform1i( uniforms.fogType, 1 );
  21975. oldFogType = 1;
  21976. sceneFogType = 1;
  21977. } else if ( fog instanceof THREE.FogExp2 ) {
  21978. _gl.uniform1f( uniforms.fogDensity, fog.density );
  21979. _gl.uniform1i( uniforms.fogType, 2 );
  21980. oldFogType = 2;
  21981. sceneFogType = 2;
  21982. }
  21983. } else {
  21984. _gl.uniform1i( uniforms.fogType, 0 );
  21985. oldFogType = 0;
  21986. sceneFogType = 0;
  21987. }
  21988. // update positions and sort
  21989. var i, sprite, material, fogType, scale = [];
  21990. for( i = 0; i < nSprites; i ++ ) {
  21991. sprite = sprites[ i ];
  21992. material = sprite.material;
  21993. if ( sprite.visible === false ) continue;
  21994. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  21995. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  21996. }
  21997. sprites.sort( painterSortStable );
  21998. // render all sprites
  21999. for( i = 0; i < nSprites; i ++ ) {
  22000. sprite = sprites[ i ];
  22001. if ( sprite.visible === false ) continue;
  22002. material = sprite.material;
  22003. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  22004. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  22005. scale[ 0 ] = sprite.scale.x;
  22006. scale[ 1 ] = sprite.scale.y;
  22007. if ( scene.fog && material.fog ) {
  22008. fogType = sceneFogType;
  22009. } else {
  22010. fogType = 0;
  22011. }
  22012. if ( oldFogType !== fogType ) {
  22013. _gl.uniform1i( uniforms.fogType, fogType );
  22014. oldFogType = fogType;
  22015. }
  22016. if ( material.map !== null ) {
  22017. _gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  22018. _gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  22019. } else {
  22020. _gl.uniform2f( uniforms.uvOffset, 0, 0 );
  22021. _gl.uniform2f( uniforms.uvScale, 1, 1 );
  22022. }
  22023. _gl.uniform1f( uniforms.opacity, material.opacity );
  22024. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  22025. _gl.uniform1f( uniforms.rotation, material.rotation );
  22026. _gl.uniform2fv( uniforms.scale, scale );
  22027. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  22028. _renderer.setDepthTest( material.depthTest );
  22029. _renderer.setDepthWrite( material.depthWrite );
  22030. if ( material.map && material.map.image && material.map.image.width ) {
  22031. _renderer.setTexture( material.map, 0 );
  22032. } else {
  22033. _renderer.setTexture( _texture, 0 );
  22034. }
  22035. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  22036. }
  22037. // restore gl
  22038. _gl.enable( _gl.CULL_FACE );
  22039. };
  22040. function createProgram () {
  22041. var program = _gl.createProgram();
  22042. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  22043. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  22044. _gl.shaderSource( vertexShader, [
  22045. 'precision ' + _renderer.getPrecision() + ' float;',
  22046. 'uniform mat4 modelViewMatrix;',
  22047. 'uniform mat4 projectionMatrix;',
  22048. 'uniform float rotation;',
  22049. 'uniform vec2 scale;',
  22050. 'uniform vec2 uvOffset;',
  22051. 'uniform vec2 uvScale;',
  22052. 'attribute vec2 position;',
  22053. 'attribute vec2 uv;',
  22054. 'varying vec2 vUV;',
  22055. 'void main() {',
  22056. 'vUV = uvOffset + uv * uvScale;',
  22057. 'vec2 alignedPosition = position * scale;',
  22058. 'vec2 rotatedPosition;',
  22059. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  22060. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  22061. 'vec4 finalPosition;',
  22062. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  22063. 'finalPosition.xy += rotatedPosition;',
  22064. 'finalPosition = projectionMatrix * finalPosition;',
  22065. 'gl_Position = finalPosition;',
  22066. '}'
  22067. ].join( '\n' ) );
  22068. _gl.shaderSource( fragmentShader, [
  22069. 'precision ' + _renderer.getPrecision() + ' float;',
  22070. 'uniform vec3 color;',
  22071. 'uniform sampler2D map;',
  22072. 'uniform float opacity;',
  22073. 'uniform int fogType;',
  22074. 'uniform vec3 fogColor;',
  22075. 'uniform float fogDensity;',
  22076. 'uniform float fogNear;',
  22077. 'uniform float fogFar;',
  22078. 'uniform float alphaTest;',
  22079. 'varying vec2 vUV;',
  22080. 'void main() {',
  22081. 'vec4 texture = texture2D( map, vUV );',
  22082. 'if ( texture.a < alphaTest ) discard;',
  22083. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  22084. 'if ( fogType > 0 ) {',
  22085. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  22086. 'float fogFactor = 0.0;',
  22087. 'if ( fogType == 1 ) {',
  22088. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  22089. '} else {',
  22090. 'const float LOG2 = 1.442695;',
  22091. 'float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  22092. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  22093. '}',
  22094. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  22095. '}',
  22096. '}'
  22097. ].join( '\n' ) );
  22098. _gl.compileShader( vertexShader );
  22099. _gl.compileShader( fragmentShader );
  22100. _gl.attachShader( program, vertexShader );
  22101. _gl.attachShader( program, fragmentShader );
  22102. _gl.linkProgram( program );
  22103. return program;
  22104. };
  22105. function painterSortStable ( a, b ) {
  22106. if ( a.z !== b.z ) {
  22107. return b.z - a.z;
  22108. } else {
  22109. return b.id - a.id;
  22110. }
  22111. };
  22112. };
  22113. /**
  22114. * @author alteredq / http://alteredqualia.com/
  22115. */
  22116. THREE.DepthPassPlugin = function () {
  22117. this.enabled = false;
  22118. this.renderTarget = null;
  22119. var _gl,
  22120. _renderer,
  22121. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  22122. _frustum = new THREE.Frustum(),
  22123. _projScreenMatrix = new THREE.Matrix4();
  22124. this.init = function ( renderer ) {
  22125. _gl = renderer.context;
  22126. _renderer = renderer;
  22127. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  22128. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  22129. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  22130. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  22131. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  22132. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  22133. _depthMaterial._shadowPass = true;
  22134. _depthMaterialMorph._shadowPass = true;
  22135. _depthMaterialSkin._shadowPass = true;
  22136. _depthMaterialMorphSkin._shadowPass = true;
  22137. };
  22138. this.render = function ( scene, camera ) {
  22139. if ( ! this.enabled ) return;
  22140. this.update( scene, camera );
  22141. };
  22142. this.update = function ( scene, camera ) {
  22143. var i, il, j, jl, n,
  22144. program, buffer, material,
  22145. webglObject, object, light,
  22146. renderList,
  22147. fog = null;
  22148. // set GL state for depth map
  22149. _gl.clearColor( 1, 1, 1, 1 );
  22150. _gl.disable( _gl.BLEND );
  22151. _renderer.setDepthTest( true );
  22152. // update scene
  22153. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  22154. // update camera matrices and frustum
  22155. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  22156. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  22157. _frustum.setFromMatrix( _projScreenMatrix );
  22158. // render depth map
  22159. _renderer.setRenderTarget( this.renderTarget );
  22160. _renderer.clear();
  22161. // set object matrices & frustum culling
  22162. renderList = scene.__webglObjects;
  22163. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22164. webglObject = renderList[ j ];
  22165. object = webglObject.object;
  22166. webglObject.render = false;
  22167. if ( object.visible ) {
  22168. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  22169. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  22170. webglObject.render = true;
  22171. }
  22172. }
  22173. }
  22174. // render regular objects
  22175. var objectMaterial, useMorphing, useSkinning;
  22176. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22177. webglObject = renderList[ j ];
  22178. if ( webglObject.render ) {
  22179. object = webglObject.object;
  22180. buffer = webglObject.buffer;
  22181. // todo: create proper depth material for particles
  22182. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  22183. objectMaterial = getObjectMaterial( object );
  22184. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  22185. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  22186. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  22187. if ( object.customDepthMaterial ) {
  22188. material = object.customDepthMaterial;
  22189. } else if ( useSkinning ) {
  22190. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  22191. } else if ( useMorphing ) {
  22192. material = _depthMaterialMorph;
  22193. } else {
  22194. material = _depthMaterial;
  22195. }
  22196. if ( buffer instanceof THREE.BufferGeometry ) {
  22197. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  22198. } else {
  22199. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  22200. }
  22201. }
  22202. }
  22203. // set matrices and render immediate objects
  22204. renderList = scene.__webglObjectsImmediate;
  22205. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22206. webglObject = renderList[ j ];
  22207. object = webglObject.object;
  22208. if ( object.visible ) {
  22209. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  22210. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  22211. }
  22212. }
  22213. // restore GL state
  22214. var clearColor = _renderer.getClearColor(),
  22215. clearAlpha = _renderer.getClearAlpha();
  22216. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  22217. _gl.enable( _gl.BLEND );
  22218. };
  22219. // For the moment just ignore objects that have multiple materials with different animation methods
  22220. // Only the first material will be taken into account for deciding which depth material to use
  22221. function getObjectMaterial( object ) {
  22222. return object.material instanceof THREE.MeshFaceMaterial
  22223. ? object.material.materials[ 0 ]
  22224. : object.material;
  22225. };
  22226. };
  22227. /**
  22228. * @author mikael emtinger / http://gomo.se/
  22229. */
  22230. THREE.ShaderFlares = {
  22231. 'lensFlareVertexTexture': {
  22232. vertexShader: [
  22233. "uniform lowp int renderType;",
  22234. "uniform vec3 screenPosition;",
  22235. "uniform vec2 scale;",
  22236. "uniform float rotation;",
  22237. "uniform sampler2D occlusionMap;",
  22238. "attribute vec2 position;",
  22239. "attribute vec2 uv;",
  22240. "varying vec2 vUV;",
  22241. "varying float vVisibility;",
  22242. "void main() {",
  22243. "vUV = uv;",
  22244. "vec2 pos = position;",
  22245. "if( renderType == 2 ) {",
  22246. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  22247. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  22248. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  22249. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  22250. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  22251. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  22252. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  22253. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  22254. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  22255. "vVisibility = visibility.r / 9.0;",
  22256. "vVisibility *= 1.0 - visibility.g / 9.0;",
  22257. "vVisibility *= visibility.b / 9.0;",
  22258. "vVisibility *= 1.0 - visibility.a / 9.0;",
  22259. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22260. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22261. "}",
  22262. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22263. "}"
  22264. ].join( "\n" ),
  22265. fragmentShader: [
  22266. "uniform lowp int renderType;",
  22267. "uniform sampler2D map;",
  22268. "uniform float opacity;",
  22269. "uniform vec3 color;",
  22270. "varying vec2 vUV;",
  22271. "varying float vVisibility;",
  22272. "void main() {",
  22273. // pink square
  22274. "if( renderType == 0 ) {",
  22275. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  22276. // restore
  22277. "} else if( renderType == 1 ) {",
  22278. "gl_FragColor = texture2D( map, vUV );",
  22279. // flare
  22280. "} else {",
  22281. "vec4 texture = texture2D( map, vUV );",
  22282. "texture.a *= opacity * vVisibility;",
  22283. "gl_FragColor = texture;",
  22284. "gl_FragColor.rgb *= color;",
  22285. "}",
  22286. "}"
  22287. ].join( "\n" )
  22288. },
  22289. 'lensFlare': {
  22290. vertexShader: [
  22291. "uniform lowp int renderType;",
  22292. "uniform vec3 screenPosition;",
  22293. "uniform vec2 scale;",
  22294. "uniform float rotation;",
  22295. "attribute vec2 position;",
  22296. "attribute vec2 uv;",
  22297. "varying vec2 vUV;",
  22298. "void main() {",
  22299. "vUV = uv;",
  22300. "vec2 pos = position;",
  22301. "if( renderType == 2 ) {",
  22302. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22303. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22304. "}",
  22305. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22306. "}"
  22307. ].join( "\n" ),
  22308. fragmentShader: [
  22309. "precision mediump float;",
  22310. "uniform lowp int renderType;",
  22311. "uniform sampler2D map;",
  22312. "uniform sampler2D occlusionMap;",
  22313. "uniform float opacity;",
  22314. "uniform vec3 color;",
  22315. "varying vec2 vUV;",
  22316. "void main() {",
  22317. // pink square
  22318. "if( renderType == 0 ) {",
  22319. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  22320. // restore
  22321. "} else if( renderType == 1 ) {",
  22322. "gl_FragColor = texture2D( map, vUV );",
  22323. // flare
  22324. "} else {",
  22325. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  22326. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  22327. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  22328. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  22329. "visibility = ( 1.0 - visibility / 4.0 );",
  22330. "vec4 texture = texture2D( map, vUV );",
  22331. "texture.a *= opacity * visibility;",
  22332. "gl_FragColor = texture;",
  22333. "gl_FragColor.rgb *= color;",
  22334. "}",
  22335. "}"
  22336. ].join( "\n" )
  22337. }
  22338. };
粤ICP备19079148号