three.js 820 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745
  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 = THREE || { REVISION: '59dev' };
  7. self.console = self.console || {
  8. info: function () {},
  9. log: function () {},
  10. debug: function () {},
  11. warn: function () {},
  12. error: function () {}
  13. };
  14. self.Int32Array = self.Int32Array || Array;
  15. self.Float32Array = self.Float32Array || Array;
  16. String.prototype.trim = String.prototype.trim || function () {
  17. return this.replace( /^\s+|\s+$/g, '' );
  18. };
  19. // based on https://github.com/documentcloud/underscore/blob/bf657be243a075b5e72acc8a83e6f12a564d8f55/underscore.js#L767
  20. THREE.extend = function ( obj, source ) {
  21. // ECMAScript5 compatibility based on: http://www.nczonline.net/blog/2012/12/11/are-your-mixins-ecmascript-5-compatible/
  22. if ( Object.keys ) {
  23. var keys = Object.keys( source );
  24. for (var i = 0, il = keys.length; i < il; i++) {
  25. var prop = keys[i];
  26. Object.defineProperty( obj, prop, Object.getOwnPropertyDescriptor( source, prop ) );
  27. }
  28. } else {
  29. var safeHasOwnProperty = {}.hasOwnProperty;
  30. for ( var prop in source ) {
  31. if ( safeHasOwnProperty.call( source, prop ) ) {
  32. obj[prop] = source[prop];
  33. }
  34. }
  35. }
  36. return obj;
  37. };
  38. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  39. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  40. // requestAnimationFrame polyfill by Erik Möller
  41. // fixes from Paul Irish and Tino Zijdel
  42. // using 'self' instead of 'window' for compatibility with both NodeJS and IE10.
  43. ( function () {
  44. var lastTime = 0;
  45. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  46. for ( var x = 0; x < vendors.length && !self.requestAnimationFrame; ++ x ) {
  47. self.requestAnimationFrame = self[ vendors[ x ] + 'RequestAnimationFrame' ];
  48. self.cancelAnimationFrame = self[ vendors[ x ] + 'CancelAnimationFrame' ] || self[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  49. }
  50. if ( self.requestAnimationFrame === undefined && self['setTimeout'] !== undefined ) {
  51. self.requestAnimationFrame = function ( callback ) {
  52. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  53. var id = self.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  54. lastTime = currTime + timeToCall;
  55. return id;
  56. };
  57. }
  58. if( self.cancelAnimationFrame === undefined && self['clearTimeout'] !== undefined ) {
  59. self.cancelAnimationFrame = function ( id ) { self.clearTimeout( id ) };
  60. }
  61. }() );
  62. // GL STATE CONSTANTS
  63. THREE.CullFaceNone = 0;
  64. THREE.CullFaceBack = 1;
  65. THREE.CullFaceFront = 2;
  66. THREE.CullFaceFrontBack = 3;
  67. THREE.FrontFaceDirectionCW = 0;
  68. THREE.FrontFaceDirectionCCW = 1;
  69. // SHADOWING TYPES
  70. THREE.BasicShadowMap = 0;
  71. THREE.PCFShadowMap = 1;
  72. THREE.PCFSoftShadowMap = 2;
  73. // MATERIAL CONSTANTS
  74. // side
  75. THREE.FrontSide = 0;
  76. THREE.BackSide = 1;
  77. THREE.DoubleSide = 2;
  78. // shading
  79. THREE.NoShading = 0;
  80. THREE.FlatShading = 1;
  81. THREE.SmoothShading = 2;
  82. // colors
  83. THREE.NoColors = 0;
  84. THREE.FaceColors = 1;
  85. THREE.VertexColors = 2;
  86. // blending modes
  87. THREE.NoBlending = 0;
  88. THREE.NormalBlending = 1;
  89. THREE.AdditiveBlending = 2;
  90. THREE.SubtractiveBlending = 3;
  91. THREE.MultiplyBlending = 4;
  92. THREE.CustomBlending = 5;
  93. // custom blending equations
  94. // (numbers start from 100 not to clash with other
  95. // mappings to OpenGL constants defined in Texture.js)
  96. THREE.AddEquation = 100;
  97. THREE.SubtractEquation = 101;
  98. THREE.ReverseSubtractEquation = 102;
  99. // custom blending destination factors
  100. THREE.ZeroFactor = 200;
  101. THREE.OneFactor = 201;
  102. THREE.SrcColorFactor = 202;
  103. THREE.OneMinusSrcColorFactor = 203;
  104. THREE.SrcAlphaFactor = 204;
  105. THREE.OneMinusSrcAlphaFactor = 205;
  106. THREE.DstAlphaFactor = 206;
  107. THREE.OneMinusDstAlphaFactor = 207;
  108. // custom blending source factors
  109. //THREE.ZeroFactor = 200;
  110. //THREE.OneFactor = 201;
  111. //THREE.SrcAlphaFactor = 204;
  112. //THREE.OneMinusSrcAlphaFactor = 205;
  113. //THREE.DstAlphaFactor = 206;
  114. //THREE.OneMinusDstAlphaFactor = 207;
  115. THREE.DstColorFactor = 208;
  116. THREE.OneMinusDstColorFactor = 209;
  117. THREE.SrcAlphaSaturateFactor = 210;
  118. // TEXTURE CONSTANTS
  119. THREE.MultiplyOperation = 0;
  120. THREE.MixOperation = 1;
  121. THREE.AddOperation = 2;
  122. // Mapping modes
  123. THREE.UVMapping = function () {};
  124. THREE.CubeReflectionMapping = function () {};
  125. THREE.CubeRefractionMapping = function () {};
  126. THREE.SphericalReflectionMapping = function () {};
  127. THREE.SphericalRefractionMapping = function () {};
  128. // Wrapping modes
  129. THREE.RepeatWrapping = 1000;
  130. THREE.ClampToEdgeWrapping = 1001;
  131. THREE.MirroredRepeatWrapping = 1002;
  132. // Filters
  133. THREE.NearestFilter = 1003;
  134. THREE.NearestMipMapNearestFilter = 1004;
  135. THREE.NearestMipMapLinearFilter = 1005;
  136. THREE.LinearFilter = 1006;
  137. THREE.LinearMipMapNearestFilter = 1007;
  138. THREE.LinearMipMapLinearFilter = 1008;
  139. // Data types
  140. THREE.UnsignedByteType = 1009;
  141. THREE.ByteType = 1010;
  142. THREE.ShortType = 1011;
  143. THREE.UnsignedShortType = 1012;
  144. THREE.IntType = 1013;
  145. THREE.UnsignedIntType = 1014;
  146. THREE.FloatType = 1015;
  147. // Pixel types
  148. //THREE.UnsignedByteType = 1009;
  149. THREE.UnsignedShort4444Type = 1016;
  150. THREE.UnsignedShort5551Type = 1017;
  151. THREE.UnsignedShort565Type = 1018;
  152. // Pixel formats
  153. THREE.AlphaFormat = 1019;
  154. THREE.RGBFormat = 1020;
  155. THREE.RGBAFormat = 1021;
  156. THREE.LuminanceFormat = 1022;
  157. THREE.LuminanceAlphaFormat = 1023;
  158. // Compressed texture formats
  159. THREE.RGB_S3TC_DXT1_Format = 2001;
  160. THREE.RGBA_S3TC_DXT1_Format = 2002;
  161. THREE.RGBA_S3TC_DXT3_Format = 2003;
  162. THREE.RGBA_S3TC_DXT5_Format = 2004;
  163. /*
  164. // Potential future PVRTC compressed texture formats
  165. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  166. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  167. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  168. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  169. */
  170. /**
  171. * @author mrdoob / http://mrdoob.com/
  172. */
  173. THREE.Color = function ( value ) {
  174. if ( value !== undefined ) this.set( value );
  175. return this;
  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 () {
  297. var hsl = { h: 0, s: 0, l: 0 };
  298. return function () {
  299. // h,s,l ranges are in 0.0 - 1.0
  300. var r = this.r, g = this.g, b = this.b;
  301. var max = Math.max( r, g, b );
  302. var min = Math.min( r, g, b );
  303. var hue, saturation;
  304. var lightness = ( min + max ) / 2.0;
  305. if ( min === max ) {
  306. hue = 0;
  307. saturation = 0;
  308. } else {
  309. var delta = max - min;
  310. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  311. switch ( max ) {
  312. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  313. case g: hue = ( b - r ) / delta + 2; break;
  314. case b: hue = ( r - g ) / delta + 4; break;
  315. }
  316. hue /= 6;
  317. }
  318. hsl.h = hue;
  319. hsl.s = saturation;
  320. hsl.l = lightness;
  321. return hsl;
  322. };
  323. }(),
  324. getStyle: function () {
  325. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  326. },
  327. offsetHSL: function ( h, s, l ) {
  328. var hsl = this.getHSL();
  329. hsl.h += h; hsl.s += s; hsl.l += l;
  330. this.setHSL( hsl.h, hsl.s, hsl.l );
  331. return this;
  332. },
  333. add: function ( color ) {
  334. this.r += color.r;
  335. this.g += color.g;
  336. this.b += color.b;
  337. return this;
  338. },
  339. addColors: function ( color1, color2 ) {
  340. this.r = color1.r + color2.r;
  341. this.g = color1.g + color2.g;
  342. this.b = color1.b + color2.b;
  343. return this;
  344. },
  345. addScalar: function ( s ) {
  346. this.r += s;
  347. this.g += s;
  348. this.b += s;
  349. return this;
  350. },
  351. multiply: function ( color ) {
  352. this.r *= color.r;
  353. this.g *= color.g;
  354. this.b *= color.b;
  355. return this;
  356. },
  357. multiplyScalar: function ( s ) {
  358. this.r *= s;
  359. this.g *= s;
  360. this.b *= s;
  361. return this;
  362. },
  363. lerp: function ( color, alpha ) {
  364. this.r += ( color.r - this.r ) * alpha;
  365. this.g += ( color.g - this.g ) * alpha;
  366. this.b += ( color.b - this.b ) * alpha;
  367. return this;
  368. },
  369. equals: function ( c ) {
  370. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  371. },
  372. clone: function () {
  373. return new THREE.Color().setRGB( this.r, this.g, this.b );
  374. }
  375. };
  376. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF,
  377. "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2,
  378. "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50,
  379. "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B,
  380. "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B,
  381. "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F,
  382. "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3,
  383. "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222,
  384. "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700,
  385. "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4,
  386. "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00,
  387. "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3,
  388. "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA,
  389. "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32,
  390. "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3,
  391. "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC,
  392. "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD,
  393. "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6,
  394. "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9,
  395. "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F,
  396. "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE,
  397. "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA,
  398. "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0,
  399. "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  400. /**
  401. * @author mikael emtinger / http://gomo.se/
  402. * @author alteredq / http://alteredqualia.com/
  403. * @author WestLangley / http://github.com/WestLangley
  404. * @author bhouston / http://exocortex.com
  405. */
  406. THREE.Quaternion = function( x, y, z, w ) {
  407. this.x = x || 0;
  408. this.y = y || 0;
  409. this.z = z || 0;
  410. this.w = ( w !== undefined ) ? w : 1;
  411. };
  412. THREE.Quaternion.prototype = {
  413. constructor: THREE.Quaternion,
  414. set: function ( x, y, z, w ) {
  415. this.x = x;
  416. this.y = y;
  417. this.z = z;
  418. this.w = w;
  419. return this;
  420. },
  421. copy: function ( q ) {
  422. this.x = q.x;
  423. this.y = q.y;
  424. this.z = q.z;
  425. this.w = q.w;
  426. return this;
  427. },
  428. setFromEuler: function ( euler ) {
  429. if ( typeof euler['order'] === undefined ) {
  430. console.error( 'ERROR: Quaternion\'s .setFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  431. }
  432. // http://www.mathworks.com/matlabcentral/fileexchange/
  433. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  434. // content/SpinCalc.m
  435. var c1 = Math.cos( euler.x / 2 );
  436. var c2 = Math.cos( euler.y / 2 );
  437. var c3 = Math.cos( euler.z / 2 );
  438. var s1 = Math.sin( euler.x / 2 );
  439. var s2 = Math.sin( euler.y / 2 );
  440. var s3 = Math.sin( euler.z / 2 );
  441. if ( euler.order === undefined || euler.order === 'XYZ' ) {
  442. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  443. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  444. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  445. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  446. } else if ( euler.order === 'YXZ' ) {
  447. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  448. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  449. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  450. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  451. } else if ( euler.order === 'ZXY' ) {
  452. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  453. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  454. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  455. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  456. } else if ( euler.order === 'ZYX' ) {
  457. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  458. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  459. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  460. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  461. } else if ( euler.order === 'YZX' ) {
  462. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  463. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  464. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  465. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  466. } else if ( euler.order === 'XZY' ) {
  467. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  468. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  469. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  470. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  471. }
  472. return this;
  473. },
  474. setFromAxisAngle: function ( axis, angle ) {
  475. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  476. // axis have to be normalized
  477. var halfAngle = angle / 2,
  478. s = Math.sin( halfAngle );
  479. this.x = axis.x * s;
  480. this.y = axis.y * s;
  481. this.z = axis.z * s;
  482. this.w = Math.cos( halfAngle );
  483. return this;
  484. },
  485. setFromRotationMatrix: function ( m ) {
  486. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  487. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  488. var te = m.elements,
  489. m11 = te[0], m12 = te[4], m13 = te[8],
  490. m21 = te[1], m22 = te[5], m23 = te[9],
  491. m31 = te[2], m32 = te[6], m33 = te[10],
  492. trace = m11 + m22 + m33,
  493. s;
  494. if ( trace > 0 ) {
  495. s = 0.5 / Math.sqrt( trace + 1.0 );
  496. this.w = 0.25 / s;
  497. this.x = ( m32 - m23 ) * s;
  498. this.y = ( m13 - m31 ) * s;
  499. this.z = ( m21 - m12 ) * s;
  500. } else if ( m11 > m22 && m11 > m33 ) {
  501. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  502. this.w = (m32 - m23 ) / s;
  503. this.x = 0.25 * s;
  504. this.y = (m12 + m21 ) / s;
  505. this.z = (m13 + m31 ) / s;
  506. } else if ( m22 > m33 ) {
  507. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  508. this.w = (m13 - m31 ) / s;
  509. this.x = (m12 + m21 ) / s;
  510. this.y = 0.25 * s;
  511. this.z = (m23 + m32 ) / s;
  512. } else {
  513. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  514. this.w = ( m21 - m12 ) / s;
  515. this.x = ( m13 + m31 ) / s;
  516. this.y = ( m23 + m32 ) / s;
  517. this.z = 0.25 * s;
  518. }
  519. return this;
  520. },
  521. inverse: function () {
  522. this.conjugate().normalize();
  523. return this;
  524. },
  525. conjugate: function () {
  526. this.x *= -1;
  527. this.y *= -1;
  528. this.z *= -1;
  529. return this;
  530. },
  531. lengthSq: function () {
  532. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  533. },
  534. length: function () {
  535. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  536. },
  537. normalize: function () {
  538. var l = this.length();
  539. if ( l === 0 ) {
  540. this.x = 0;
  541. this.y = 0;
  542. this.z = 0;
  543. this.w = 1;
  544. } else {
  545. l = 1 / l;
  546. this.x = this.x * l;
  547. this.y = this.y * l;
  548. this.z = this.z * l;
  549. this.w = this.w * l;
  550. }
  551. return this;
  552. },
  553. multiply: function ( q, p ) {
  554. if ( p !== undefined ) {
  555. console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  556. return this.multiplyQuaternions( q, p );
  557. }
  558. return this.multiplyQuaternions( this, q );
  559. },
  560. multiplyQuaternions: function ( a, b ) {
  561. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  562. var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w;
  563. var qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  564. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  565. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  566. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  567. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  568. return this;
  569. },
  570. multiplyVector3: function ( vector ) {
  571. console.warn( 'DEPRECATED: Quaternion\'s .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  572. return vector.applyQuaternion( this );
  573. },
  574. slerp: function ( qb, t ) {
  575. var x = this.x, y = this.y, z = this.z, w = this.w;
  576. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  577. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  578. if ( cosHalfTheta < 0 ) {
  579. this.w = -qb.w;
  580. this.x = -qb.x;
  581. this.y = -qb.y;
  582. this.z = -qb.z;
  583. cosHalfTheta = -cosHalfTheta;
  584. } else {
  585. this.copy( qb );
  586. }
  587. if ( cosHalfTheta >= 1.0 ) {
  588. this.w = w;
  589. this.x = x;
  590. this.y = y;
  591. this.z = z;
  592. return this;
  593. }
  594. var halfTheta = Math.acos( cosHalfTheta );
  595. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  596. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  597. this.w = 0.5 * ( w + this.w );
  598. this.x = 0.5 * ( x + this.x );
  599. this.y = 0.5 * ( y + this.y );
  600. this.z = 0.5 * ( z + this.z );
  601. return this;
  602. }
  603. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  604. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  605. this.w = ( w * ratioA + this.w * ratioB );
  606. this.x = ( x * ratioA + this.x * ratioB );
  607. this.y = ( y * ratioA + this.y * ratioB );
  608. this.z = ( z * ratioA + this.z * ratioB );
  609. return this;
  610. },
  611. equals: function ( v ) {
  612. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  613. },
  614. fromArray: function ( array ) {
  615. this.x = array[ 0 ];
  616. this.y = array[ 1 ];
  617. this.z = array[ 2 ];
  618. this.w = array[ 3 ];
  619. return this;
  620. },
  621. toArray: function () {
  622. return [ this.x, this.y, this.z, this.w ];
  623. },
  624. clone: function () {
  625. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  626. }
  627. };
  628. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  629. return qm.copy( qa ).slerp( qb, t );
  630. }
  631. /**
  632. * @author mrdoob / http://mrdoob.com/
  633. * @author philogb / http://blog.thejit.org/
  634. * @author egraether / http://egraether.com/
  635. * @author zz85 / http://www.lab4games.net/zz85/blog
  636. */
  637. THREE.Vector2 = function ( x, y ) {
  638. this.x = x || 0;
  639. this.y = y || 0;
  640. };
  641. THREE.Vector2.prototype = {
  642. constructor: THREE.Vector2,
  643. set: function ( x, y ) {
  644. this.x = x;
  645. this.y = y;
  646. return this;
  647. },
  648. setX: function ( x ) {
  649. this.x = x;
  650. return this;
  651. },
  652. setY: function ( y ) {
  653. this.y = y;
  654. return this;
  655. },
  656. setComponent: function ( index, value ) {
  657. switch ( index ) {
  658. case 0: this.x = value; break;
  659. case 1: this.y = value; break;
  660. default: throw new Error( "index is out of range: " + index );
  661. }
  662. },
  663. getComponent: function ( index ) {
  664. switch ( index ) {
  665. case 0: return this.x;
  666. case 1: return this.y;
  667. default: throw new Error( "index is out of range: " + index );
  668. }
  669. },
  670. copy: function ( v ) {
  671. this.x = v.x;
  672. this.y = v.y;
  673. return this;
  674. },
  675. add: function ( v, w ) {
  676. if ( w !== undefined ) {
  677. console.warn( 'DEPRECATED: Vector2\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  678. return this.addVectors( v, w );
  679. }
  680. this.x += v.x;
  681. this.y += v.y;
  682. return this;
  683. },
  684. addVectors: function ( a, b ) {
  685. this.x = a.x + b.x;
  686. this.y = a.y + b.y;
  687. return this;
  688. },
  689. addScalar: function ( s ) {
  690. this.x += s;
  691. this.y += s;
  692. return this;
  693. },
  694. sub: function ( v, w ) {
  695. if ( w !== undefined ) {
  696. console.warn( 'DEPRECATED: Vector2\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  697. return this.subVectors( v, w );
  698. }
  699. this.x -= v.x;
  700. this.y -= v.y;
  701. return this;
  702. },
  703. subVectors: function ( a, b ) {
  704. this.x = a.x - b.x;
  705. this.y = a.y - b.y;
  706. return this;
  707. },
  708. multiplyScalar: function ( s ) {
  709. this.x *= s;
  710. this.y *= s;
  711. return this;
  712. },
  713. divideScalar: function ( s ) {
  714. if ( s !== 0 ) {
  715. this.x /= s;
  716. this.y /= s;
  717. } else {
  718. this.set( 0, 0 );
  719. }
  720. return this;
  721. },
  722. min: function ( v ) {
  723. if ( this.x > v.x ) {
  724. this.x = v.x;
  725. }
  726. if ( this.y > v.y ) {
  727. this.y = v.y;
  728. }
  729. return this;
  730. },
  731. max: function ( v ) {
  732. if ( this.x < v.x ) {
  733. this.x = v.x;
  734. }
  735. if ( this.y < v.y ) {
  736. this.y = v.y;
  737. }
  738. return this;
  739. },
  740. clamp: function ( min, max ) {
  741. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  742. if ( this.x < min.x ) {
  743. this.x = min.x;
  744. } else if ( this.x > max.x ) {
  745. this.x = max.x;
  746. }
  747. if ( this.y < min.y ) {
  748. this.y = min.y;
  749. } else if ( this.y > max.y ) {
  750. this.y = max.y;
  751. }
  752. return this;
  753. },
  754. negate: function() {
  755. return this.multiplyScalar( - 1 );
  756. },
  757. dot: function ( v ) {
  758. return this.x * v.x + this.y * v.y;
  759. },
  760. lengthSq: function () {
  761. return this.x * this.x + this.y * this.y;
  762. },
  763. length: function () {
  764. return Math.sqrt( this.x * this.x + this.y * this.y );
  765. },
  766. normalize: function () {
  767. return this.divideScalar( this.length() );
  768. },
  769. distanceTo: function ( v ) {
  770. return Math.sqrt( this.distanceToSquared( v ) );
  771. },
  772. distanceToSquared: function ( v ) {
  773. var dx = this.x - v.x, dy = this.y - v.y;
  774. return dx * dx + dy * dy;
  775. },
  776. setLength: function ( l ) {
  777. var oldLength = this.length();
  778. if ( oldLength !== 0 && l !== oldLength ) {
  779. this.multiplyScalar( l / oldLength );
  780. }
  781. return this;
  782. },
  783. lerp: function ( v, alpha ) {
  784. this.x += ( v.x - this.x ) * alpha;
  785. this.y += ( v.y - this.y ) * alpha;
  786. return this;
  787. },
  788. equals: function( v ) {
  789. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  790. },
  791. fromArray: function ( array ) {
  792. this.x = array[ 0 ];
  793. this.y = array[ 1 ];
  794. return this;
  795. },
  796. toArray: function () {
  797. return [ this.x, this.y ];
  798. },
  799. clone: function () {
  800. return new THREE.Vector2( this.x, this.y );
  801. }
  802. };
  803. /**
  804. * @author mrdoob / http://mrdoob.com/
  805. * @author *kile / http://kile.stravaganza.org/
  806. * @author philogb / http://blog.thejit.org/
  807. * @author mikael emtinger / http://gomo.se/
  808. * @author egraether / http://egraether.com/
  809. * @author WestLangley / http://github.com/WestLangley
  810. */
  811. THREE.Vector3 = function ( x, y, z ) {
  812. this.x = x || 0;
  813. this.y = y || 0;
  814. this.z = z || 0;
  815. };
  816. THREE.Vector3.prototype = {
  817. constructor: THREE.Vector3,
  818. set: function ( x, y, z ) {
  819. this.x = x;
  820. this.y = y;
  821. this.z = z;
  822. return this;
  823. },
  824. setX: function ( x ) {
  825. this.x = x;
  826. return this;
  827. },
  828. setY: function ( y ) {
  829. this.y = y;
  830. return this;
  831. },
  832. setZ: function ( z ) {
  833. this.z = z;
  834. return this;
  835. },
  836. setComponent: function ( index, value ) {
  837. switch ( index ) {
  838. case 0: this.x = value; break;
  839. case 1: this.y = value; break;
  840. case 2: this.z = value; break;
  841. default: throw new Error( "index is out of range: " + index );
  842. }
  843. },
  844. getComponent: function ( index ) {
  845. switch ( index ) {
  846. case 0: return this.x;
  847. case 1: return this.y;
  848. case 2: return this.z;
  849. default: throw new Error( "index is out of range: " + index );
  850. }
  851. },
  852. copy: function ( v ) {
  853. this.x = v.x;
  854. this.y = v.y;
  855. this.z = v.z;
  856. return this;
  857. },
  858. add: function ( v, w ) {
  859. if ( w !== undefined ) {
  860. console.warn( 'DEPRECATED: Vector3\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  861. return this.addVectors( v, w );
  862. }
  863. this.x += v.x;
  864. this.y += v.y;
  865. this.z += v.z;
  866. return this;
  867. },
  868. addScalar: function ( s ) {
  869. this.x += s;
  870. this.y += s;
  871. this.z += s;
  872. return this;
  873. },
  874. addVectors: function ( a, b ) {
  875. this.x = a.x + b.x;
  876. this.y = a.y + b.y;
  877. this.z = a.z + b.z;
  878. return this;
  879. },
  880. sub: function ( v, w ) {
  881. if ( w !== undefined ) {
  882. console.warn( 'DEPRECATED: Vector3\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  883. return this.subVectors( v, w );
  884. }
  885. this.x -= v.x;
  886. this.y -= v.y;
  887. this.z -= v.z;
  888. return this;
  889. },
  890. subVectors: function ( a, b ) {
  891. this.x = a.x - b.x;
  892. this.y = a.y - b.y;
  893. this.z = a.z - b.z;
  894. return this;
  895. },
  896. multiply: function ( v, w ) {
  897. if ( w !== undefined ) {
  898. console.warn( 'DEPRECATED: Vector3\'s .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  899. return this.multiplyVectors( v, w );
  900. }
  901. this.x *= v.x;
  902. this.y *= v.y;
  903. this.z *= v.z;
  904. return this;
  905. },
  906. multiplyScalar: function ( s ) {
  907. this.x *= s;
  908. this.y *= s;
  909. this.z *= s;
  910. return this;
  911. },
  912. multiplyVectors: function ( a, b ) {
  913. this.x = a.x * b.x;
  914. this.y = a.y * b.y;
  915. this.z = a.z * b.z;
  916. return this;
  917. },
  918. applyMatrix3: function ( m ) {
  919. var x = this.x;
  920. var y = this.y;
  921. var z = this.z;
  922. var e = m.elements;
  923. this.x = e[0] * x + e[3] * y + e[6] * z;
  924. this.y = e[1] * x + e[4] * y + e[7] * z;
  925. this.z = e[2] * x + e[5] * y + e[8] * z;
  926. return this;
  927. },
  928. applyMatrix4: function ( m ) {
  929. // input: THREE.Matrix4 affine matrix
  930. var x = this.x, y = this.y, z = this.z;
  931. var e = m.elements;
  932. this.x = e[0] * x + e[4] * y + e[8] * z + e[12];
  933. this.y = e[1] * x + e[5] * y + e[9] * z + e[13];
  934. this.z = e[2] * x + e[6] * y + e[10] * z + e[14];
  935. return this;
  936. },
  937. applyProjection: function ( m ) {
  938. // input: THREE.Matrix4 projection matrix
  939. var x = this.x, y = this.y, z = this.z;
  940. var e = m.elements;
  941. var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] ); // perspective divide
  942. this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
  943. this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
  944. this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
  945. return this;
  946. },
  947. applyQuaternion: function ( q ) {
  948. var x = this.x;
  949. var y = this.y;
  950. var z = this.z;
  951. var qx = q.x;
  952. var qy = q.y;
  953. var qz = q.z;
  954. var qw = q.w;
  955. // calculate quat * vector
  956. var ix = qw * x + qy * z - qz * y;
  957. var iy = qw * y + qz * x - qx * z;
  958. var iz = qw * z + qx * y - qy * x;
  959. var iw = -qx * x - qy * y - qz * z;
  960. // calculate result * inverse quat
  961. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  962. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  963. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  964. return this;
  965. },
  966. transformDirection: function ( m ) {
  967. // input: THREE.Matrix4 affine matrix
  968. // vector interpreted as a direction
  969. var x = this.x, y = this.y, z = this.z;
  970. var e = m.elements;
  971. this.x = e[0] * x + e[4] * y + e[8] * z;
  972. this.y = e[1] * x + e[5] * y + e[9] * z;
  973. this.z = e[2] * x + e[6] * y + e[10] * z;
  974. this.normalize();
  975. return this;
  976. },
  977. divide: function ( v ) {
  978. this.x /= v.x;
  979. this.y /= v.y;
  980. this.z /= v.z;
  981. return this;
  982. },
  983. divideScalar: function ( s ) {
  984. if ( s !== 0 ) {
  985. this.x /= s;
  986. this.y /= s;
  987. this.z /= s;
  988. } else {
  989. this.x = 0;
  990. this.y = 0;
  991. this.z = 0;
  992. }
  993. return this;
  994. },
  995. min: function ( v ) {
  996. if ( this.x > v.x ) {
  997. this.x = v.x;
  998. }
  999. if ( this.y > v.y ) {
  1000. this.y = v.y;
  1001. }
  1002. if ( this.z > v.z ) {
  1003. this.z = v.z;
  1004. }
  1005. return this;
  1006. },
  1007. max: function ( v ) {
  1008. if ( this.x < v.x ) {
  1009. this.x = v.x;
  1010. }
  1011. if ( this.y < v.y ) {
  1012. this.y = v.y;
  1013. }
  1014. if ( this.z < v.z ) {
  1015. this.z = v.z;
  1016. }
  1017. return this;
  1018. },
  1019. clamp: function ( min, max ) {
  1020. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1021. if ( this.x < min.x ) {
  1022. this.x = min.x;
  1023. } else if ( this.x > max.x ) {
  1024. this.x = max.x;
  1025. }
  1026. if ( this.y < min.y ) {
  1027. this.y = min.y;
  1028. } else if ( this.y > max.y ) {
  1029. this.y = max.y;
  1030. }
  1031. if ( this.z < min.z ) {
  1032. this.z = min.z;
  1033. } else if ( this.z > max.z ) {
  1034. this.z = max.z;
  1035. }
  1036. return this;
  1037. },
  1038. negate: function () {
  1039. return this.multiplyScalar( - 1 );
  1040. },
  1041. dot: function ( v ) {
  1042. return this.x * v.x + this.y * v.y + this.z * v.z;
  1043. },
  1044. lengthSq: function () {
  1045. return this.x * this.x + this.y * this.y + this.z * this.z;
  1046. },
  1047. length: function () {
  1048. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1049. },
  1050. lengthManhattan: function () {
  1051. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1052. },
  1053. normalize: function () {
  1054. return this.divideScalar( this.length() );
  1055. },
  1056. setLength: function ( l ) {
  1057. var oldLength = this.length();
  1058. if ( oldLength !== 0 && l !== oldLength ) {
  1059. this.multiplyScalar( l / oldLength );
  1060. }
  1061. return this;
  1062. },
  1063. lerp: function ( v, alpha ) {
  1064. this.x += ( v.x - this.x ) * alpha;
  1065. this.y += ( v.y - this.y ) * alpha;
  1066. this.z += ( v.z - this.z ) * alpha;
  1067. return this;
  1068. },
  1069. cross: function ( v, w ) {
  1070. if ( w !== undefined ) {
  1071. console.warn( 'DEPRECATED: Vector3\'s .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1072. return this.crossVectors( v, w );
  1073. }
  1074. var x = this.x, y = this.y, z = this.z;
  1075. this.x = y * v.z - z * v.y;
  1076. this.y = z * v.x - x * v.z;
  1077. this.z = x * v.y - y * v.x;
  1078. return this;
  1079. },
  1080. crossVectors: function ( a, b ) {
  1081. this.x = a.y * b.z - a.z * b.y;
  1082. this.y = a.z * b.x - a.x * b.z;
  1083. this.z = a.x * b.y - a.y * b.x;
  1084. return this;
  1085. },
  1086. angleTo: function ( v ) {
  1087. var theta = this.dot( v ) / ( this.length() * v.length() );
  1088. // clamp, to handle numerical problems
  1089. return Math.acos( THREE.Math.clamp( theta, -1, 1 ) );
  1090. },
  1091. distanceTo: function ( v ) {
  1092. return Math.sqrt( this.distanceToSquared( v ) );
  1093. },
  1094. distanceToSquared: function ( v ) {
  1095. var dx = this.x - v.x;
  1096. var dy = this.y - v.y;
  1097. var dz = this.z - v.z;
  1098. return dx * dx + dy * dy + dz * dz;
  1099. },
  1100. setEulerFromRotationMatrix: function ( m, order ) {
  1101. console.error( "REMOVED: Vector3\'s setEulerFromRotationMatrix has been removed in favor of Euler.setFromRotationMatrix(), please update your code.");
  1102. },
  1103. setEulerFromQuaternion: function ( q, order ) {
  1104. console.error( "REMOVED: Vector3\'s setEulerFromQuaternion: has been removed in favor of Euler.setFromQuaternion(), please update your code.");
  1105. },
  1106. getPositionFromMatrix: function ( m ) {
  1107. this.x = m.elements[12];
  1108. this.y = m.elements[13];
  1109. this.z = m.elements[14];
  1110. return this;
  1111. },
  1112. getScaleFromMatrix: function ( m ) {
  1113. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  1114. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  1115. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  1116. this.x = sx;
  1117. this.y = sy;
  1118. this.z = sz;
  1119. return this;
  1120. },
  1121. getColumnFromMatrix: function ( index, matrix ) {
  1122. var offset = index * 4;
  1123. var me = matrix.elements;
  1124. this.x = me[ offset ];
  1125. this.y = me[ offset + 1 ];
  1126. this.z = me[ offset + 2 ];
  1127. return this;
  1128. },
  1129. equals: function ( v ) {
  1130. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1131. },
  1132. fromArray: function ( array ) {
  1133. this.x = array[ 0 ];
  1134. this.y = array[ 1 ];
  1135. this.z = array[ 2 ];
  1136. return this;
  1137. },
  1138. toArray: function () {
  1139. return [ this.x, this.y, this.z ];
  1140. },
  1141. clone: function () {
  1142. return new THREE.Vector3( this.x, this.y, this.z );
  1143. }
  1144. };
  1145. THREE.extend( THREE.Vector3.prototype, {
  1146. applyEuler: function () {
  1147. var q1 = new THREE.Quaternion();
  1148. return function ( rotation ) {
  1149. if( typeof rotation['order'] === undefined ) {
  1150. console.error( 'ERROR: Vector3\'s .applyEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  1151. }
  1152. var quaternion = q1.setFromEuler( rotation );
  1153. this.applyQuaternion( quaternion );
  1154. return this;
  1155. };
  1156. }(),
  1157. applyAxisAngle: function () {
  1158. var q1 = new THREE.Quaternion();
  1159. return function ( axis, angle ) {
  1160. var quaternion = q1.setFromAxisAngle( axis, angle );
  1161. this.applyQuaternion( quaternion );
  1162. return this;
  1163. };
  1164. }(),
  1165. projectOnVector: function () {
  1166. var v1 = new THREE.Vector3();
  1167. return function ( vector ) {
  1168. v1.copy( vector ).normalize();
  1169. var d = this.dot( v1 );
  1170. return this.copy( v1 ).multiplyScalar( d );
  1171. };
  1172. }(),
  1173. projectOnPlane: function () {
  1174. var v1 = new THREE.Vector3();
  1175. return function ( planeNormal ) {
  1176. v1.copy( this ).projectOnVector( planeNormal );
  1177. return this.sub( v1 );
  1178. }
  1179. }(),
  1180. reflect: function () {
  1181. var v1 = new THREE.Vector3();
  1182. return function ( vector ) {
  1183. v1.copy( this ).projectOnVector( vector ).multiplyScalar( 2 );
  1184. return this.subVectors( v1, this );
  1185. }
  1186. }()
  1187. } );
  1188. /**
  1189. * @author supereggbert / http://www.paulbrunt.co.uk/
  1190. * @author philogb / http://blog.thejit.org/
  1191. * @author mikael emtinger / http://gomo.se/
  1192. * @author egraether / http://egraether.com/
  1193. * @author WestLangley / http://github.com/WestLangley
  1194. */
  1195. THREE.Vector4 = function ( x, y, z, w ) {
  1196. this.x = x || 0;
  1197. this.y = y || 0;
  1198. this.z = z || 0;
  1199. this.w = ( w !== undefined ) ? w : 1;
  1200. };
  1201. THREE.Vector4.prototype = {
  1202. constructor: THREE.Vector4,
  1203. set: function ( x, y, z, w ) {
  1204. this.x = x;
  1205. this.y = y;
  1206. this.z = z;
  1207. this.w = w;
  1208. return this;
  1209. },
  1210. setX: function ( x ) {
  1211. this.x = x;
  1212. return this;
  1213. },
  1214. setY: function ( y ) {
  1215. this.y = y;
  1216. return this;
  1217. },
  1218. setZ: function ( z ) {
  1219. this.z = z;
  1220. return this;
  1221. },
  1222. setW: function ( w ) {
  1223. this.w = w;
  1224. return this;
  1225. },
  1226. setComponent: function ( index, value ) {
  1227. switch ( index ) {
  1228. case 0: this.x = value; break;
  1229. case 1: this.y = value; break;
  1230. case 2: this.z = value; break;
  1231. case 3: this.w = value; break;
  1232. default: throw new Error( "index is out of range: " + index );
  1233. }
  1234. },
  1235. getComponent: function ( index ) {
  1236. switch ( index ) {
  1237. case 0: return this.x;
  1238. case 1: return this.y;
  1239. case 2: return this.z;
  1240. case 3: return this.w;
  1241. default: throw new Error( "index is out of range: " + index );
  1242. }
  1243. },
  1244. copy: function ( v ) {
  1245. this.x = v.x;
  1246. this.y = v.y;
  1247. this.z = v.z;
  1248. this.w = ( v.w !== undefined ) ? v.w : 1;
  1249. return this;
  1250. },
  1251. add: function ( v, w ) {
  1252. if ( w !== undefined ) {
  1253. console.warn( 'DEPRECATED: Vector4\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1254. return this.addVectors( v, w );
  1255. }
  1256. this.x += v.x;
  1257. this.y += v.y;
  1258. this.z += v.z;
  1259. this.w += v.w;
  1260. return this;
  1261. },
  1262. addScalar: function ( s ) {
  1263. this.x += s;
  1264. this.y += s;
  1265. this.z += s;
  1266. this.w += s;
  1267. return this;
  1268. },
  1269. addVectors: function ( a, b ) {
  1270. this.x = a.x + b.x;
  1271. this.y = a.y + b.y;
  1272. this.z = a.z + b.z;
  1273. this.w = a.w + b.w;
  1274. return this;
  1275. },
  1276. sub: function ( v, w ) {
  1277. if ( w !== undefined ) {
  1278. console.warn( 'DEPRECATED: Vector4\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1279. return this.subVectors( v, w );
  1280. }
  1281. this.x -= v.x;
  1282. this.y -= v.y;
  1283. this.z -= v.z;
  1284. this.w -= v.w;
  1285. return this;
  1286. },
  1287. subVectors: function ( a, b ) {
  1288. this.x = a.x - b.x;
  1289. this.y = a.y - b.y;
  1290. this.z = a.z - b.z;
  1291. this.w = a.w - b.w;
  1292. return this;
  1293. },
  1294. multiplyScalar: function ( s ) {
  1295. this.x *= s;
  1296. this.y *= s;
  1297. this.z *= s;
  1298. this.w *= s;
  1299. return this;
  1300. },
  1301. applyMatrix4: function ( m ) {
  1302. var x = this.x;
  1303. var y = this.y;
  1304. var z = this.z;
  1305. var w = this.w;
  1306. var e = m.elements;
  1307. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1308. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1309. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1310. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1311. return this;
  1312. },
  1313. divideScalar: function ( s ) {
  1314. if ( s !== 0 ) {
  1315. this.x /= s;
  1316. this.y /= s;
  1317. this.z /= s;
  1318. this.w /= s;
  1319. } else {
  1320. this.x = 0;
  1321. this.y = 0;
  1322. this.z = 0;
  1323. this.w = 1;
  1324. }
  1325. return this;
  1326. },
  1327. setAxisAngleFromQuaternion: function ( q ) {
  1328. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1329. // q is assumed to be normalized
  1330. this.w = 2 * Math.acos( q.w );
  1331. var s = Math.sqrt( 1 - q.w * q.w );
  1332. if ( s < 0.0001 ) {
  1333. this.x = 1;
  1334. this.y = 0;
  1335. this.z = 0;
  1336. } else {
  1337. this.x = q.x / s;
  1338. this.y = q.y / s;
  1339. this.z = q.z / s;
  1340. }
  1341. return this;
  1342. },
  1343. setAxisAngleFromRotationMatrix: function ( m ) {
  1344. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1345. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1346. var angle, x, y, z, // variables for result
  1347. epsilon = 0.01, // margin to allow for rounding errors
  1348. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1349. te = m.elements,
  1350. m11 = te[0], m12 = te[4], m13 = te[8],
  1351. m21 = te[1], m22 = te[5], m23 = te[9],
  1352. m31 = te[2], m32 = te[6], m33 = te[10];
  1353. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1354. && ( Math.abs( m13 - m31 ) < epsilon )
  1355. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1356. // singularity found
  1357. // first check for identity matrix which must have +1 for all terms
  1358. // in leading diagonal and zero in other terms
  1359. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1360. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1361. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1362. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1363. // this singularity is identity matrix so angle = 0
  1364. this.set( 1, 0, 0, 0 );
  1365. return this; // zero angle, arbitrary axis
  1366. }
  1367. // otherwise this singularity is angle = 180
  1368. angle = Math.PI;
  1369. var xx = ( m11 + 1 ) / 2;
  1370. var yy = ( m22 + 1 ) / 2;
  1371. var zz = ( m33 + 1 ) / 2;
  1372. var xy = ( m12 + m21 ) / 4;
  1373. var xz = ( m13 + m31 ) / 4;
  1374. var yz = ( m23 + m32 ) / 4;
  1375. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1376. if ( xx < epsilon ) {
  1377. x = 0;
  1378. y = 0.707106781;
  1379. z = 0.707106781;
  1380. } else {
  1381. x = Math.sqrt( xx );
  1382. y = xy / x;
  1383. z = xz / x;
  1384. }
  1385. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1386. if ( yy < epsilon ) {
  1387. x = 0.707106781;
  1388. y = 0;
  1389. z = 0.707106781;
  1390. } else {
  1391. y = Math.sqrt( yy );
  1392. x = xy / y;
  1393. z = yz / y;
  1394. }
  1395. } else { // m33 is the largest diagonal term so base result on this
  1396. if ( zz < epsilon ) {
  1397. x = 0.707106781;
  1398. y = 0.707106781;
  1399. z = 0;
  1400. } else {
  1401. z = Math.sqrt( zz );
  1402. x = xz / z;
  1403. y = yz / z;
  1404. }
  1405. }
  1406. this.set( x, y, z, angle );
  1407. return this; // return 180 deg rotation
  1408. }
  1409. // as we have reached here there are no singularities so we can handle normally
  1410. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1411. + ( m13 - m31 ) * ( m13 - m31 )
  1412. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1413. if ( Math.abs( s ) < 0.001 ) s = 1;
  1414. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1415. // caught by singularity test above, but I've left it in just in case
  1416. this.x = ( m32 - m23 ) / s;
  1417. this.y = ( m13 - m31 ) / s;
  1418. this.z = ( m21 - m12 ) / s;
  1419. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1420. return this;
  1421. },
  1422. min: function ( v ) {
  1423. if ( this.x > v.x ) {
  1424. this.x = v.x;
  1425. }
  1426. if ( this.y > v.y ) {
  1427. this.y = v.y;
  1428. }
  1429. if ( this.z > v.z ) {
  1430. this.z = v.z;
  1431. }
  1432. if ( this.w > v.w ) {
  1433. this.w = v.w;
  1434. }
  1435. return this;
  1436. },
  1437. max: function ( v ) {
  1438. if ( this.x < v.x ) {
  1439. this.x = v.x;
  1440. }
  1441. if ( this.y < v.y ) {
  1442. this.y = v.y;
  1443. }
  1444. if ( this.z < v.z ) {
  1445. this.z = v.z;
  1446. }
  1447. if ( this.w < v.w ) {
  1448. this.w = v.w;
  1449. }
  1450. return this;
  1451. },
  1452. clamp: function ( min, max ) {
  1453. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1454. if ( this.x < min.x ) {
  1455. this.x = min.x;
  1456. } else if ( this.x > max.x ) {
  1457. this.x = max.x;
  1458. }
  1459. if ( this.y < min.y ) {
  1460. this.y = min.y;
  1461. } else if ( this.y > max.y ) {
  1462. this.y = max.y;
  1463. }
  1464. if ( this.z < min.z ) {
  1465. this.z = min.z;
  1466. } else if ( this.z > max.z ) {
  1467. this.z = max.z;
  1468. }
  1469. if ( this.w < min.w ) {
  1470. this.w = min.w;
  1471. } else if ( this.w > max.w ) {
  1472. this.w = max.w;
  1473. }
  1474. return this;
  1475. },
  1476. negate: function() {
  1477. return this.multiplyScalar( -1 );
  1478. },
  1479. dot: function ( v ) {
  1480. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1481. },
  1482. lengthSq: function () {
  1483. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1484. },
  1485. length: function () {
  1486. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1487. },
  1488. lengthManhattan: function () {
  1489. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1490. },
  1491. normalize: function () {
  1492. return this.divideScalar( this.length() );
  1493. },
  1494. setLength: function ( l ) {
  1495. var oldLength = this.length();
  1496. if ( oldLength !== 0 && l !== oldLength ) {
  1497. this.multiplyScalar( l / oldLength );
  1498. }
  1499. return this;
  1500. },
  1501. lerp: function ( v, alpha ) {
  1502. this.x += ( v.x - this.x ) * alpha;
  1503. this.y += ( v.y - this.y ) * alpha;
  1504. this.z += ( v.z - this.z ) * alpha;
  1505. this.w += ( v.w - this.w ) * alpha;
  1506. return this;
  1507. },
  1508. equals: function ( v ) {
  1509. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1510. },
  1511. fromArray: function ( array ) {
  1512. this.x = array[ 0 ];
  1513. this.y = array[ 1 ];
  1514. this.z = array[ 2 ];
  1515. this.w = array[ 3 ];
  1516. return this;
  1517. },
  1518. toArray: function () {
  1519. return [ this.x, this.y, this.z, this.w ];
  1520. },
  1521. clone: function () {
  1522. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1523. }
  1524. };
  1525. /**
  1526. * @author mrdoob / http://mrdoob.com/
  1527. * @author WestLangley / http://github.com/WestLangley
  1528. * @author bhouston / http://exocortex.com
  1529. */
  1530. THREE.Euler = function ( x, y, z, order ) {
  1531. this.x = x || 0;
  1532. this.y = y || 0;
  1533. this.z = z || 0;
  1534. this.order = order || THREE.Euler.DefaultOrder;
  1535. };
  1536. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1537. THREE.Euler.DefaultOrder = 'XYZ';
  1538. THREE.Euler.prototype = {
  1539. constructor: THREE.Euler,
  1540. set: function ( x, y, z, order ) {
  1541. this.x = x;
  1542. this.y = y;
  1543. this.z = z;
  1544. this.order = order || this.order;
  1545. return this;
  1546. },
  1547. copy: function ( e ) {
  1548. this.x = e.x;
  1549. this.y = e.y;
  1550. this.z = e.z;
  1551. this.order = e.order;
  1552. return this;
  1553. },
  1554. setFromRotationMatrix: function ( m, order ) {
  1555. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1556. // clamp, to handle numerical problems
  1557. function clamp( x ) {
  1558. return Math.min( Math.max( x, -1 ), 1 );
  1559. }
  1560. var te = m.elements;
  1561. var m11 = te[0], m12 = te[4], m13 = te[8];
  1562. var m21 = te[1], m22 = te[5], m23 = te[9];
  1563. var m31 = te[2], m32 = te[6], m33 = te[10];
  1564. order = order || this.order;
  1565. if ( order === 'XYZ' ) {
  1566. this.y = Math.asin( clamp( m13 ) );
  1567. if ( Math.abs( m13 ) < 0.99999 ) {
  1568. this.x = Math.atan2( - m23, m33 );
  1569. this.z = Math.atan2( - m12, m11 );
  1570. } else {
  1571. this.x = Math.atan2( m32, m22 );
  1572. this.z = 0;
  1573. }
  1574. } else if ( order === 'YXZ' ) {
  1575. this.x = Math.asin( - clamp( m23 ) );
  1576. if ( Math.abs( m23 ) < 0.99999 ) {
  1577. this.y = Math.atan2( m13, m33 );
  1578. this.z = Math.atan2( m21, m22 );
  1579. } else {
  1580. this.y = Math.atan2( - m31, m11 );
  1581. this.z = 0;
  1582. }
  1583. } else if ( order === 'ZXY' ) {
  1584. this.x = Math.asin( clamp( m32 ) );
  1585. if ( Math.abs( m32 ) < 0.99999 ) {
  1586. this.y = Math.atan2( - m31, m33 );
  1587. this.z = Math.atan2( - m12, m22 );
  1588. } else {
  1589. this.y = 0;
  1590. this.z = Math.atan2( m21, m11 );
  1591. }
  1592. } else if ( order === 'ZYX' ) {
  1593. this.y = Math.asin( - clamp( m31 ) );
  1594. if ( Math.abs( m31 ) < 0.99999 ) {
  1595. this.x = Math.atan2( m32, m33 );
  1596. this.z = Math.atan2( m21, m11 );
  1597. } else {
  1598. this.x = 0;
  1599. this.z = Math.atan2( - m12, m22 );
  1600. }
  1601. } else if ( order === 'YZX' ) {
  1602. this.z = Math.asin( clamp( m21 ) );
  1603. if ( Math.abs( m21 ) < 0.99999 ) {
  1604. this.x = Math.atan2( - m23, m22 );
  1605. this.y = Math.atan2( - m31, m11 );
  1606. } else {
  1607. this.x = 0;
  1608. this.y = Math.atan2( m13, m33 );
  1609. }
  1610. } else if ( order === 'XZY' ) {
  1611. this.z = Math.asin( - clamp( m12 ) );
  1612. if ( Math.abs( m12 ) < 0.99999 ) {
  1613. this.x = Math.atan2( m32, m22 );
  1614. this.y = Math.atan2( m13, m11 );
  1615. } else {
  1616. this.x = Math.atan2( - m23, m33 );
  1617. this.y = 0;
  1618. }
  1619. } else {
  1620. console.warn( 'WARNING: Euler.setFromRotationMatrix() given unsupported order: ' + order )
  1621. }
  1622. this.order = order;
  1623. return this;
  1624. },
  1625. setFromQuaternion: function ( q, order ) {
  1626. // q is assumed to be normalized
  1627. // clamp, to handle numerical problems
  1628. function clamp( x ) {
  1629. return Math.min( Math.max( x, -1 ), 1 );
  1630. }
  1631. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  1632. var sqx = q.x * q.x;
  1633. var sqy = q.y * q.y;
  1634. var sqz = q.z * q.z;
  1635. var sqw = q.w * q.w;
  1636. order = order || this.order;
  1637. if ( order === 'XYZ' ) {
  1638. this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  1639. this.y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  1640. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  1641. } else if ( order === 'YXZ' ) {
  1642. this.x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  1643. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  1644. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  1645. } else if ( order === 'ZXY' ) {
  1646. this.x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  1647. this.y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  1648. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  1649. } else if ( order === 'ZYX' ) {
  1650. this.x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  1651. this.y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  1652. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  1653. } else if ( order === 'YZX' ) {
  1654. this.x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  1655. this.y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  1656. this.z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  1657. } else if ( order === 'XZY' ) {
  1658. this.x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  1659. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  1660. this.z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  1661. } else {
  1662. console.warn( 'WARNING: Euler.setFromQuaternion() given unsupported order: ' + order )
  1663. }
  1664. this.order = order;
  1665. return this;
  1666. },
  1667. reorder: function() {
  1668. // WARNING: this discards revolution information -bhouston
  1669. var q = new THREE.Quaternion();
  1670. return function( newOrder ) {
  1671. q.setFromEuler( this );
  1672. this.setFromQuaternion( q, newOrder );
  1673. };
  1674. }(),
  1675. fromArray: function ( array ) {
  1676. this.x = array[ 0 ];
  1677. this.y = array[ 1 ];
  1678. this.z = array[ 2 ];
  1679. this.order = array[ 3 ];
  1680. return this;
  1681. },
  1682. toArray: function () {
  1683. return [ this.x, this.y, this.z, this.order ];
  1684. },
  1685. equals: function ( rotation ) {
  1686. return ( ( rotation.x === this.x ) && ( rotation.y === this.y ) && ( rotation.z === this.z ) && ( rotation.order === this.order ) );
  1687. },
  1688. clone: function () {
  1689. return new THREE.Euler( this.x, this.y, this.z, this.order );
  1690. }
  1691. };
  1692. /**
  1693. * @author mrdoob / http://mrdoob.com/
  1694. * @author bhouston / http://exocortex.com/
  1695. */
  1696. THREE.Rotation = function ( quaternion ) {
  1697. this.euler = new THREE.Euler();
  1698. this.quaternion = quaternion;
  1699. this.updateEuler();
  1700. };
  1701. THREE.Rotation.prototype = {
  1702. get x () {
  1703. return this.euler.x;
  1704. },
  1705. set x ( value ) {
  1706. this.euler.x = value;
  1707. this.updateQuaternion();
  1708. },
  1709. get y () {
  1710. return this.euler.y;
  1711. },
  1712. set y ( value ) {
  1713. this.euler.y = value;
  1714. this.updateQuaternion();
  1715. },
  1716. get z () {
  1717. return this.euler.z;
  1718. },
  1719. set z ( value ) {
  1720. this.euler.z = value;
  1721. this.updateQuaternion();
  1722. },
  1723. //
  1724. set: function ( x, y, z ) {
  1725. this.euler.x = x;
  1726. this.euler.y = y;
  1727. this.euler.z = z;
  1728. this.updateQuaternion();
  1729. return this;
  1730. },
  1731. setX: function ( x ) {
  1732. this.euler.x = x;
  1733. this.updateQuaternion();
  1734. return this;
  1735. },
  1736. setY: function ( y ) {
  1737. this.euler.y = y;
  1738. this.updateQuaternion();
  1739. return this;
  1740. },
  1741. setZ: function ( z ) {
  1742. this.euler.z = z;
  1743. this.updateQuaternion();
  1744. return this;
  1745. },
  1746. setEulerFromRotationMatrix: function ( matrix, order ) {
  1747. console.warn( 'DEPRECATED: Rotation\'s .setEulerFromRotationMatrix() has been renamed to .setFromRotationMatrix().' );
  1748. return this.setFromRotationMatrix( matrix, order );
  1749. },
  1750. setFromRotationMatrix: function ( matrix, order ) {
  1751. this.euler.setFromRotationMatrix( matrix, order );
  1752. this.updateQuaternion();
  1753. return this;
  1754. },
  1755. setFromQuaternion: function ( quaternion, order ) {
  1756. this.euler.setFromQuaternion( quaternion, order );
  1757. this.quaternion.copy( quaternion );
  1758. return this;
  1759. },
  1760. copy: function ( rotation ) {
  1761. this.euler.copy( rotation.euler );
  1762. this.quaternion.copy( rotation.quaternion );
  1763. return this;
  1764. },
  1765. fromArray: function ( array ) {
  1766. this.euler.fromArray( array );
  1767. this.updateQuaternion();
  1768. return this;
  1769. },
  1770. toArray: function () {
  1771. return this.euler.toArray();
  1772. },
  1773. updateEuler: function () {
  1774. this.euler.setFromQuaternion( this.quaternion );
  1775. return this;
  1776. },
  1777. updateQuaternion: function () {
  1778. this.quaternion.setFromEuler( this.euler );
  1779. return this;
  1780. }
  1781. };
  1782. /**
  1783. * @author bhouston / http://exocortex.com
  1784. */
  1785. THREE.Line3 = function ( start, end ) {
  1786. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  1787. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  1788. };
  1789. THREE.Line3.prototype = {
  1790. constructor: THREE.Line3,
  1791. set: function ( start, end ) {
  1792. this.start.copy( start );
  1793. this.end.copy( end );
  1794. return this;
  1795. },
  1796. copy: function ( line ) {
  1797. this.start.copy( line.start );
  1798. this.end.copy( line.end );
  1799. return this;
  1800. },
  1801. center: function ( optionalTarget ) {
  1802. var result = optionalTarget || new THREE.Vector3();
  1803. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  1804. },
  1805. delta: function ( optionalTarget ) {
  1806. var result = optionalTarget || new THREE.Vector3();
  1807. return result.subVectors( this.end, this.start );
  1808. },
  1809. distanceSq: function () {
  1810. return this.start.distanceToSquared( this.end );
  1811. },
  1812. distance: function () {
  1813. return this.start.distanceTo( this.end );
  1814. },
  1815. at: function ( t, optionalTarget ) {
  1816. var result = optionalTarget || new THREE.Vector3();
  1817. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1818. },
  1819. closestPointToPointParameter: function() {
  1820. var startP = new THREE.Vector3();
  1821. var startEnd = new THREE.Vector3();
  1822. return function ( point, clampToLine ) {
  1823. startP.subVectors( point, this.start );
  1824. startEnd.subVectors( this.end, this.start );
  1825. var startEnd2 = startEnd.dot( startEnd );
  1826. var startEnd_startP = startEnd.dot( startP );
  1827. var t = startEnd_startP / startEnd2;
  1828. if ( clampToLine ) {
  1829. t = THREE.Math.clamp( t, 0, 1 );
  1830. }
  1831. return t;
  1832. };
  1833. }(),
  1834. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  1835. var t = this.closestPointToPointParameter( point, clampToLine );
  1836. var result = optionalTarget || new THREE.Vector3();
  1837. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1838. },
  1839. applyMatrix4: function ( matrix ) {
  1840. this.start.applyMatrix4( matrix );
  1841. this.end.applyMatrix4( matrix );
  1842. return this;
  1843. },
  1844. equals: function ( line ) {
  1845. return line.start.equals( this.start ) && line.end.equals( this.end );
  1846. },
  1847. clone: function () {
  1848. return new THREE.Line3().copy( this );
  1849. }
  1850. };
  1851. /**
  1852. * @author bhouston / http://exocortex.com
  1853. */
  1854. THREE.Box2 = function ( min, max ) {
  1855. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  1856. this.max = ( max !== undefined ) ? max : new THREE.Vector2( -Infinity, -Infinity );
  1857. };
  1858. THREE.Box2.prototype = {
  1859. constructor: THREE.Box2,
  1860. set: function ( min, max ) {
  1861. this.min.copy( min );
  1862. this.max.copy( max );
  1863. return this;
  1864. },
  1865. setFromPoints: function ( points ) {
  1866. if ( points.length > 0 ) {
  1867. var point = points[ 0 ];
  1868. this.min.copy( point );
  1869. this.max.copy( point );
  1870. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1871. point = points[ i ];
  1872. if ( point.x < this.min.x ) {
  1873. this.min.x = point.x;
  1874. } else if ( point.x > this.max.x ) {
  1875. this.max.x = point.x;
  1876. }
  1877. if ( point.y < this.min.y ) {
  1878. this.min.y = point.y;
  1879. } else if ( point.y > this.max.y ) {
  1880. this.max.y = point.y;
  1881. }
  1882. }
  1883. } else {
  1884. this.makeEmpty();
  1885. }
  1886. return this;
  1887. },
  1888. setFromCenterAndSize: function () {
  1889. var v1 = new THREE.Vector2();
  1890. return function ( center, size ) {
  1891. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1892. this.min.copy( center ).sub( halfSize );
  1893. this.max.copy( center ).add( halfSize );
  1894. return this;
  1895. };
  1896. }(),
  1897. copy: function ( box ) {
  1898. this.min.copy( box.min );
  1899. this.max.copy( box.max );
  1900. return this;
  1901. },
  1902. makeEmpty: function () {
  1903. this.min.x = this.min.y = Infinity;
  1904. this.max.x = this.max.y = -Infinity;
  1905. return this;
  1906. },
  1907. empty: function () {
  1908. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1909. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  1910. },
  1911. center: function ( optionalTarget ) {
  1912. var result = optionalTarget || new THREE.Vector2();
  1913. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1914. },
  1915. size: function ( optionalTarget ) {
  1916. var result = optionalTarget || new THREE.Vector2();
  1917. return result.subVectors( this.max, this.min );
  1918. },
  1919. expandByPoint: function ( point ) {
  1920. this.min.min( point );
  1921. this.max.max( point );
  1922. return this;
  1923. },
  1924. expandByVector: function ( vector ) {
  1925. this.min.sub( vector );
  1926. this.max.add( vector );
  1927. return this;
  1928. },
  1929. expandByScalar: function ( scalar ) {
  1930. this.min.addScalar( -scalar );
  1931. this.max.addScalar( scalar );
  1932. return this;
  1933. },
  1934. containsPoint: function ( point ) {
  1935. if ( point.x < this.min.x || point.x > this.max.x ||
  1936. point.y < this.min.y || point.y > this.max.y ) {
  1937. return false;
  1938. }
  1939. return true;
  1940. },
  1941. containsBox: function ( box ) {
  1942. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1943. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  1944. return true;
  1945. }
  1946. return false;
  1947. },
  1948. getParameter: function ( point ) {
  1949. // This can potentially have a divide by zero if the box
  1950. // has a size dimension of 0.
  1951. return new THREE.Vector2(
  1952. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1953. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  1954. );
  1955. },
  1956. isIntersectionBox: function ( box ) {
  1957. // using 6 splitting planes to rule out intersections.
  1958. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  1959. box.max.y < this.min.y || box.min.y > this.max.y ) {
  1960. return false;
  1961. }
  1962. return true;
  1963. },
  1964. clampPoint: function ( point, optionalTarget ) {
  1965. var result = optionalTarget || new THREE.Vector2();
  1966. return result.copy( point ).clamp( this.min, this.max );
  1967. },
  1968. distanceToPoint: function () {
  1969. var v1 = new THREE.Vector2();
  1970. return function ( point ) {
  1971. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  1972. return clampedPoint.sub( point ).length();
  1973. };
  1974. }(),
  1975. intersect: function ( box ) {
  1976. this.min.max( box.min );
  1977. this.max.min( box.max );
  1978. return this;
  1979. },
  1980. union: function ( box ) {
  1981. this.min.min( box.min );
  1982. this.max.max( box.max );
  1983. return this;
  1984. },
  1985. translate: function ( offset ) {
  1986. this.min.add( offset );
  1987. this.max.add( offset );
  1988. return this;
  1989. },
  1990. equals: function ( box ) {
  1991. return box.min.equals( this.min ) && box.max.equals( this.max );
  1992. },
  1993. clone: function () {
  1994. return new THREE.Box2().copy( this );
  1995. }
  1996. };
  1997. /**
  1998. * @author bhouston / http://exocortex.com
  1999. * @author WestLangley / http://github.com/WestLangley
  2000. */
  2001. THREE.Box3 = function ( min, max ) {
  2002. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  2003. this.max = ( max !== undefined ) ? max : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  2004. };
  2005. THREE.Box3.prototype = {
  2006. constructor: THREE.Box3,
  2007. set: function ( min, max ) {
  2008. this.min.copy( min );
  2009. this.max.copy( max );
  2010. return this;
  2011. },
  2012. setFromPoints: function ( points ) {
  2013. if ( points.length > 0 ) {
  2014. var point = points[ 0 ];
  2015. this.min.copy( point );
  2016. this.max.copy( point );
  2017. for ( var i = 1, il = points.length; i < il; i ++ ) {
  2018. point = points[ i ];
  2019. if ( point.x < this.min.x ) {
  2020. this.min.x = point.x;
  2021. } else if ( point.x > this.max.x ) {
  2022. this.max.x = point.x;
  2023. }
  2024. if ( point.y < this.min.y ) {
  2025. this.min.y = point.y;
  2026. } else if ( point.y > this.max.y ) {
  2027. this.max.y = point.y;
  2028. }
  2029. if ( point.z < this.min.z ) {
  2030. this.min.z = point.z;
  2031. } else if ( point.z > this.max.z ) {
  2032. this.max.z = point.z;
  2033. }
  2034. }
  2035. } else {
  2036. this.makeEmpty();
  2037. }
  2038. return this;
  2039. },
  2040. setFromCenterAndSize: function() {
  2041. var v1 = new THREE.Vector3();
  2042. return function ( center, size ) {
  2043. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2044. this.min.copy( center ).sub( halfSize );
  2045. this.max.copy( center ).add( halfSize );
  2046. return this;
  2047. };
  2048. }(),
  2049. setFromObject: function() {
  2050. // Computes the world-axis-aligned bounding box of an object (including its children),
  2051. // accounting for both the object's, and childrens', world transforms
  2052. var v1 = new THREE.Vector3();
  2053. return function( object ) {
  2054. var scope = this;
  2055. object.updateMatrixWorld( true );
  2056. this.makeEmpty();
  2057. object.traverse( function ( node ) {
  2058. if ( node.geometry !== undefined && node.geometry.vertices !== undefined ) {
  2059. var vertices = node.geometry.vertices;
  2060. for ( var i = 0, il = vertices.length; i < il; i++ ) {
  2061. v1.copy( vertices[ i ] );
  2062. v1.applyMatrix4( node.matrixWorld );
  2063. scope.expandByPoint( v1 );
  2064. }
  2065. }
  2066. } );
  2067. return this;
  2068. };
  2069. }(),
  2070. copy: function ( box ) {
  2071. this.min.copy( box.min );
  2072. this.max.copy( box.max );
  2073. return this;
  2074. },
  2075. makeEmpty: function () {
  2076. this.min.x = this.min.y = this.min.z = Infinity;
  2077. this.max.x = this.max.y = this.max.z = -Infinity;
  2078. return this;
  2079. },
  2080. empty: function () {
  2081. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2082. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2083. },
  2084. center: function ( optionalTarget ) {
  2085. var result = optionalTarget || new THREE.Vector3();
  2086. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2087. },
  2088. size: function ( optionalTarget ) {
  2089. var result = optionalTarget || new THREE.Vector3();
  2090. return result.subVectors( this.max, this.min );
  2091. },
  2092. expandByPoint: function ( point ) {
  2093. this.min.min( point );
  2094. this.max.max( point );
  2095. return this;
  2096. },
  2097. expandByVector: function ( vector ) {
  2098. this.min.sub( vector );
  2099. this.max.add( vector );
  2100. return this;
  2101. },
  2102. expandByScalar: function ( scalar ) {
  2103. this.min.addScalar( -scalar );
  2104. this.max.addScalar( scalar );
  2105. return this;
  2106. },
  2107. containsPoint: function ( point ) {
  2108. if ( point.x < this.min.x || point.x > this.max.x ||
  2109. point.y < this.min.y || point.y > this.max.y ||
  2110. point.z < this.min.z || point.z > this.max.z ) {
  2111. return false;
  2112. }
  2113. return true;
  2114. },
  2115. containsBox: function ( box ) {
  2116. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2117. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2118. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2119. return true;
  2120. }
  2121. return false;
  2122. },
  2123. getParameter: function ( point ) {
  2124. // This can potentially have a divide by zero if the box
  2125. // has a size dimension of 0.
  2126. return new THREE.Vector3(
  2127. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2128. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2129. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2130. );
  2131. },
  2132. isIntersectionBox: function ( box ) {
  2133. // using 6 splitting planes to rule out intersections.
  2134. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2135. box.max.y < this.min.y || box.min.y > this.max.y ||
  2136. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2137. return false;
  2138. }
  2139. return true;
  2140. },
  2141. clampPoint: function ( point, optionalTarget ) {
  2142. var result = optionalTarget || new THREE.Vector3();
  2143. return result.copy( point ).clamp( this.min, this.max );
  2144. },
  2145. distanceToPoint: function() {
  2146. var v1 = new THREE.Vector3();
  2147. return function ( point ) {
  2148. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2149. return clampedPoint.sub( point ).length();
  2150. };
  2151. }(),
  2152. getBoundingSphere: function() {
  2153. var v1 = new THREE.Vector3();
  2154. return function ( optionalTarget ) {
  2155. var result = optionalTarget || new THREE.Sphere();
  2156. result.center = this.center();
  2157. result.radius = this.size( v1 ).length() * 0.5;
  2158. return result;
  2159. };
  2160. }(),
  2161. intersect: function ( box ) {
  2162. this.min.max( box.min );
  2163. this.max.min( box.max );
  2164. return this;
  2165. },
  2166. union: function ( box ) {
  2167. this.min.min( box.min );
  2168. this.max.max( box.max );
  2169. return this;
  2170. },
  2171. applyMatrix4: function() {
  2172. var points = [
  2173. new THREE.Vector3(),
  2174. new THREE.Vector3(),
  2175. new THREE.Vector3(),
  2176. new THREE.Vector3(),
  2177. new THREE.Vector3(),
  2178. new THREE.Vector3(),
  2179. new THREE.Vector3(),
  2180. new THREE.Vector3()
  2181. ];
  2182. return function ( matrix ) {
  2183. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2184. points[0].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2185. points[1].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2186. points[2].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2187. points[3].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2188. points[4].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2189. points[5].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2190. points[6].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2191. points[7].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2192. this.makeEmpty();
  2193. this.setFromPoints( points );
  2194. return this;
  2195. };
  2196. }(),
  2197. translate: function ( offset ) {
  2198. this.min.add( offset );
  2199. this.max.add( offset );
  2200. return this;
  2201. },
  2202. equals: function ( box ) {
  2203. return box.min.equals( this.min ) && box.max.equals( this.max );
  2204. },
  2205. clone: function () {
  2206. return new THREE.Box3().copy( this );
  2207. }
  2208. };
  2209. /**
  2210. * @author alteredq / http://alteredqualia.com/
  2211. * @author WestLangley / http://github.com/WestLangley
  2212. * @author bhouston / http://exocortex.com
  2213. */
  2214. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2215. this.elements = new Float32Array(9);
  2216. this.set(
  2217. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0,
  2218. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0,
  2219. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1
  2220. );
  2221. };
  2222. THREE.Matrix3.prototype = {
  2223. constructor: THREE.Matrix3,
  2224. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2225. var te = this.elements;
  2226. te[0] = n11; te[3] = n12; te[6] = n13;
  2227. te[1] = n21; te[4] = n22; te[7] = n23;
  2228. te[2] = n31; te[5] = n32; te[8] = n33;
  2229. return this;
  2230. },
  2231. identity: function () {
  2232. this.set(
  2233. 1, 0, 0,
  2234. 0, 1, 0,
  2235. 0, 0, 1
  2236. );
  2237. return this;
  2238. },
  2239. copy: function ( m ) {
  2240. var me = m.elements;
  2241. this.set(
  2242. me[0], me[3], me[6],
  2243. me[1], me[4], me[7],
  2244. me[2], me[5], me[8]
  2245. );
  2246. return this;
  2247. },
  2248. multiplyVector3: function ( vector ) {
  2249. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2250. return vector.applyMatrix3( this );
  2251. },
  2252. multiplyVector3Array: function() {
  2253. var v1 = new THREE.Vector3();
  2254. return function ( a ) {
  2255. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2256. v1.x = a[ i ];
  2257. v1.y = a[ i + 1 ];
  2258. v1.z = a[ i + 2 ];
  2259. v1.applyMatrix3(this);
  2260. a[ i ] = v1.x;
  2261. a[ i + 1 ] = v1.y;
  2262. a[ i + 2 ] = v1.z;
  2263. }
  2264. return a;
  2265. };
  2266. }(),
  2267. multiplyScalar: function ( s ) {
  2268. var te = this.elements;
  2269. te[0] *= s; te[3] *= s; te[6] *= s;
  2270. te[1] *= s; te[4] *= s; te[7] *= s;
  2271. te[2] *= s; te[5] *= s; te[8] *= s;
  2272. return this;
  2273. },
  2274. determinant: function () {
  2275. var te = this.elements;
  2276. var a = te[0], b = te[1], c = te[2],
  2277. d = te[3], e = te[4], f = te[5],
  2278. g = te[6], h = te[7], i = te[8];
  2279. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  2280. },
  2281. getInverse: function ( matrix, throwOnInvertible ) {
  2282. // input: THREE.Matrix4
  2283. // ( based on http://code.google.com/p/webgl-mjs/ )
  2284. var me = matrix.elements;
  2285. var te = this.elements;
  2286. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  2287. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  2288. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  2289. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  2290. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  2291. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  2292. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  2293. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  2294. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  2295. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2296. // no inverse
  2297. if ( det === 0 ) {
  2298. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2299. if ( throwOnInvertible || false ) {
  2300. throw new Error( msg );
  2301. } else {
  2302. console.warn( msg );
  2303. }
  2304. this.identity();
  2305. return this;
  2306. }
  2307. this.multiplyScalar( 1.0 / det );
  2308. return this;
  2309. },
  2310. transpose: function () {
  2311. var tmp, m = this.elements;
  2312. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  2313. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  2314. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  2315. return this;
  2316. },
  2317. getNormalMatrix: function ( m ) {
  2318. // input: THREE.Matrix4
  2319. this.getInverse( m ).transpose();
  2320. return this;
  2321. },
  2322. transposeIntoArray: function ( r ) {
  2323. var m = this.elements;
  2324. r[ 0 ] = m[ 0 ];
  2325. r[ 1 ] = m[ 3 ];
  2326. r[ 2 ] = m[ 6 ];
  2327. r[ 3 ] = m[ 1 ];
  2328. r[ 4 ] = m[ 4 ];
  2329. r[ 5 ] = m[ 7 ];
  2330. r[ 6 ] = m[ 2 ];
  2331. r[ 7 ] = m[ 5 ];
  2332. r[ 8 ] = m[ 8 ];
  2333. return this;
  2334. },
  2335. clone: function () {
  2336. var te = this.elements;
  2337. return new THREE.Matrix3(
  2338. te[0], te[3], te[6],
  2339. te[1], te[4], te[7],
  2340. te[2], te[5], te[8]
  2341. );
  2342. }
  2343. };
  2344. /**
  2345. * @author mrdoob / http://mrdoob.com/
  2346. * @author supereggbert / http://www.paulbrunt.co.uk/
  2347. * @author philogb / http://blog.thejit.org/
  2348. * @author jordi_ros / http://plattsoft.com
  2349. * @author D1plo1d / http://github.com/D1plo1d
  2350. * @author alteredq / http://alteredqualia.com/
  2351. * @author mikael emtinger / http://gomo.se/
  2352. * @author timknip / http://www.floorplanner.com/
  2353. * @author bhouston / http://exocortex.com
  2354. * @author WestLangley / http://github.com/WestLangley
  2355. */
  2356. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2357. this.elements = new Float32Array( 16 );
  2358. // TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix
  2359. // we should not support semi specification of Matrix4, it is just weird.
  2360. var te = this.elements;
  2361. te[0] = ( n11 !== undefined ) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  2362. te[1] = n21 || 0; te[5] = ( n22 !== undefined ) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  2363. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = ( n33 !== undefined ) ? n33 : 1; te[14] = n34 || 0;
  2364. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = ( n44 !== undefined ) ? n44 : 1;
  2365. };
  2366. THREE.Matrix4.prototype = {
  2367. constructor: THREE.Matrix4,
  2368. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2369. var te = this.elements;
  2370. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  2371. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  2372. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  2373. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  2374. return this;
  2375. },
  2376. identity: function () {
  2377. this.set(
  2378. 1, 0, 0, 0,
  2379. 0, 1, 0, 0,
  2380. 0, 0, 1, 0,
  2381. 0, 0, 0, 1
  2382. );
  2383. return this;
  2384. },
  2385. copy: function ( m ) {
  2386. this.elements.set( m.elements );
  2387. return this;
  2388. },
  2389. extractPosition: function ( m ) {
  2390. console.warn( 'DEPRECATED: Matrix4\'s .extractPosition() has been renamed to .copyPosition().' );
  2391. return this.copyPosition( m );
  2392. },
  2393. copyPosition: function ( m ) {
  2394. var te = this.elements;
  2395. var me = m.elements;
  2396. te[12] = me[12];
  2397. te[13] = me[13];
  2398. te[14] = me[14];
  2399. return this;
  2400. },
  2401. extractRotation: function () {
  2402. var v1 = new THREE.Vector3();
  2403. return function ( m ) {
  2404. var te = this.elements;
  2405. var me = m.elements;
  2406. var scaleX = 1 / v1.set( me[0], me[1], me[2] ).length();
  2407. var scaleY = 1 / v1.set( me[4], me[5], me[6] ).length();
  2408. var scaleZ = 1 / v1.set( me[8], me[9], me[10] ).length();
  2409. te[0] = me[0] * scaleX;
  2410. te[1] = me[1] * scaleX;
  2411. te[2] = me[2] * scaleX;
  2412. te[4] = me[4] * scaleY;
  2413. te[5] = me[5] * scaleY;
  2414. te[6] = me[6] * scaleY;
  2415. te[8] = me[8] * scaleZ;
  2416. te[9] = me[9] * scaleZ;
  2417. te[10] = me[10] * scaleZ;
  2418. return this;
  2419. };
  2420. }(),
  2421. makeRotationFromEuler: function ( euler ) {
  2422. if ( typeof euler['order'] === undefined ) {
  2423. console.error( 'ERROR: Matrix\'s .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  2424. }
  2425. var te = this.elements;
  2426. var x = euler.x, y = euler.y, z = euler.z;
  2427. var a = Math.cos( x ), b = Math.sin( x );
  2428. var c = Math.cos( y ), d = Math.sin( y );
  2429. var e = Math.cos( z ), f = Math.sin( z );
  2430. if ( euler.order === undefined || euler.order === 'XYZ' ) {
  2431. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2432. te[0] = c * e;
  2433. te[4] = - c * f;
  2434. te[8] = d;
  2435. te[1] = af + be * d;
  2436. te[5] = ae - bf * d;
  2437. te[9] = - b * c;
  2438. te[2] = bf - ae * d;
  2439. te[6] = be + af * d;
  2440. te[10] = a * c;
  2441. } else if ( euler.order === 'YXZ' ) {
  2442. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2443. te[0] = ce + df * b;
  2444. te[4] = de * b - cf;
  2445. te[8] = a * d;
  2446. te[1] = a * f;
  2447. te[5] = a * e;
  2448. te[9] = - b;
  2449. te[2] = cf * b - de;
  2450. te[6] = df + ce * b;
  2451. te[10] = a * c;
  2452. } else if ( euler.order === 'ZXY' ) {
  2453. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2454. te[0] = ce - df * b;
  2455. te[4] = - a * f;
  2456. te[8] = de + cf * b;
  2457. te[1] = cf + de * b;
  2458. te[5] = a * e;
  2459. te[9] = df - ce * b;
  2460. te[2] = - a * d;
  2461. te[6] = b;
  2462. te[10] = a * c;
  2463. } else if ( euler.order === 'ZYX' ) {
  2464. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2465. te[0] = c * e;
  2466. te[4] = be * d - af;
  2467. te[8] = ae * d + bf;
  2468. te[1] = c * f;
  2469. te[5] = bf * d + ae;
  2470. te[9] = af * d - be;
  2471. te[2] = - d;
  2472. te[6] = b * c;
  2473. te[10] = a * c;
  2474. } else if ( euler.order === 'YZX' ) {
  2475. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2476. te[0] = c * e;
  2477. te[4] = bd - ac * f;
  2478. te[8] = bc * f + ad;
  2479. te[1] = f;
  2480. te[5] = a * e;
  2481. te[9] = - b * e;
  2482. te[2] = - d * e;
  2483. te[6] = ad * f + bc;
  2484. te[10] = ac - bd * f;
  2485. } else if ( euler.order === 'XZY' ) {
  2486. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2487. te[0] = c * e;
  2488. te[4] = - f;
  2489. te[8] = d * e;
  2490. te[1] = ac * f + bd;
  2491. te[5] = a * e;
  2492. te[9] = ad * f - bc;
  2493. te[2] = bc * f - ad;
  2494. te[6] = b * e;
  2495. te[10] = bd * f + ac;
  2496. }
  2497. // last column
  2498. te[3] = 0;
  2499. te[7] = 0;
  2500. te[11] = 0;
  2501. // bottom row
  2502. te[12] = 0;
  2503. te[13] = 0;
  2504. te[14] = 0;
  2505. te[15] = 1;
  2506. return this;
  2507. },
  2508. setRotationFromQuaternion: function ( q ) {
  2509. console.warn( 'DEPRECATED: Matrix4\'s .setRotationFromQuaternion() has been deprecated in favor of makeRotationFromQuaternion. Please update your code.' );
  2510. return this.makeRotationFromQuaternion( q );
  2511. },
  2512. makeRotationFromQuaternion: function ( q ) {
  2513. var te = this.elements;
  2514. var x = q.x, y = q.y, z = q.z, w = q.w;
  2515. var x2 = x + x, y2 = y + y, z2 = z + z;
  2516. var xx = x * x2, xy = x * y2, xz = x * z2;
  2517. var yy = y * y2, yz = y * z2, zz = z * z2;
  2518. var wx = w * x2, wy = w * y2, wz = w * z2;
  2519. te[0] = 1 - ( yy + zz );
  2520. te[4] = xy - wz;
  2521. te[8] = xz + wy;
  2522. te[1] = xy + wz;
  2523. te[5] = 1 - ( xx + zz );
  2524. te[9] = yz - wx;
  2525. te[2] = xz - wy;
  2526. te[6] = yz + wx;
  2527. te[10] = 1 - ( xx + yy );
  2528. // last column
  2529. te[3] = 0;
  2530. te[7] = 0;
  2531. te[11] = 0;
  2532. // bottom row
  2533. te[12] = 0;
  2534. te[13] = 0;
  2535. te[14] = 0;
  2536. te[15] = 1;
  2537. return this;
  2538. },
  2539. lookAt: function() {
  2540. var x = new THREE.Vector3();
  2541. var y = new THREE.Vector3();
  2542. var z = new THREE.Vector3();
  2543. return function ( eye, target, up ) {
  2544. var te = this.elements;
  2545. z.subVectors( eye, target ).normalize();
  2546. if ( z.length() === 0 ) {
  2547. z.z = 1;
  2548. }
  2549. x.crossVectors( up, z ).normalize();
  2550. if ( x.length() === 0 ) {
  2551. z.x += 0.0001;
  2552. x.crossVectors( up, z ).normalize();
  2553. }
  2554. y.crossVectors( z, x );
  2555. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  2556. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  2557. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  2558. return this;
  2559. };
  2560. }(),
  2561. multiply: function ( m, n ) {
  2562. if ( n !== undefined ) {
  2563. console.warn( 'DEPRECATED: Matrix4\'s .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2564. return this.multiplyMatrices( m, n );
  2565. }
  2566. return this.multiplyMatrices( this, m );
  2567. },
  2568. multiplyMatrices: function ( a, b ) {
  2569. var ae = a.elements;
  2570. var be = b.elements;
  2571. var te = this.elements;
  2572. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  2573. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  2574. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  2575. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  2576. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  2577. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  2578. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  2579. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  2580. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2581. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2582. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2583. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2584. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2585. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2586. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2587. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2588. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2589. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2590. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2591. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2592. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2593. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2594. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2595. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2596. return this;
  2597. },
  2598. multiplyToArray: function ( a, b, r ) {
  2599. var te = this.elements;
  2600. this.multiplyMatrices( a, b );
  2601. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  2602. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  2603. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  2604. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  2605. return this;
  2606. },
  2607. multiplyScalar: function ( s ) {
  2608. var te = this.elements;
  2609. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  2610. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  2611. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  2612. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  2613. return this;
  2614. },
  2615. multiplyVector3: function ( vector ) {
  2616. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2617. return vector.applyProjection( this );
  2618. },
  2619. multiplyVector4: function ( vector ) {
  2620. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2621. return vector.applyMatrix4( this );
  2622. },
  2623. multiplyVector3Array: function() {
  2624. var v1 = new THREE.Vector3();
  2625. return function ( a ) {
  2626. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2627. v1.x = a[ i ];
  2628. v1.y = a[ i + 1 ];
  2629. v1.z = a[ i + 2 ];
  2630. v1.applyProjection( this );
  2631. a[ i ] = v1.x;
  2632. a[ i + 1 ] = v1.y;
  2633. a[ i + 2 ] = v1.z;
  2634. }
  2635. return a;
  2636. };
  2637. }(),
  2638. rotateAxis: function ( v ) {
  2639. console.warn( 'DEPRECATED: Matrix4\'s .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2640. v.transformDirection( this );
  2641. },
  2642. crossVector: function ( vector ) {
  2643. console.warn( 'DEPRECATED: Matrix4\'s .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2644. return vector.applyMatrix4( this );
  2645. },
  2646. determinant: function () {
  2647. var te = this.elements;
  2648. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  2649. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  2650. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  2651. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  2652. //TODO: make this more efficient
  2653. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2654. return (
  2655. n41 * (
  2656. +n14 * n23 * n32
  2657. -n13 * n24 * n32
  2658. -n14 * n22 * n33
  2659. +n12 * n24 * n33
  2660. +n13 * n22 * n34
  2661. -n12 * n23 * n34
  2662. ) +
  2663. n42 * (
  2664. +n11 * n23 * n34
  2665. -n11 * n24 * n33
  2666. +n14 * n21 * n33
  2667. -n13 * n21 * n34
  2668. +n13 * n24 * n31
  2669. -n14 * n23 * n31
  2670. ) +
  2671. n43 * (
  2672. +n11 * n24 * n32
  2673. -n11 * n22 * n34
  2674. -n14 * n21 * n32
  2675. +n12 * n21 * n34
  2676. +n14 * n22 * n31
  2677. -n12 * n24 * n31
  2678. ) +
  2679. n44 * (
  2680. -n13 * n22 * n31
  2681. -n11 * n23 * n32
  2682. +n11 * n22 * n33
  2683. +n13 * n21 * n32
  2684. -n12 * n21 * n33
  2685. +n12 * n23 * n31
  2686. )
  2687. );
  2688. },
  2689. transpose: function () {
  2690. var te = this.elements;
  2691. var tmp;
  2692. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  2693. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  2694. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  2695. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  2696. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  2697. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  2698. return this;
  2699. },
  2700. flattenToArray: function ( flat ) {
  2701. var te = this.elements;
  2702. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  2703. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  2704. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  2705. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  2706. return flat;
  2707. },
  2708. flattenToArrayOffset: function( flat, offset ) {
  2709. var te = this.elements;
  2710. flat[ offset ] = te[0];
  2711. flat[ offset + 1 ] = te[1];
  2712. flat[ offset + 2 ] = te[2];
  2713. flat[ offset + 3 ] = te[3];
  2714. flat[ offset + 4 ] = te[4];
  2715. flat[ offset + 5 ] = te[5];
  2716. flat[ offset + 6 ] = te[6];
  2717. flat[ offset + 7 ] = te[7];
  2718. flat[ offset + 8 ] = te[8];
  2719. flat[ offset + 9 ] = te[9];
  2720. flat[ offset + 10 ] = te[10];
  2721. flat[ offset + 11 ] = te[11];
  2722. flat[ offset + 12 ] = te[12];
  2723. flat[ offset + 13 ] = te[13];
  2724. flat[ offset + 14 ] = te[14];
  2725. flat[ offset + 15 ] = te[15];
  2726. return flat;
  2727. },
  2728. getPosition: function() {
  2729. var v1 = new THREE.Vector3();
  2730. return function () {
  2731. console.warn( 'DEPRECATED: Matrix4\'s .getPosition() has been removed. Use Vector3.getPositionFromMatrix( matrix ) instead.' );
  2732. var te = this.elements;
  2733. return v1.set( te[12], te[13], te[14] );
  2734. };
  2735. }(),
  2736. setPosition: function ( v ) {
  2737. var te = this.elements;
  2738. te[12] = v.x;
  2739. te[13] = v.y;
  2740. te[14] = v.z;
  2741. return this;
  2742. },
  2743. getInverse: function ( m, throwOnInvertible ) {
  2744. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2745. var te = this.elements;
  2746. var me = m.elements;
  2747. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2748. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2749. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2750. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2751. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2752. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2753. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2754. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2755. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2756. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2757. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2758. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2759. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2760. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2761. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2762. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2763. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2764. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2765. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2766. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2767. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  2768. if ( det == 0 ) {
  2769. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2770. if ( throwOnInvertible || false ) {
  2771. throw new Error( msg );
  2772. } else {
  2773. console.warn( msg );
  2774. }
  2775. this.identity();
  2776. return this;
  2777. }
  2778. this.multiplyScalar( 1 / det );
  2779. return this;
  2780. },
  2781. translate: function ( v ) {
  2782. console.warn( 'DEPRECATED: Matrix4\'s .translate() has been removed.');
  2783. },
  2784. rotateX: function ( angle ) {
  2785. console.warn( 'DEPRECATED: Matrix4\'s .rotateX() has been removed.');
  2786. },
  2787. rotateY: function ( angle ) {
  2788. console.warn( 'DEPRECATED: Matrix4\'s .rotateY() has been removed.');
  2789. },
  2790. rotateZ: function ( angle ) {
  2791. console.warn( 'DEPRECATED: Matrix4\'s .rotateZ() has been removed.');
  2792. },
  2793. rotateByAxis: function ( axis, angle ) {
  2794. console.warn( 'DEPRECATED: Matrix4\'s .rotateByAxis() has been removed.');
  2795. },
  2796. scale: function ( v ) {
  2797. var te = this.elements;
  2798. var x = v.x, y = v.y, z = v.z;
  2799. te[0] *= x; te[4] *= y; te[8] *= z;
  2800. te[1] *= x; te[5] *= y; te[9] *= z;
  2801. te[2] *= x; te[6] *= y; te[10] *= z;
  2802. te[3] *= x; te[7] *= y; te[11] *= z;
  2803. return this;
  2804. },
  2805. getMaxScaleOnAxis: function () {
  2806. var te = this.elements;
  2807. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2808. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2809. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2810. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2811. },
  2812. makeTranslation: function ( x, y, z ) {
  2813. this.set(
  2814. 1, 0, 0, x,
  2815. 0, 1, 0, y,
  2816. 0, 0, 1, z,
  2817. 0, 0, 0, 1
  2818. );
  2819. return this;
  2820. },
  2821. makeRotationX: function ( theta ) {
  2822. var c = Math.cos( theta ), s = Math.sin( theta );
  2823. this.set(
  2824. 1, 0, 0, 0,
  2825. 0, c, -s, 0,
  2826. 0, s, c, 0,
  2827. 0, 0, 0, 1
  2828. );
  2829. return this;
  2830. },
  2831. makeRotationY: function ( theta ) {
  2832. var c = Math.cos( theta ), s = Math.sin( theta );
  2833. this.set(
  2834. c, 0, s, 0,
  2835. 0, 1, 0, 0,
  2836. -s, 0, c, 0,
  2837. 0, 0, 0, 1
  2838. );
  2839. return this;
  2840. },
  2841. makeRotationZ: function ( theta ) {
  2842. var c = Math.cos( theta ), s = Math.sin( theta );
  2843. this.set(
  2844. c, -s, 0, 0,
  2845. s, c, 0, 0,
  2846. 0, 0, 1, 0,
  2847. 0, 0, 0, 1
  2848. );
  2849. return this;
  2850. },
  2851. makeRotationAxis: function ( axis, angle ) {
  2852. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2853. var c = Math.cos( angle );
  2854. var s = Math.sin( angle );
  2855. var t = 1 - c;
  2856. var x = axis.x, y = axis.y, z = axis.z;
  2857. var tx = t * x, ty = t * y;
  2858. this.set(
  2859. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2860. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2861. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2862. 0, 0, 0, 1
  2863. );
  2864. return this;
  2865. },
  2866. makeScale: function ( x, y, z ) {
  2867. this.set(
  2868. x, 0, 0, 0,
  2869. 0, y, 0, 0,
  2870. 0, 0, z, 0,
  2871. 0, 0, 0, 1
  2872. );
  2873. return this;
  2874. },
  2875. compose: function ( position, quaternion, scale ) {
  2876. console.warn( 'DEPRECATED: Matrix4\'s .compose() has been deprecated in favor of makeFromPositionQuaternionScale. Please update your code.' );
  2877. return this.makeFromPositionQuaternionScale( position, quaternion, scale );
  2878. },
  2879. makeFromPositionQuaternionScale: function ( position, quaternion, scale ) {
  2880. this.makeRotationFromQuaternion( quaternion );
  2881. this.scale( scale );
  2882. this.setPosition( position );
  2883. return this;
  2884. },
  2885. makeFromPositionEulerScale: function ( position, rotation, scale ) {
  2886. if( typeof rotation['order'] === undefined ) {
  2887. console.error( 'ERROR: Matrix4\'s .makeFromPositionEulerScale() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  2888. }
  2889. this.makeRotationFromEuler( rotation );
  2890. this.scale( scale );
  2891. this.setPosition( position );
  2892. return this;
  2893. },
  2894. makeFrustum: function ( left, right, bottom, top, near, far ) {
  2895. var te = this.elements;
  2896. var x = 2 * near / ( right - left );
  2897. var y = 2 * near / ( top - bottom );
  2898. var a = ( right + left ) / ( right - left );
  2899. var b = ( top + bottom ) / ( top - bottom );
  2900. var c = - ( far + near ) / ( far - near );
  2901. var d = - 2 * far * near / ( far - near );
  2902. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  2903. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  2904. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  2905. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  2906. return this;
  2907. },
  2908. makePerspective: function ( fov, aspect, near, far ) {
  2909. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  2910. var ymin = - ymax;
  2911. var xmin = ymin * aspect;
  2912. var xmax = ymax * aspect;
  2913. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  2914. },
  2915. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2916. var te = this.elements;
  2917. var w = right - left;
  2918. var h = top - bottom;
  2919. var p = far - near;
  2920. var x = ( right + left ) / w;
  2921. var y = ( top + bottom ) / h;
  2922. var z = ( far + near ) / p;
  2923. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  2924. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  2925. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  2926. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  2927. return this;
  2928. },
  2929. fromArray: function ( array ) {
  2930. this.elements.set( array );
  2931. return this;
  2932. },
  2933. toArray: function () {
  2934. var te = this.elements;
  2935. return [
  2936. te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ],
  2937. te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ],
  2938. te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ],
  2939. te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ]
  2940. ];
  2941. },
  2942. clone: function () {
  2943. var te = this.elements;
  2944. return new THREE.Matrix4(
  2945. te[0], te[4], te[8], te[12],
  2946. te[1], te[5], te[9], te[13],
  2947. te[2], te[6], te[10], te[14],
  2948. te[3], te[7], te[11], te[15]
  2949. );
  2950. }
  2951. };
  2952. THREE.extend( THREE.Matrix4.prototype, {
  2953. decompose: function () {
  2954. var x = new THREE.Vector3();
  2955. var y = new THREE.Vector3();
  2956. var z = new THREE.Vector3();
  2957. var matrix = new THREE.Matrix4();
  2958. return function ( position, quaternion, scale ) {
  2959. var te = this.elements;
  2960. // grab the axis vectors
  2961. x.set( te[0], te[1], te[2] );
  2962. y.set( te[4], te[5], te[6] );
  2963. z.set( te[8], te[9], te[10] );
  2964. position = ( position instanceof THREE.Vector3 ) ? position : new THREE.Vector3();
  2965. quaternion = ( quaternion instanceof THREE.Quaternion ) ? quaternion : new THREE.Quaternion();
  2966. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  2967. scale.x = x.length();
  2968. scale.y = y.length();
  2969. scale.z = z.length();
  2970. position.x = te[12];
  2971. position.y = te[13];
  2972. position.z = te[14];
  2973. // scale the rotation part
  2974. matrix.copy( this );
  2975. matrix.elements[0] /= scale.x;
  2976. matrix.elements[1] /= scale.x;
  2977. matrix.elements[2] /= scale.x;
  2978. matrix.elements[4] /= scale.y;
  2979. matrix.elements[5] /= scale.y;
  2980. matrix.elements[6] /= scale.y;
  2981. matrix.elements[8] /= scale.z;
  2982. matrix.elements[9] /= scale.z;
  2983. matrix.elements[10] /= scale.z;
  2984. quaternion.setFromRotationMatrix( matrix );
  2985. return [ position, quaternion, scale ];
  2986. };
  2987. }()
  2988. } );
  2989. /**
  2990. * @author bhouston / http://exocortex.com
  2991. */
  2992. THREE.Ray = function ( origin, direction ) {
  2993. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  2994. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  2995. };
  2996. THREE.Ray.prototype = {
  2997. constructor: THREE.Ray,
  2998. set: function ( origin, direction ) {
  2999. this.origin.copy( origin );
  3000. this.direction.copy( direction );
  3001. return this;
  3002. },
  3003. copy: function ( ray ) {
  3004. this.origin.copy( ray.origin );
  3005. this.direction.copy( ray.direction );
  3006. return this;
  3007. },
  3008. at: function( t, optionalTarget ) {
  3009. var result = optionalTarget || new THREE.Vector3();
  3010. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3011. },
  3012. recast: function() {
  3013. var v1 = new THREE.Vector3();
  3014. return function ( t ) {
  3015. this.origin.copy( this.at( t, v1 ) );
  3016. return this;
  3017. };
  3018. }(),
  3019. closestPointToPoint: function ( point, optionalTarget ) {
  3020. var result = optionalTarget || new THREE.Vector3();
  3021. result.subVectors( point, this.origin );
  3022. var directionDistance = result.dot( this.direction );
  3023. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3024. },
  3025. distanceToPoint: function() {
  3026. var v1 = new THREE.Vector3();
  3027. return function ( point ) {
  3028. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  3029. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3030. return v1.distanceTo( point );
  3031. };
  3032. }(),
  3033. isIntersectionSphere: function( sphere ) {
  3034. return ( this.distanceToPoint( sphere.center ) <= sphere.radius );
  3035. },
  3036. isIntersectionPlane: function ( plane ) {
  3037. // check if the line and plane are non-perpendicular, if they
  3038. // eventually they will intersect.
  3039. var denominator = plane.normal.dot( this.direction );
  3040. if ( denominator != 0 ) {
  3041. return true;
  3042. }
  3043. // line is coplanar, return origin
  3044. if( plane.distanceToPoint( this.origin ) == 0 ) {
  3045. return true;
  3046. }
  3047. return false;
  3048. },
  3049. distanceToPlane: function ( plane ) {
  3050. var denominator = plane.normal.dot( this.direction );
  3051. if ( denominator == 0 ) {
  3052. // line is coplanar, return origin
  3053. if( plane.distanceToPoint( this.origin ) == 0 ) {
  3054. return 0;
  3055. }
  3056. // Unsure if this is the correct method to handle this case.
  3057. return undefined;
  3058. }
  3059. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3060. return t;
  3061. },
  3062. intersectPlane: function ( plane, optionalTarget ) {
  3063. var t = this.distanceToPlane( plane );
  3064. if ( t === undefined ) {
  3065. return undefined;
  3066. }
  3067. return this.at( t, optionalTarget );
  3068. },
  3069. applyMatrix4: function ( matrix4 ) {
  3070. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3071. this.origin.applyMatrix4( matrix4 );
  3072. this.direction.sub( this.origin );
  3073. return this;
  3074. },
  3075. equals: function ( ray ) {
  3076. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3077. },
  3078. clone: function () {
  3079. return new THREE.Ray().copy( this );
  3080. }
  3081. };
  3082. /**
  3083. * @author bhouston / http://exocortex.com
  3084. * @author mrdoob / http://mrdoob.com/
  3085. */
  3086. THREE.Sphere = function ( center, radius ) {
  3087. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3088. this.radius = ( radius !== undefined ) ? radius : 0;
  3089. };
  3090. THREE.Sphere.prototype = {
  3091. constructor: THREE.Sphere,
  3092. set: function ( center, radius ) {
  3093. this.center.copy( center );
  3094. this.radius = radius;
  3095. return this;
  3096. },
  3097. setFromPoints: function ( points ) {
  3098. var radiusSq, maxRadiusSq = 0;
  3099. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3100. radiusSq = points[ i ].lengthSq();
  3101. maxRadiusSq = Math.max( maxRadiusSq, radiusSq );
  3102. }
  3103. this.center.set( 0, 0, 0 );
  3104. this.radius = Math.sqrt( maxRadiusSq );
  3105. return this;
  3106. },
  3107. copy: function ( sphere ) {
  3108. this.center.copy( sphere.center );
  3109. this.radius = sphere.radius;
  3110. return this;
  3111. },
  3112. empty: function () {
  3113. return ( this.radius <= 0 );
  3114. },
  3115. containsPoint: function ( point ) {
  3116. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3117. },
  3118. distanceToPoint: function ( point ) {
  3119. return ( point.distanceTo( this.center ) - this.radius );
  3120. },
  3121. intersectsSphere: function ( sphere ) {
  3122. var radiusSum = this.radius + sphere.radius;
  3123. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3124. },
  3125. clampPoint: function ( point, optionalTarget ) {
  3126. var deltaLengthSq = this.center.distanceToSquared( point );
  3127. var result = optionalTarget || new THREE.Vector3();
  3128. result.copy( point );
  3129. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3130. result.sub( this.center ).normalize();
  3131. result.multiplyScalar( this.radius ).add( this.center );
  3132. }
  3133. return result;
  3134. },
  3135. getBoundingBox: function ( optionalTarget ) {
  3136. var box = optionalTarget || new THREE.Box3();
  3137. box.set( this.center, this.center );
  3138. box.expandByScalar( this.radius );
  3139. return box;
  3140. },
  3141. applyMatrix4: function ( matrix ) {
  3142. this.center.applyMatrix4( matrix );
  3143. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3144. return this;
  3145. },
  3146. translate: function ( offset ) {
  3147. this.center.add( offset );
  3148. return this;
  3149. },
  3150. equals: function ( sphere ) {
  3151. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3152. },
  3153. clone: function () {
  3154. return new THREE.Sphere().copy( this );
  3155. }
  3156. };
  3157. /**
  3158. * @author mrdoob / http://mrdoob.com/
  3159. * @author alteredq / http://alteredqualia.com/
  3160. * @author bhouston / http://exocortex.com
  3161. */
  3162. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3163. this.planes = [
  3164. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3165. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3166. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3167. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3168. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3169. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3170. ];
  3171. };
  3172. THREE.Frustum.prototype = {
  3173. constructor: THREE.Frustum,
  3174. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3175. var planes = this.planes;
  3176. planes[0].copy( p0 );
  3177. planes[1].copy( p1 );
  3178. planes[2].copy( p2 );
  3179. planes[3].copy( p3 );
  3180. planes[4].copy( p4 );
  3181. planes[5].copy( p5 );
  3182. return this;
  3183. },
  3184. copy: function ( frustum ) {
  3185. var planes = this.planes;
  3186. for( var i = 0; i < 6; i ++ ) {
  3187. planes[i].copy( frustum.planes[i] );
  3188. }
  3189. return this;
  3190. },
  3191. setFromMatrix: function ( m ) {
  3192. var planes = this.planes;
  3193. var me = m.elements;
  3194. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  3195. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  3196. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  3197. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  3198. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3199. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3200. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3201. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3202. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3203. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3204. return this;
  3205. },
  3206. intersectsObject: function () {
  3207. var center = new THREE.Vector3();
  3208. return function ( object ) {
  3209. // this method is expanded inlined for performance reasons.
  3210. var matrix = object.matrixWorld;
  3211. var planes = this.planes;
  3212. var negRadius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  3213. center.getPositionFromMatrix( matrix );
  3214. for ( var i = 0; i < 6; i ++ ) {
  3215. var distance = planes[ i ].distanceToPoint( center );
  3216. if ( distance < negRadius ) {
  3217. return false;
  3218. }
  3219. }
  3220. return true;
  3221. };
  3222. }(),
  3223. intersectsSphere: function ( sphere ) {
  3224. var planes = this.planes;
  3225. var center = sphere.center;
  3226. var negRadius = -sphere.radius;
  3227. for ( var i = 0; i < 6; i ++ ) {
  3228. var distance = planes[ i ].distanceToPoint( center );
  3229. if ( distance < negRadius ) {
  3230. return false;
  3231. }
  3232. }
  3233. return true;
  3234. },
  3235. containsPoint: function ( point ) {
  3236. var planes = this.planes;
  3237. for ( var i = 0; i < 6; i ++ ) {
  3238. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3239. return false;
  3240. }
  3241. }
  3242. return true;
  3243. },
  3244. clone: function () {
  3245. return new THREE.Frustum().copy( this );
  3246. }
  3247. };
  3248. /**
  3249. * @author bhouston / http://exocortex.com
  3250. */
  3251. THREE.Plane = function ( normal, constant ) {
  3252. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3253. this.constant = ( constant !== undefined ) ? constant : 0;
  3254. };
  3255. THREE.Plane.prototype = {
  3256. constructor: THREE.Plane,
  3257. set: function ( normal, constant ) {
  3258. this.normal.copy( normal );
  3259. this.constant = constant;
  3260. return this;
  3261. },
  3262. setComponents: function ( x, y, z, w ) {
  3263. this.normal.set( x, y, z );
  3264. this.constant = w;
  3265. return this;
  3266. },
  3267. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3268. this.normal.copy( normal );
  3269. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3270. return this;
  3271. },
  3272. setFromCoplanarPoints: function() {
  3273. var v1 = new THREE.Vector3();
  3274. var v2 = new THREE.Vector3();
  3275. return function ( a, b, c ) {
  3276. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3277. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3278. this.setFromNormalAndCoplanarPoint( normal, a );
  3279. return this;
  3280. };
  3281. }(),
  3282. copy: function ( plane ) {
  3283. this.normal.copy( plane.normal );
  3284. this.constant = plane.constant;
  3285. return this;
  3286. },
  3287. normalize: function () {
  3288. // Note: will lead to a divide by zero if the plane is invalid.
  3289. var inverseNormalLength = 1.0 / this.normal.length();
  3290. this.normal.multiplyScalar( inverseNormalLength );
  3291. this.constant *= inverseNormalLength;
  3292. return this;
  3293. },
  3294. negate: function () {
  3295. this.constant *= -1;
  3296. this.normal.negate();
  3297. return this;
  3298. },
  3299. distanceToPoint: function ( point ) {
  3300. return this.normal.dot( point ) + this.constant;
  3301. },
  3302. distanceToSphere: function ( sphere ) {
  3303. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3304. },
  3305. projectPoint: function ( point, optionalTarget ) {
  3306. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3307. },
  3308. orthoPoint: function ( point, optionalTarget ) {
  3309. var perpendicularMagnitude = this.distanceToPoint( point );
  3310. var result = optionalTarget || new THREE.Vector3();
  3311. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3312. },
  3313. isIntersectionLine: function ( line ) {
  3314. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3315. var startSign = this.distanceToPoint( line.start );
  3316. var endSign = this.distanceToPoint( line.end );
  3317. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3318. },
  3319. intersectLine: function() {
  3320. var v1 = new THREE.Vector3();
  3321. return function ( line, optionalTarget ) {
  3322. var result = optionalTarget || new THREE.Vector3();
  3323. var direction = line.delta( v1 );
  3324. var denominator = this.normal.dot( direction );
  3325. if ( denominator == 0 ) {
  3326. // line is coplanar, return origin
  3327. if( this.distanceToPoint( line.start ) == 0 ) {
  3328. return result.copy( line.start );
  3329. }
  3330. // Unsure if this is the correct method to handle this case.
  3331. return undefined;
  3332. }
  3333. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3334. if( t < 0 || t > 1 ) {
  3335. return undefined;
  3336. }
  3337. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3338. };
  3339. }(),
  3340. coplanarPoint: function ( optionalTarget ) {
  3341. var result = optionalTarget || new THREE.Vector3();
  3342. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3343. },
  3344. applyMatrix4: function() {
  3345. var v1 = new THREE.Vector3();
  3346. var v2 = new THREE.Vector3();
  3347. return function ( matrix, optionalNormalMatrix ) {
  3348. // compute new normal based on theory here:
  3349. // http://www.songho.ca/opengl/gl_normaltransform.html
  3350. optionalNormalMatrix = optionalNormalMatrix || new THREE.Matrix3().getNormalMatrix( matrix );
  3351. var newNormal = v1.copy( this.normal ).applyMatrix3( optionalNormalMatrix );
  3352. var newCoplanarPoint = this.coplanarPoint( v2 );
  3353. newCoplanarPoint.applyMatrix4( matrix );
  3354. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3355. return this;
  3356. };
  3357. }(),
  3358. translate: function ( offset ) {
  3359. this.constant = this.constant - offset.dot( this.normal );
  3360. return this;
  3361. },
  3362. equals: function ( plane ) {
  3363. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3364. },
  3365. clone: function () {
  3366. return new THREE.Plane().copy( this );
  3367. }
  3368. };
  3369. /**
  3370. * @author alteredq / http://alteredqualia.com/
  3371. * @author mrdoob / http://mrdoob.com/
  3372. */
  3373. THREE.Math = {
  3374. PI2: Math.PI * 2,
  3375. generateUUID: function () {
  3376. // http://www.broofa.com/Tools/Math.uuid.htm
  3377. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  3378. var uuid = new Array(36);
  3379. var rnd = 0, r;
  3380. return function () {
  3381. for ( var i = 0; i < 36; i ++ ) {
  3382. if ( i == 8 || i == 13 || i == 18 || i == 23 ) {
  3383. uuid[ i ] = '-';
  3384. } else if ( i == 14 ) {
  3385. uuid[ i ] = '4';
  3386. } else {
  3387. if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
  3388. r = rnd & 0xf;
  3389. rnd = rnd >> 4;
  3390. uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
  3391. }
  3392. }
  3393. return uuid.join('');
  3394. };
  3395. }(),
  3396. // Clamp value to range <a, b>
  3397. clamp: function ( x, a, b ) {
  3398. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3399. },
  3400. // Clamp value to range <a, inf)
  3401. clampBottom: function ( x, a ) {
  3402. return x < a ? a : x;
  3403. },
  3404. // Linear mapping from range <a1, a2> to range <b1, b2>
  3405. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3406. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3407. },
  3408. // http://en.wikipedia.org/wiki/Smoothstep
  3409. smoothstep: function ( x, min, max ) {
  3410. if ( x <= min ) return 0;
  3411. if ( x >= max ) return 1;
  3412. x = ( x - min )/( max - min );
  3413. return x*x*(3 - 2*x);
  3414. },
  3415. smootherstep: function ( x, min, max ) {
  3416. if ( x <= min ) return 0;
  3417. if ( x >= max ) return 1;
  3418. x = ( x - min )/( max - min );
  3419. return x*x*x*(x*(x*6 - 15) + 10);
  3420. },
  3421. // Random float from <0, 1> with 16 bits of randomness
  3422. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3423. random16: function () {
  3424. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3425. },
  3426. // Random integer from <low, high> interval
  3427. randInt: function ( low, high ) {
  3428. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  3429. },
  3430. // Random float from <low, high> interval
  3431. randFloat: function ( low, high ) {
  3432. return low + Math.random() * ( high - low );
  3433. },
  3434. // Random float from <-range/2, range/2> interval
  3435. randFloatSpread: function ( range ) {
  3436. return range * ( 0.5 - Math.random() );
  3437. },
  3438. sign: function ( x ) {
  3439. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  3440. },
  3441. degToRad: function() {
  3442. var degreeToRadiansFactor = Math.PI / 180;
  3443. return function ( degrees ) {
  3444. return degrees * degreeToRadiansFactor;
  3445. };
  3446. }(),
  3447. radToDeg: function() {
  3448. var radianToDegreesFactor = 180 / Math.PI;
  3449. return function ( radians ) {
  3450. return radians * radianToDegreesFactor;
  3451. };
  3452. }()
  3453. };
  3454. /**
  3455. * Spline from Tween.js, slightly optimized (and trashed)
  3456. * http://sole.github.com/tween.js/examples/05_spline.html
  3457. *
  3458. * @author mrdoob / http://mrdoob.com/
  3459. * @author alteredq / http://alteredqualia.com/
  3460. */
  3461. THREE.Spline = function ( points ) {
  3462. this.points = points;
  3463. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3464. point, intPoint, weight, w2, w3,
  3465. pa, pb, pc, pd;
  3466. this.initFromArray = function( a ) {
  3467. this.points = [];
  3468. for ( var i = 0; i < a.length; i++ ) {
  3469. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3470. }
  3471. };
  3472. this.getPoint = function ( k ) {
  3473. point = ( this.points.length - 1 ) * k;
  3474. intPoint = Math.floor( point );
  3475. weight = point - intPoint;
  3476. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3477. c[ 1 ] = intPoint;
  3478. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3479. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3480. pa = this.points[ c[ 0 ] ];
  3481. pb = this.points[ c[ 1 ] ];
  3482. pc = this.points[ c[ 2 ] ];
  3483. pd = this.points[ c[ 3 ] ];
  3484. w2 = weight * weight;
  3485. w3 = weight * w2;
  3486. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3487. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3488. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3489. return v3;
  3490. };
  3491. this.getControlPointsArray = function () {
  3492. var i, p, l = this.points.length,
  3493. coords = [];
  3494. for ( i = 0; i < l; i ++ ) {
  3495. p = this.points[ i ];
  3496. coords[ i ] = [ p.x, p.y, p.z ];
  3497. }
  3498. return coords;
  3499. };
  3500. // approximate length by summing linear segments
  3501. this.getLength = function ( nSubDivisions ) {
  3502. var i, index, nSamples, position,
  3503. point = 0, intPoint = 0, oldIntPoint = 0,
  3504. oldPosition = new THREE.Vector3(),
  3505. tmpVec = new THREE.Vector3(),
  3506. chunkLengths = [],
  3507. totalLength = 0;
  3508. // first point has 0 length
  3509. chunkLengths[ 0 ] = 0;
  3510. if ( !nSubDivisions ) nSubDivisions = 100;
  3511. nSamples = this.points.length * nSubDivisions;
  3512. oldPosition.copy( this.points[ 0 ] );
  3513. for ( i = 1; i < nSamples; i ++ ) {
  3514. index = i / nSamples;
  3515. position = this.getPoint( index );
  3516. tmpVec.copy( position );
  3517. totalLength += tmpVec.distanceTo( oldPosition );
  3518. oldPosition.copy( position );
  3519. point = ( this.points.length - 1 ) * index;
  3520. intPoint = Math.floor( point );
  3521. if ( intPoint != oldIntPoint ) {
  3522. chunkLengths[ intPoint ] = totalLength;
  3523. oldIntPoint = intPoint;
  3524. }
  3525. }
  3526. // last point ends with total length
  3527. chunkLengths[ chunkLengths.length ] = totalLength;
  3528. return { chunks: chunkLengths, total: totalLength };
  3529. };
  3530. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3531. var i, j,
  3532. index, indexCurrent, indexNext,
  3533. linearDistance, realDistance,
  3534. sampling, position,
  3535. newpoints = [],
  3536. tmpVec = new THREE.Vector3(),
  3537. sl = this.getLength();
  3538. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3539. for ( i = 1; i < this.points.length; i++ ) {
  3540. //tmpVec.copy( this.points[ i - 1 ] );
  3541. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3542. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3543. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3544. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3545. indexNext = i / ( this.points.length - 1 );
  3546. for ( j = 1; j < sampling - 1; j++ ) {
  3547. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3548. position = this.getPoint( index );
  3549. newpoints.push( tmpVec.copy( position ).clone() );
  3550. }
  3551. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3552. }
  3553. this.points = newpoints;
  3554. };
  3555. // Catmull-Rom
  3556. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3557. var v0 = ( p2 - p0 ) * 0.5,
  3558. v1 = ( p3 - p1 ) * 0.5;
  3559. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3560. };
  3561. };
  3562. /**
  3563. * @author bhouston / http://exocortex.com
  3564. * @author mrdoob / http://mrdoob.com/
  3565. */
  3566. THREE.Triangle = function ( a, b, c ) {
  3567. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3568. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3569. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3570. };
  3571. THREE.Triangle.normal = function() {
  3572. var v0 = new THREE.Vector3();
  3573. return function ( a, b, c, optionalTarget ) {
  3574. var result = optionalTarget || new THREE.Vector3();
  3575. result.subVectors( c, b );
  3576. v0.subVectors( a, b );
  3577. result.cross( v0 );
  3578. var resultLengthSq = result.lengthSq();
  3579. if( resultLengthSq > 0 ) {
  3580. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3581. }
  3582. return result.set( 0, 0, 0 );
  3583. };
  3584. }();
  3585. // static/instance method to calculate barycoordinates
  3586. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3587. THREE.Triangle.barycoordFromPoint = function() {
  3588. var v0 = new THREE.Vector3();
  3589. var v1 = new THREE.Vector3();
  3590. var v2 = new THREE.Vector3();
  3591. return function ( point, a, b, c, optionalTarget ) {
  3592. v0.subVectors( c, a );
  3593. v1.subVectors( b, a );
  3594. v2.subVectors( point, a );
  3595. var dot00 = v0.dot( v0 );
  3596. var dot01 = v0.dot( v1 );
  3597. var dot02 = v0.dot( v2 );
  3598. var dot11 = v1.dot( v1 );
  3599. var dot12 = v1.dot( v2 );
  3600. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3601. var result = optionalTarget || new THREE.Vector3();
  3602. // colinear or singular triangle
  3603. if( denom == 0 ) {
  3604. // arbitrary location outside of triangle?
  3605. // not sure if this is the best idea, maybe should be returning undefined
  3606. return result.set( -2, -1, -1 );
  3607. }
  3608. var invDenom = 1 / denom;
  3609. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3610. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3611. // barycoordinates must always sum to 1
  3612. return result.set( 1 - u - v, v, u );
  3613. };
  3614. }();
  3615. THREE.Triangle.containsPoint = function() {
  3616. var v1 = new THREE.Vector3();
  3617. return function ( point, a, b, c ) {
  3618. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  3619. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3620. };
  3621. }();
  3622. THREE.Triangle.prototype = {
  3623. constructor: THREE.Triangle,
  3624. set: function ( a, b, c ) {
  3625. this.a.copy( a );
  3626. this.b.copy( b );
  3627. this.c.copy( c );
  3628. return this;
  3629. },
  3630. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3631. this.a.copy( points[i0] );
  3632. this.b.copy( points[i1] );
  3633. this.c.copy( points[i2] );
  3634. return this;
  3635. },
  3636. copy: function ( triangle ) {
  3637. this.a.copy( triangle.a );
  3638. this.b.copy( triangle.b );
  3639. this.c.copy( triangle.c );
  3640. return this;
  3641. },
  3642. area: function() {
  3643. var v0 = new THREE.Vector3();
  3644. var v1 = new THREE.Vector3();
  3645. return function () {
  3646. v0.subVectors( this.c, this.b );
  3647. v1.subVectors( this.a, this.b );
  3648. return v0.cross( v1 ).length() * 0.5;
  3649. };
  3650. }(),
  3651. midpoint: function ( optionalTarget ) {
  3652. var result = optionalTarget || new THREE.Vector3();
  3653. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  3654. },
  3655. normal: function ( optionalTarget ) {
  3656. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3657. },
  3658. plane: function ( optionalTarget ) {
  3659. var result = optionalTarget || new THREE.Plane();
  3660. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  3661. },
  3662. barycoordFromPoint: function ( point, optionalTarget ) {
  3663. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  3664. },
  3665. containsPoint: function ( point ) {
  3666. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  3667. },
  3668. equals: function ( triangle ) {
  3669. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  3670. },
  3671. clone: function () {
  3672. return new THREE.Triangle().copy( this );
  3673. }
  3674. };
  3675. /**
  3676. * @author mrdoob / http://mrdoob.com/
  3677. */
  3678. THREE.Vertex = function ( v ) {
  3679. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  3680. return v;
  3681. };
  3682. /**
  3683. * @author mrdoob / http://mrdoob.com/
  3684. */
  3685. THREE.UV = function ( u, v ) {
  3686. console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
  3687. return new THREE.Vector2( u, v );
  3688. };
  3689. /**
  3690. * @author alteredq / http://alteredqualia.com/
  3691. */
  3692. THREE.Clock = function ( autoStart ) {
  3693. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  3694. this.startTime = 0;
  3695. this.oldTime = 0;
  3696. this.elapsedTime = 0;
  3697. this.running = false;
  3698. };
  3699. THREE.Clock.prototype = {
  3700. constructor: THREE.Clock,
  3701. start: function () {
  3702. this.startTime = self.performance !== undefined && self.performance.now !== undefined
  3703. ? self.performance.now()
  3704. : Date.now();
  3705. this.oldTime = this.startTime;
  3706. this.running = true;
  3707. },
  3708. stop: function () {
  3709. this.getElapsedTime();
  3710. this.running = false;
  3711. },
  3712. getElapsedTime: function () {
  3713. this.getDelta();
  3714. return this.elapsedTime;
  3715. },
  3716. getDelta: function () {
  3717. var diff = 0;
  3718. if ( this.autoStart && ! this.running ) {
  3719. this.start();
  3720. }
  3721. if ( this.running ) {
  3722. var newTime = self.performance !== undefined && self.performance.now !== undefined
  3723. ? self.performance.now()
  3724. : Date.now();
  3725. diff = 0.001 * ( newTime - this.oldTime );
  3726. this.oldTime = newTime;
  3727. this.elapsedTime += diff;
  3728. }
  3729. return diff;
  3730. }
  3731. };
  3732. /**
  3733. * https://github.com/mrdoob/eventdispatcher.js/
  3734. */
  3735. THREE.EventDispatcher = function () {}
  3736. THREE.EventDispatcher.prototype = {
  3737. constructor: THREE.EventDispatcher,
  3738. addEventListener: function ( type, listener ) {
  3739. if ( this._listeners === undefined ) this._listeners = {};
  3740. var listeners = this._listeners;
  3741. if ( listeners[ type ] === undefined ) {
  3742. listeners[ type ] = [];
  3743. }
  3744. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  3745. listeners[ type ].push( listener );
  3746. }
  3747. },
  3748. hasEventListener: function ( type, listener ) {
  3749. if ( this._listeners === undefined ) return false;
  3750. var listeners = this._listeners;
  3751. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  3752. return true;
  3753. }
  3754. return false;
  3755. },
  3756. removeEventListener: function ( type, listener ) {
  3757. if ( this._listeners === undefined ) return;
  3758. var listeners = this._listeners;
  3759. var index = listeners[ type ].indexOf( listener );
  3760. if ( index !== - 1 ) {
  3761. listeners[ type ].splice( index, 1 );
  3762. }
  3763. },
  3764. dispatchEvent: function ( event ) {
  3765. if ( this._listeners === undefined ) return;
  3766. var listeners = this._listeners;
  3767. var listenerArray = listeners[ event.type ];
  3768. if ( listenerArray !== undefined ) {
  3769. event.target = this;
  3770. for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
  3771. listenerArray[ i ].call( this, event );
  3772. }
  3773. }
  3774. }
  3775. };
  3776. /**
  3777. * @author mrdoob / http://mrdoob.com/
  3778. * @author bhouston / http://exocortex.com/
  3779. */
  3780. ( function ( THREE ) {
  3781. THREE.Raycaster = function ( origin, direction, near, far ) {
  3782. this.ray = new THREE.Ray( origin, direction );
  3783. // normalized ray.direction required for accurate distance calculations
  3784. if ( this.ray.direction.lengthSq() > 0 ) {
  3785. this.ray.direction.normalize();
  3786. }
  3787. this.near = near || 0;
  3788. this.far = far || Infinity;
  3789. };
  3790. var sphere = new THREE.Sphere();
  3791. var localRay = new THREE.Ray();
  3792. var facePlane = new THREE.Plane();
  3793. var intersectPoint = new THREE.Vector3();
  3794. var matrixPosition = new THREE.Vector3();
  3795. var inverseMatrix = new THREE.Matrix4();
  3796. var descSort = function ( a, b ) {
  3797. return a.distance - b.distance;
  3798. };
  3799. var intersectObject = function ( object, raycaster, intersects ) {
  3800. if ( object instanceof THREE.Particle ) {
  3801. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3802. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  3803. if ( distance > object.scale.x ) {
  3804. return intersects;
  3805. }
  3806. intersects.push( {
  3807. distance: distance,
  3808. point: object.position,
  3809. face: null,
  3810. object: object
  3811. } );
  3812. } else if ( object instanceof THREE.LOD ) {
  3813. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3814. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  3815. intersectObject( object.getObjectForDistance( distance ), raycaster, intersects );
  3816. } else if (object instanceof THREE.Mesh ) {
  3817. // Checking boundingSphere distance to ray
  3818. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3819. sphere.set( matrixPosition, object.geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis() );
  3820. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  3821. return intersects;
  3822. }
  3823. var geometry = object.geometry;
  3824. var vertices = geometry.vertices;
  3825. if ( geometry instanceof THREE.BufferGeometry ) {
  3826. var material = object.material;
  3827. if ( material === undefined ) return intersects;
  3828. if ( ! geometry.dynamic ) return intersects;
  3829. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3830. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  3831. var side = object.material.side;
  3832. var a, b, c;
  3833. var precision = raycaster.precision;
  3834. inverseMatrix.getInverse( object.matrixWorld );
  3835. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  3836. var fl;
  3837. var indexed = false;
  3838. if ( geometry.attributes.index ) {
  3839. indexed = true;
  3840. fl = geometry.attributes.index.numItems / 3;
  3841. } else {
  3842. fl = geometry.attributes.position.numItems / 9;
  3843. }
  3844. var vA = new THREE.Vector3();
  3845. var vB = new THREE.Vector3();
  3846. var vC = new THREE.Vector3();
  3847. var vCB = new THREE.Vector3();
  3848. var vAB = new THREE.Vector3();
  3849. for ( var oi = 0; oi < geometry.offsets.length; ++oi ) {
  3850. var start = geometry.offsets[ oi ].start;
  3851. var count = geometry.offsets[ oi ].count;
  3852. var index = geometry.offsets[ oi ].index;
  3853. for ( var i = start, il = start + count; i < il; i += 3 ) {
  3854. if ( indexed ) {
  3855. a = index + geometry.attributes.index.array[ i ];
  3856. b = index + geometry.attributes.index.array[ i + 1 ];
  3857. c = index + geometry.attributes.index.array[ i + 2 ];
  3858. } else {
  3859. a = index;
  3860. b = index + 1;
  3861. c = index + 2;
  3862. }
  3863. vA.set( geometry.attributes.position.array[ a * 3 ],
  3864. geometry.attributes.position.array[ a * 3 + 1 ],
  3865. geometry.attributes.position.array[ a * 3 + 2] );
  3866. vB.set( geometry.attributes.position.array[ b * 3 ],
  3867. geometry.attributes.position.array[ b * 3 + 1 ],
  3868. geometry.attributes.position.array[ b * 3 + 2] );
  3869. vC.set( geometry.attributes.position.array[ c * 3 ],
  3870. geometry.attributes.position.array[ c * 3 + 1 ],
  3871. geometry.attributes.position.array[ c * 3 + 2 ] );
  3872. facePlane.setFromCoplanarPoints( vA, vB, vC );
  3873. var planeDistance = localRay.distanceToPlane( facePlane );
  3874. // bail if raycaster and plane are parallel
  3875. if ( Math.abs( planeDistance ) < precision ) continue;
  3876. // if negative distance, then plane is behind raycaster
  3877. if ( planeDistance < 0 ) continue;
  3878. // check if we hit the wrong side of a single sided face
  3879. side = material.side;
  3880. if ( side !== THREE.DoubleSide ) {
  3881. var planeSign = localRay.direction.dot( facePlane.normal );
  3882. if ( ! ( side === THREE.FrontSide ? planeSign < 0 : planeSign > 0 ) ) continue;
  3883. }
  3884. // this can be done using the planeDistance from localRay because localRay wasn't normalized, but ray was
  3885. if ( planeDistance < raycaster.near || planeDistance > raycaster.far ) continue;
  3886. intersectPoint = localRay.at( planeDistance, intersectPoint ); // passing in intersectPoint avoids a copy
  3887. if ( ! THREE.Triangle.containsPoint( intersectPoint, vA, vB, vC ) ) continue;
  3888. intersects.push( {
  3889. distance: planeDistance, // this works because the original ray was normalized, and the transformed localRay wasn't
  3890. point: raycaster.ray.at(planeDistance),
  3891. face: null,
  3892. faceIndex: null,
  3893. object: object
  3894. } );
  3895. }
  3896. }
  3897. } else if ( geometry instanceof THREE.Geometry ) {
  3898. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3899. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  3900. var side = object.material.side;
  3901. var a, b, c, d;
  3902. var precision = raycaster.precision;
  3903. inverseMatrix.getInverse( object.matrixWorld );
  3904. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  3905. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  3906. var face = geometry.faces[ f ];
  3907. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  3908. if ( material === undefined ) continue;
  3909. facePlane.setFromNormalAndCoplanarPoint( face.normal, vertices[face.a] );
  3910. var planeDistance = localRay.distanceToPlane( facePlane );
  3911. // bail if raycaster and plane are parallel
  3912. if ( Math.abs( planeDistance ) < precision ) continue;
  3913. // if negative distance, then plane is behind raycaster
  3914. if ( planeDistance < 0 ) continue;
  3915. // check if we hit the wrong side of a single sided face
  3916. side = material.side;
  3917. if ( side !== THREE.DoubleSide ) {
  3918. var planeSign = localRay.direction.dot( facePlane.normal );
  3919. if ( ! ( side === THREE.FrontSide ? planeSign < 0 : planeSign > 0 ) ) continue;
  3920. }
  3921. // this can be done using the planeDistance from localRay because localRay wasn't normalized, but ray was
  3922. if ( planeDistance < raycaster.near || planeDistance > raycaster.far ) continue;
  3923. intersectPoint = localRay.at( planeDistance, intersectPoint ); // passing in intersectPoint avoids a copy
  3924. if ( face instanceof THREE.Face3 ) {
  3925. a = vertices[ face.a ];
  3926. b = vertices[ face.b ];
  3927. c = vertices[ face.c ];
  3928. if ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, c ) ) continue;
  3929. } else if ( face instanceof THREE.Face4 ) {
  3930. a = vertices[ face.a ];
  3931. b = vertices[ face.b ];
  3932. c = vertices[ face.c ];
  3933. d = vertices[ face.d ];
  3934. if ( ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, d ) ) &&
  3935. ( ! THREE.Triangle.containsPoint( intersectPoint, b, c, d ) ) ) continue;
  3936. } else {
  3937. // This is added because if we call out of this if/else group when none of the cases
  3938. // match it will add a point to the intersection list erroneously.
  3939. throw Error( "face type not supported" );
  3940. }
  3941. intersects.push( {
  3942. distance: planeDistance, // this works because the original ray was normalized, and the transformed localRay wasn't
  3943. point: raycaster.ray.at( planeDistance ),
  3944. face: face,
  3945. faceIndex: f,
  3946. object: object
  3947. } );
  3948. }
  3949. }
  3950. }
  3951. };
  3952. var intersectDescendants = function ( object, raycaster, intersects ) {
  3953. var descendants = object.getDescendants();
  3954. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  3955. intersectObject( descendants[ i ], raycaster, intersects );
  3956. }
  3957. };
  3958. //
  3959. THREE.Raycaster.prototype.precision = 0.0001;
  3960. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  3961. this.ray.set( origin, direction );
  3962. // normalized ray.direction required for accurate distance calculations
  3963. if ( this.ray.direction.length() > 0 ) {
  3964. this.ray.direction.normalize();
  3965. }
  3966. };
  3967. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  3968. var intersects = [];
  3969. if ( recursive === true ) {
  3970. intersectDescendants( object, this, intersects );
  3971. }
  3972. intersectObject( object, this, intersects );
  3973. intersects.sort( descSort );
  3974. return intersects;
  3975. };
  3976. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  3977. var intersects = [];
  3978. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  3979. intersectObject( objects[ i ], this, intersects );
  3980. if ( recursive === true ) {
  3981. intersectDescendants( objects[ i ], this, intersects );
  3982. }
  3983. }
  3984. intersects.sort( descSort );
  3985. return intersects;
  3986. };
  3987. }( THREE ) );
  3988. /**
  3989. * @author mrdoob / http://mrdoob.com/
  3990. * @author mikael emtinger / http://gomo.se/
  3991. * @author alteredq / http://alteredqualia.com/
  3992. * @author WestLangley / http://github.com/WestLangley
  3993. */
  3994. THREE.Object3D = function () {
  3995. this.id = THREE.Math.generateUUID();
  3996. this.name = '';
  3997. this.parent = undefined;
  3998. this.children = [];
  3999. this.up = new THREE.Vector3( 0, 1, 0 );
  4000. this.position = new THREE.Vector3();
  4001. this.quaternion = new THREE.Quaternion();
  4002. this.scale = new THREE.Vector3( 1, 1, 1 );
  4003. // for backwards compatibility (maps changes to this.rotation onto this.quaternion)
  4004. this.rotation = new THREE.Rotation( this.quaternion );
  4005. this.renderDepth = null;
  4006. this.rotationAutoUpdate = true;
  4007. this.matrix = new THREE.Matrix4();
  4008. this.matrixWorld = new THREE.Matrix4();
  4009. this.matrixAutoUpdate = true;
  4010. this.matrixWorldNeedsUpdate = true;
  4011. this.visible = true;
  4012. this.castShadow = false;
  4013. this.receiveShadow = false;
  4014. this.frustumCulled = true;
  4015. this.userData = {};
  4016. };
  4017. THREE.Object3D.prototype = {
  4018. constructor: THREE.Object3D,
  4019. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  4020. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  4021. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  4022. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  4023. applyMatrix: function () {
  4024. var m1 = new THREE.Matrix4();
  4025. return function ( matrix ) {
  4026. this.matrix.multiplyMatrices( matrix, this.matrix );
  4027. this.position.getPositionFromMatrix( this.matrix );
  4028. this.scale.getScaleFromMatrix( this.matrix );
  4029. m1.extractRotation( this.matrix );
  4030. this.quaternion.setFromRotationMatrix( m1 );
  4031. }
  4032. }(),
  4033. rotateOnAxis: function() {
  4034. // rotate object on axis in object space
  4035. // axis is assumed to be normalized
  4036. var q1 = new THREE.Quaternion();
  4037. var q2 = new THREE.Quaternion();
  4038. return function ( axis, angle ) {
  4039. q1.setFromAxisAngle( axis, angle );
  4040. this.quaternion.multiply( q1 );
  4041. return this;
  4042. }
  4043. }(),
  4044. translateOnAxis: function () {
  4045. // translate object by distance along axis in object space
  4046. // axis is assumed to be normalized
  4047. var v1 = new THREE.Vector3();
  4048. return function ( axis, distance ) {
  4049. v1.copy( axis );
  4050. v1.applyQuaternion( this.quaternion );
  4051. this.position.add( v1.multiplyScalar( distance ) );
  4052. return this;
  4053. }
  4054. }(),
  4055. translate: function ( distance, axis ) {
  4056. console.warn( 'DEPRECATED: Object3D\'s .translate() has been removed. Use .translateOnAxis( axis, distance ) instead. Note args have been changed.' );
  4057. return this.translateOnAxis( axis, distance );
  4058. },
  4059. translateX: function () {
  4060. var v1 = new THREE.Vector3( 1, 0, 0 );
  4061. return function ( distance ) {
  4062. return this.translateOnAxis( v1, distance );
  4063. };
  4064. }(),
  4065. translateY: function () {
  4066. var v1 = new THREE.Vector3( 0, 1, 0 );
  4067. return function ( distance ) {
  4068. return this.translateOnAxis( v1, distance );
  4069. };
  4070. }(),
  4071. translateZ: function () {
  4072. var v1 = new THREE.Vector3( 0, 0, 1 );
  4073. return function ( distance ) {
  4074. return this.translateOnAxis( v1, distance );
  4075. };
  4076. }(),
  4077. localToWorld: function ( vector ) {
  4078. return vector.applyMatrix4( this.matrixWorld );
  4079. },
  4080. worldToLocal: function () {
  4081. var m1 = new THREE.Matrix4();
  4082. return function ( vector ) {
  4083. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  4084. };
  4085. }(),
  4086. lookAt: function () {
  4087. // This routine does not support objects with rotated and/or translated parent(s)
  4088. var m1 = new THREE.Matrix4();
  4089. return function ( vector ) {
  4090. m1.lookAt( vector, this.position, this.up );
  4091. this.quaternion.setFromRotationMatrix( m1 );
  4092. };
  4093. }(),
  4094. add: function ( object ) {
  4095. if ( object === this ) {
  4096. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  4097. return;
  4098. }
  4099. if ( object instanceof THREE.Object3D ) {
  4100. if ( object.parent !== undefined ) {
  4101. object.parent.remove( object );
  4102. }
  4103. object.parent = this;
  4104. this.children.push( object );
  4105. // add to scene
  4106. var scene = this;
  4107. while ( scene.parent !== undefined ) {
  4108. scene = scene.parent;
  4109. }
  4110. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4111. scene.__addObject( object );
  4112. }
  4113. }
  4114. },
  4115. remove: function ( object ) {
  4116. var index = this.children.indexOf( object );
  4117. if ( index !== - 1 ) {
  4118. object.parent = undefined;
  4119. this.children.splice( index, 1 );
  4120. // remove from scene
  4121. var scene = this;
  4122. while ( scene.parent !== undefined ) {
  4123. scene = scene.parent;
  4124. }
  4125. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4126. scene.__removeObject( object );
  4127. }
  4128. }
  4129. },
  4130. traverse: function ( callback ) {
  4131. callback( this );
  4132. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4133. this.children[ i ].traverse( callback );
  4134. }
  4135. },
  4136. getObjectById: function ( id, recursive ) {
  4137. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4138. var child = this.children[ i ];
  4139. if ( child.id === id ) {
  4140. return child;
  4141. }
  4142. if ( recursive === true ) {
  4143. child = child.getObjectById( id, recursive );
  4144. if ( child !== undefined ) {
  4145. return child;
  4146. }
  4147. }
  4148. }
  4149. return undefined;
  4150. },
  4151. getObjectByName: function ( name, recursive ) {
  4152. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4153. var child = this.children[ i ];
  4154. if ( child.name === name ) {
  4155. return child;
  4156. }
  4157. if ( recursive === true ) {
  4158. child = child.getObjectByName( name, recursive );
  4159. if ( child !== undefined ) {
  4160. return child;
  4161. }
  4162. }
  4163. }
  4164. return undefined;
  4165. },
  4166. getChildByName: function ( name, recursive ) {
  4167. console.warn( 'DEPRECATED: Object3D\'s .getChildByName() has been renamed to .getObjectByName().' );
  4168. return this.getObjectByName( name, recursive );
  4169. },
  4170. getDescendants: function ( array ) {
  4171. if ( array === undefined ) array = [];
  4172. Array.prototype.push.apply( array, this.children );
  4173. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4174. this.children[ i ].getDescendants( array );
  4175. }
  4176. return array;
  4177. },
  4178. updateMatrix: function () {
  4179. this.matrix.makeFromPositionQuaternionScale( this.position, this.quaternion, this.scale );
  4180. this.matrixWorldNeedsUpdate = true;
  4181. },
  4182. updateMatrixWorld: function ( force ) {
  4183. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  4184. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  4185. if ( this.parent === undefined ) {
  4186. this.matrixWorld.copy( this.matrix );
  4187. } else {
  4188. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4189. }
  4190. this.matrixWorldNeedsUpdate = false;
  4191. force = true;
  4192. }
  4193. // update children
  4194. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4195. this.children[ i ].updateMatrixWorld( force );
  4196. }
  4197. },
  4198. clone: function ( object, recursive ) {
  4199. if ( object === undefined ) object = new THREE.Object3D();
  4200. if ( recursive === undefined ) recursive = true;
  4201. object.name = this.name;
  4202. object.up.copy( this.up );
  4203. object.position.copy( this.position );
  4204. object.quaternion.copy( this.quaternion );
  4205. object.scale.copy( this.scale );
  4206. object.renderDepth = this.renderDepth;
  4207. object.rotationAutoUpdate = this.rotationAutoUpdate;
  4208. object.matrix.copy( this.matrix );
  4209. object.matrixWorld.copy( this.matrixWorld );
  4210. object.matrixAutoUpdate = this.matrixAutoUpdate;
  4211. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  4212. object.visible = this.visible;
  4213. object.castShadow = this.castShadow;
  4214. object.receiveShadow = this.receiveShadow;
  4215. object.frustumCulled = this.frustumCulled;
  4216. object.userData = JSON.parse( JSON.stringify( this.userData ) );
  4217. if ( recursive === true ) {
  4218. for ( var i = 0; i < this.children.length; i ++ ) {
  4219. var child = this.children[ i ];
  4220. object.add( child.clone() );
  4221. }
  4222. }
  4223. return object;
  4224. }
  4225. };
  4226. THREE.Object3D.defaultEulerOrder = 'XYZ';
  4227. /**
  4228. * @author mrdoob / http://mrdoob.com/
  4229. * @author supereggbert / http://www.paulbrunt.co.uk/
  4230. * @author julianwa / https://github.com/julianwa
  4231. */
  4232. THREE.Projector = function () {
  4233. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  4234. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  4235. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  4236. _face4Count, _face4Pool = [], _face4PoolLength = 0,
  4237. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  4238. _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
  4239. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  4240. _vector3 = new THREE.Vector3(),
  4241. _vector4 = new THREE.Vector4(),
  4242. _clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ),
  4243. _boundingBox = new THREE.Box3(),
  4244. _points3 = new Array( 3 ),
  4245. _points4 = new Array( 4 ),
  4246. _viewMatrix = new THREE.Matrix4(),
  4247. _viewProjectionMatrix = new THREE.Matrix4(),
  4248. _modelMatrix,
  4249. _modelViewProjectionMatrix = new THREE.Matrix4(),
  4250. _normalMatrix = new THREE.Matrix3(),
  4251. _normalViewMatrix = new THREE.Matrix3(),
  4252. _centroid = new THREE.Vector3(),
  4253. _frustum = new THREE.Frustum(),
  4254. _clippedVertex1PositionScreen = new THREE.Vector4(),
  4255. _clippedVertex2PositionScreen = new THREE.Vector4();
  4256. this.projectVector = function ( vector, camera ) {
  4257. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  4258. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  4259. return vector.applyProjection( _viewProjectionMatrix );
  4260. };
  4261. this.unprojectVector = function ( vector, camera ) {
  4262. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  4263. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, camera.projectionMatrixInverse );
  4264. return vector.applyProjection( _viewProjectionMatrix );
  4265. };
  4266. this.pickingRay = function ( vector, camera ) {
  4267. // set two vectors with opposing z values
  4268. vector.z = -1.0;
  4269. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  4270. this.unprojectVector( vector, camera );
  4271. this.unprojectVector( end, camera );
  4272. // find direction from vector to end
  4273. end.sub( vector ).normalize();
  4274. return new THREE.Raycaster( vector, end );
  4275. };
  4276. var getObject = function ( object ) {
  4277. _object = getNextObjectInPool();
  4278. _object.object = object;
  4279. if ( object.renderDepth !== null ) {
  4280. _object.z = object.renderDepth;
  4281. } else {
  4282. _vector3.getPositionFromMatrix( object.matrixWorld );
  4283. _vector3.applyProjection( _viewProjectionMatrix );
  4284. _object.z = _vector3.z;
  4285. }
  4286. return _object;
  4287. };
  4288. var projectObject = function ( object ) {
  4289. if ( object.visible === false ) return;
  4290. if ( object instanceof THREE.Light ) {
  4291. _renderData.lights.push( object );
  4292. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  4293. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  4294. _renderData.objects.push( getObject( object ) );
  4295. }
  4296. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  4297. _renderData.sprites.push( getObject( object ) );
  4298. }
  4299. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  4300. projectObject( object.children[ i ] );
  4301. }
  4302. };
  4303. var projectGraph = function ( root, sortObjects ) {
  4304. _objectCount = 0;
  4305. _renderData.objects.length = 0;
  4306. _renderData.sprites.length = 0;
  4307. _renderData.lights.length = 0;
  4308. projectObject( root );
  4309. if ( sortObjects === true ) {
  4310. _renderData.objects.sort( painterSort );
  4311. }
  4312. };
  4313. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  4314. var visible = false,
  4315. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  4316. geometry, vertices, faces, face, faceVertexNormals, faceVertexUvs, uvs,
  4317. v1, v2, v3, v4, isFaceMaterial, objectMaterials;
  4318. _face3Count = 0;
  4319. _face4Count = 0;
  4320. _lineCount = 0;
  4321. _particleCount = 0;
  4322. _renderData.elements.length = 0;
  4323. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  4324. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  4325. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  4326. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  4327. _normalViewMatrix.getNormalMatrix( _viewMatrix );
  4328. _frustum.setFromMatrix( _viewProjectionMatrix );
  4329. projectGraph( scene, sortObjects );
  4330. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  4331. object = _renderData.objects[ o ].object;
  4332. _modelMatrix = object.matrixWorld;
  4333. _vertexCount = 0;
  4334. if ( object instanceof THREE.Mesh ) {
  4335. geometry = object.geometry;
  4336. vertices = geometry.vertices;
  4337. faces = geometry.faces;
  4338. faceVertexUvs = geometry.faceVertexUvs;
  4339. _normalMatrix.getNormalMatrix( _modelMatrix );
  4340. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4341. objectMaterials = isFaceMaterial === true ? object.material : null;
  4342. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  4343. _vertex = getNextVertexInPool();
  4344. _vertex.positionWorld.copy( vertices[ v ] ).applyMatrix4( _modelMatrix );
  4345. _vertex.positionScreen.copy( _vertex.positionWorld ).applyMatrix4( _viewProjectionMatrix );
  4346. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  4347. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  4348. _vertex.positionScreen.z /= _vertex.positionScreen.w;
  4349. _vertex.visible = ! ( _vertex.positionScreen.x < -1 || _vertex.positionScreen.x > 1 ||
  4350. _vertex.positionScreen.y < -1 || _vertex.positionScreen.y > 1 ||
  4351. _vertex.positionScreen.z < -1 || _vertex.positionScreen.z > 1 );
  4352. }
  4353. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  4354. face = faces[ f ];
  4355. var material = isFaceMaterial === true
  4356. ? objectMaterials.materials[ face.materialIndex ]
  4357. : object.material;
  4358. if ( material === undefined ) continue;
  4359. var side = material.side;
  4360. if ( face instanceof THREE.Face3 ) {
  4361. v1 = _vertexPool[ face.a ];
  4362. v2 = _vertexPool[ face.b ];
  4363. v3 = _vertexPool[ face.c ];
  4364. _points3[ 0 ] = v1.positionScreen;
  4365. _points3[ 1 ] = v2.positionScreen;
  4366. _points3[ 2 ] = v3.positionScreen;
  4367. if ( v1.visible === true || v2.visible === true || v3.visible === true ||
  4368. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) ) ) {
  4369. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  4370. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  4371. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  4372. _face = getNextFace3InPool();
  4373. _face.v1.copy( v1 );
  4374. _face.v2.copy( v2 );
  4375. _face.v3.copy( v3 );
  4376. } else {
  4377. continue;
  4378. }
  4379. } else {
  4380. continue;
  4381. }
  4382. } else if ( face instanceof THREE.Face4 ) {
  4383. v1 = _vertexPool[ face.a ];
  4384. v2 = _vertexPool[ face.b ];
  4385. v3 = _vertexPool[ face.c ];
  4386. v4 = _vertexPool[ face.d ];
  4387. _points4[ 0 ] = v1.positionScreen;
  4388. _points4[ 1 ] = v2.positionScreen;
  4389. _points4[ 2 ] = v3.positionScreen;
  4390. _points4[ 3 ] = v4.positionScreen;
  4391. if ( v1.visible === true || v2.visible === true || v3.visible === true || v4.visible === true ||
  4392. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points4 ) ) ) {
  4393. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  4394. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  4395. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  4396. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  4397. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  4398. _face = getNextFace4InPool();
  4399. _face.v1.copy( v1 );
  4400. _face.v2.copy( v2 );
  4401. _face.v3.copy( v3 );
  4402. _face.v4.copy( v4 );
  4403. } else {
  4404. continue;
  4405. }
  4406. } else {
  4407. continue;
  4408. }
  4409. }
  4410. _face.normalModel.copy( face.normal );
  4411. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4412. _face.normalModel.negate();
  4413. }
  4414. _face.normalModel.applyMatrix3( _normalMatrix ).normalize();
  4415. _face.normalModelView.copy( _face.normalModel ).applyMatrix3( _normalViewMatrix );
  4416. _face.centroidModel.copy( face.centroid ).applyMatrix4( _modelMatrix );
  4417. faceVertexNormals = face.vertexNormals;
  4418. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  4419. var normalModel = _face.vertexNormalsModel[ n ];
  4420. normalModel.copy( faceVertexNormals[ n ] );
  4421. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4422. normalModel.negate();
  4423. }
  4424. normalModel.applyMatrix3( _normalMatrix ).normalize();
  4425. var normalModelView = _face.vertexNormalsModelView[ n ];
  4426. normalModelView.copy( normalModel ).applyMatrix3( _normalViewMatrix );
  4427. }
  4428. _face.vertexNormalsLength = faceVertexNormals.length;
  4429. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  4430. uvs = faceVertexUvs[ c ][ f ];
  4431. if ( uvs === undefined ) continue;
  4432. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  4433. _face.uvs[ c ][ u ] = uvs[ u ];
  4434. }
  4435. }
  4436. _face.color = face.color;
  4437. _face.material = material;
  4438. _centroid.copy( _face.centroidModel ).applyProjection( _viewProjectionMatrix );
  4439. _face.z = _centroid.z;
  4440. _renderData.elements.push( _face );
  4441. }
  4442. } else if ( object instanceof THREE.Line ) {
  4443. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  4444. vertices = object.geometry.vertices;
  4445. v1 = getNextVertexInPool();
  4446. v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
  4447. // Handle LineStrip and LinePieces
  4448. var step = object.type === THREE.LinePieces ? 2 : 1;
  4449. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  4450. v1 = getNextVertexInPool();
  4451. v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
  4452. if ( ( v + 1 ) % step > 0 ) continue;
  4453. v2 = _vertexPool[ _vertexCount - 2 ];
  4454. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  4455. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  4456. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  4457. // Perform the perspective divide
  4458. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  4459. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  4460. _line = getNextLineInPool();
  4461. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  4462. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  4463. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  4464. _line.material = object.material;
  4465. if ( object.material.vertexColors === THREE.VertexColors ) {
  4466. _line.vertexColors[ 0 ].copy( object.geometry.colors[ v ] );
  4467. _line.vertexColors[ 1 ].copy( object.geometry.colors[ v - 1 ] );
  4468. }
  4469. _renderData.elements.push( _line );
  4470. }
  4471. }
  4472. }
  4473. }
  4474. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  4475. object = _renderData.sprites[ o ].object;
  4476. _modelMatrix = object.matrixWorld;
  4477. if ( object instanceof THREE.Particle ) {
  4478. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  4479. _vector4.applyMatrix4( _viewProjectionMatrix );
  4480. _vector4.z /= _vector4.w;
  4481. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  4482. _particle = getNextParticleInPool();
  4483. _particle.object = object;
  4484. _particle.x = _vector4.x / _vector4.w;
  4485. _particle.y = _vector4.y / _vector4.w;
  4486. _particle.z = _vector4.z;
  4487. _particle.rotation = object.rotation.z;
  4488. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  4489. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  4490. _particle.material = object.material;
  4491. _renderData.elements.push( _particle );
  4492. }
  4493. }
  4494. }
  4495. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  4496. return _renderData;
  4497. };
  4498. // Pools
  4499. function getNextObjectInPool() {
  4500. if ( _objectCount === _objectPoolLength ) {
  4501. var object = new THREE.RenderableObject();
  4502. _objectPool.push( object );
  4503. _objectPoolLength ++;
  4504. _objectCount ++;
  4505. return object;
  4506. }
  4507. return _objectPool[ _objectCount ++ ];
  4508. }
  4509. function getNextVertexInPool() {
  4510. if ( _vertexCount === _vertexPoolLength ) {
  4511. var vertex = new THREE.RenderableVertex();
  4512. _vertexPool.push( vertex );
  4513. _vertexPoolLength ++;
  4514. _vertexCount ++;
  4515. return vertex;
  4516. }
  4517. return _vertexPool[ _vertexCount ++ ];
  4518. }
  4519. function getNextFace3InPool() {
  4520. if ( _face3Count === _face3PoolLength ) {
  4521. var face = new THREE.RenderableFace3();
  4522. _face3Pool.push( face );
  4523. _face3PoolLength ++;
  4524. _face3Count ++;
  4525. return face;
  4526. }
  4527. return _face3Pool[ _face3Count ++ ];
  4528. }
  4529. function getNextFace4InPool() {
  4530. if ( _face4Count === _face4PoolLength ) {
  4531. var face = new THREE.RenderableFace4();
  4532. _face4Pool.push( face );
  4533. _face4PoolLength ++;
  4534. _face4Count ++;
  4535. return face;
  4536. }
  4537. return _face4Pool[ _face4Count ++ ];
  4538. }
  4539. function getNextLineInPool() {
  4540. if ( _lineCount === _linePoolLength ) {
  4541. var line = new THREE.RenderableLine();
  4542. _linePool.push( line );
  4543. _linePoolLength ++;
  4544. _lineCount ++
  4545. return line;
  4546. }
  4547. return _linePool[ _lineCount ++ ];
  4548. }
  4549. function getNextParticleInPool() {
  4550. if ( _particleCount === _particlePoolLength ) {
  4551. var particle = new THREE.RenderableParticle();
  4552. _particlePool.push( particle );
  4553. _particlePoolLength ++;
  4554. _particleCount ++
  4555. return particle;
  4556. }
  4557. return _particlePool[ _particleCount ++ ];
  4558. }
  4559. //
  4560. function painterSort( a, b ) {
  4561. return b.z - a.z;
  4562. }
  4563. function clipLine( s1, s2 ) {
  4564. var alpha1 = 0, alpha2 = 1,
  4565. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  4566. // Z = -1 and Z = +1, respectively.
  4567. bc1near = s1.z + s1.w,
  4568. bc2near = s2.z + s2.w,
  4569. bc1far = - s1.z + s1.w,
  4570. bc2far = - s2.z + s2.w;
  4571. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  4572. // Both vertices lie entirely within all clip planes.
  4573. return true;
  4574. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  4575. // Both vertices lie entirely outside one of the clip planes.
  4576. return false;
  4577. } else {
  4578. // The line segment spans at least one clip plane.
  4579. if ( bc1near < 0 ) {
  4580. // v1 lies outside the near plane, v2 inside
  4581. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  4582. } else if ( bc2near < 0 ) {
  4583. // v2 lies outside the near plane, v1 inside
  4584. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  4585. }
  4586. if ( bc1far < 0 ) {
  4587. // v1 lies outside the far plane, v2 inside
  4588. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  4589. } else if ( bc2far < 0 ) {
  4590. // v2 lies outside the far plane, v2 inside
  4591. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  4592. }
  4593. if ( alpha2 < alpha1 ) {
  4594. // The line segment spans two boundaries, but is outside both of them.
  4595. // (This can't happen when we're only clipping against just near/far but good
  4596. // to leave the check here for future usage if other clip planes are added.)
  4597. return false;
  4598. } else {
  4599. // Update the s1 and s2 vertices to match the clipped line segment.
  4600. s1.lerp( s2, alpha1 );
  4601. s2.lerp( s1, 1 - alpha2 );
  4602. return true;
  4603. }
  4604. }
  4605. }
  4606. };
  4607. /**
  4608. * @author mrdoob / http://mrdoob.com/
  4609. * @author alteredq / http://alteredqualia.com/
  4610. */
  4611. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  4612. this.a = a;
  4613. this.b = b;
  4614. this.c = c;
  4615. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4616. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4617. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4618. this.vertexColors = color instanceof Array ? color : [];
  4619. this.vertexTangents = [];
  4620. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4621. this.centroid = new THREE.Vector3();
  4622. };
  4623. THREE.Face3.prototype = {
  4624. constructor: THREE.Face3,
  4625. clone: function () {
  4626. var face = new THREE.Face3( this.a, this.b, this.c );
  4627. face.normal.copy( this.normal );
  4628. face.color.copy( this.color );
  4629. face.centroid.copy( this.centroid );
  4630. face.materialIndex = this.materialIndex;
  4631. var i, il;
  4632. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4633. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4634. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4635. return face;
  4636. }
  4637. };
  4638. /**
  4639. * @author mrdoob / http://mrdoob.com/
  4640. * @author alteredq / http://alteredqualia.com/
  4641. */
  4642. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  4643. this.a = a;
  4644. this.b = b;
  4645. this.c = c;
  4646. this.d = d;
  4647. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4648. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4649. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4650. this.vertexColors = color instanceof Array ? color : [];
  4651. this.vertexTangents = [];
  4652. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4653. this.centroid = new THREE.Vector3();
  4654. };
  4655. THREE.Face4.prototype = {
  4656. constructor: THREE.Face4,
  4657. clone: function () {
  4658. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  4659. face.normal.copy( this.normal );
  4660. face.color.copy( this.color );
  4661. face.centroid.copy( this.centroid );
  4662. face.materialIndex = this.materialIndex;
  4663. var i, il;
  4664. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4665. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4666. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4667. return face;
  4668. }
  4669. };
  4670. /**
  4671. * @author mrdoob / http://mrdoob.com/
  4672. * @author kile / http://kile.stravaganza.org/
  4673. * @author alteredq / http://alteredqualia.com/
  4674. * @author mikael emtinger / http://gomo.se/
  4675. * @author zz85 / http://www.lab4games.net/zz85/blog
  4676. * @author bhouston / http://exocortex.com
  4677. */
  4678. THREE.Geometry = function () {
  4679. this.id = THREE.Math.generateUUID();
  4680. this.name = '';
  4681. this.vertices = [];
  4682. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  4683. this.normals = []; // one-to-one vertex normals, used in Ribbon
  4684. this.faces = [];
  4685. this.faceUvs = [[]];
  4686. this.faceVertexUvs = [[]];
  4687. this.morphTargets = [];
  4688. this.morphColors = [];
  4689. this.morphNormals = [];
  4690. this.skinWeights = [];
  4691. this.skinIndices = [];
  4692. this.lineDistances = [];
  4693. this.boundingBox = null;
  4694. this.boundingSphere = null;
  4695. this.hasTangents = false;
  4696. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  4697. // update flags
  4698. this.verticesNeedUpdate = false;
  4699. this.elementsNeedUpdate = false;
  4700. this.uvsNeedUpdate = false;
  4701. this.normalsNeedUpdate = false;
  4702. this.tangentsNeedUpdate = false;
  4703. this.colorsNeedUpdate = false;
  4704. this.lineDistancesNeedUpdate = false;
  4705. this.buffersNeedUpdate = false;
  4706. };
  4707. THREE.Geometry.prototype = {
  4708. constructor: THREE.Geometry,
  4709. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  4710. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  4711. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  4712. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  4713. applyMatrix: function ( matrix ) {
  4714. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  4715. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  4716. var vertex = this.vertices[ i ];
  4717. vertex.applyMatrix4( matrix );
  4718. }
  4719. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  4720. var face = this.faces[ i ];
  4721. face.normal.applyMatrix3( normalMatrix ).normalize();
  4722. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  4723. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  4724. }
  4725. face.centroid.applyMatrix4( matrix );
  4726. }
  4727. if ( this.boundingBox instanceof THREE.Box3 ) {
  4728. this.computeBoundingBox();
  4729. }
  4730. if ( this.boundingSphere instanceof THREE.Sphere ) {
  4731. this.computeBoundingSphere();
  4732. }
  4733. },
  4734. computeCentroids: function () {
  4735. var f, fl, face;
  4736. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4737. face = this.faces[ f ];
  4738. face.centroid.set( 0, 0, 0 );
  4739. if ( face instanceof THREE.Face3 ) {
  4740. face.centroid.add( this.vertices[ face.a ] );
  4741. face.centroid.add( this.vertices[ face.b ] );
  4742. face.centroid.add( this.vertices[ face.c ] );
  4743. face.centroid.divideScalar( 3 );
  4744. } else if ( face instanceof THREE.Face4 ) {
  4745. face.centroid.add( this.vertices[ face.a ] );
  4746. face.centroid.add( this.vertices[ face.b ] );
  4747. face.centroid.add( this.vertices[ face.c ] );
  4748. face.centroid.add( this.vertices[ face.d ] );
  4749. face.centroid.divideScalar( 4 );
  4750. }
  4751. }
  4752. },
  4753. computeFaceNormals: function () {
  4754. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  4755. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4756. var face = this.faces[ f ];
  4757. var vA = this.vertices[ face.a ];
  4758. var vB = this.vertices[ face.b ];
  4759. var vC = this.vertices[ face.c ];
  4760. cb.subVectors( vC, vB );
  4761. ab.subVectors( vA, vB );
  4762. cb.cross( ab );
  4763. cb.normalize();
  4764. face.normal.copy( cb );
  4765. }
  4766. },
  4767. computeVertexNormals: function ( areaWeighted ) {
  4768. var v, vl, f, fl, face, vertices;
  4769. // create internal buffers for reuse when calling this method repeatedly
  4770. // (otherwise memory allocation / deallocation every frame is big resource hog)
  4771. if ( this.__tmpVertices === undefined ) {
  4772. this.__tmpVertices = new Array( this.vertices.length );
  4773. vertices = this.__tmpVertices;
  4774. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4775. vertices[ v ] = new THREE.Vector3();
  4776. }
  4777. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4778. face = this.faces[ f ];
  4779. if ( face instanceof THREE.Face3 ) {
  4780. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4781. } else if ( face instanceof THREE.Face4 ) {
  4782. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4783. }
  4784. }
  4785. } else {
  4786. vertices = this.__tmpVertices;
  4787. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4788. vertices[ v ].set( 0, 0, 0 );
  4789. }
  4790. }
  4791. if ( areaWeighted ) {
  4792. // vertex normals weighted by triangle areas
  4793. // http://www.iquilezles.org/www/articles/normals/normals.htm
  4794. var vA, vB, vC, vD;
  4795. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  4796. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  4797. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4798. face = this.faces[ f ];
  4799. if ( face instanceof THREE.Face3 ) {
  4800. vA = this.vertices[ face.a ];
  4801. vB = this.vertices[ face.b ];
  4802. vC = this.vertices[ face.c ];
  4803. cb.subVectors( vC, vB );
  4804. ab.subVectors( vA, vB );
  4805. cb.cross( ab );
  4806. vertices[ face.a ].add( cb );
  4807. vertices[ face.b ].add( cb );
  4808. vertices[ face.c ].add( cb );
  4809. } else if ( face instanceof THREE.Face4 ) {
  4810. vA = this.vertices[ face.a ];
  4811. vB = this.vertices[ face.b ];
  4812. vC = this.vertices[ face.c ];
  4813. vD = this.vertices[ face.d ];
  4814. // abd
  4815. db.subVectors( vD, vB );
  4816. ab.subVectors( vA, vB );
  4817. db.cross( ab );
  4818. vertices[ face.a ].add( db );
  4819. vertices[ face.b ].add( db );
  4820. vertices[ face.d ].add( db );
  4821. // bcd
  4822. dc.subVectors( vD, vC );
  4823. bc.subVectors( vB, vC );
  4824. dc.cross( bc );
  4825. vertices[ face.b ].add( dc );
  4826. vertices[ face.c ].add( dc );
  4827. vertices[ face.d ].add( dc );
  4828. }
  4829. }
  4830. } else {
  4831. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4832. face = this.faces[ f ];
  4833. if ( face instanceof THREE.Face3 ) {
  4834. vertices[ face.a ].add( face.normal );
  4835. vertices[ face.b ].add( face.normal );
  4836. vertices[ face.c ].add( face.normal );
  4837. } else if ( face instanceof THREE.Face4 ) {
  4838. vertices[ face.a ].add( face.normal );
  4839. vertices[ face.b ].add( face.normal );
  4840. vertices[ face.c ].add( face.normal );
  4841. vertices[ face.d ].add( face.normal );
  4842. }
  4843. }
  4844. }
  4845. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4846. vertices[ v ].normalize();
  4847. }
  4848. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4849. face = this.faces[ f ];
  4850. if ( face instanceof THREE.Face3 ) {
  4851. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4852. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4853. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4854. } else if ( face instanceof THREE.Face4 ) {
  4855. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4856. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4857. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4858. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  4859. }
  4860. }
  4861. },
  4862. computeMorphNormals: function () {
  4863. var i, il, f, fl, face;
  4864. // save original normals
  4865. // - create temp variables on first access
  4866. // otherwise just copy (for faster repeated calls)
  4867. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4868. face = this.faces[ f ];
  4869. if ( ! face.__originalFaceNormal ) {
  4870. face.__originalFaceNormal = face.normal.clone();
  4871. } else {
  4872. face.__originalFaceNormal.copy( face.normal );
  4873. }
  4874. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  4875. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  4876. if ( ! face.__originalVertexNormals[ i ] ) {
  4877. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  4878. } else {
  4879. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  4880. }
  4881. }
  4882. }
  4883. // use temp geometry to compute face and vertex normals for each morph
  4884. var tmpGeo = new THREE.Geometry();
  4885. tmpGeo.faces = this.faces;
  4886. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  4887. // create on first access
  4888. if ( ! this.morphNormals[ i ] ) {
  4889. this.morphNormals[ i ] = {};
  4890. this.morphNormals[ i ].faceNormals = [];
  4891. this.morphNormals[ i ].vertexNormals = [];
  4892. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  4893. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  4894. var faceNormal, vertexNormals;
  4895. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4896. face = this.faces[ f ];
  4897. faceNormal = new THREE.Vector3();
  4898. if ( face instanceof THREE.Face3 ) {
  4899. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  4900. } else {
  4901. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  4902. }
  4903. dstNormalsFace.push( faceNormal );
  4904. dstNormalsVertex.push( vertexNormals );
  4905. }
  4906. }
  4907. var morphNormals = this.morphNormals[ i ];
  4908. // set vertices to morph target
  4909. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  4910. // compute morph normals
  4911. tmpGeo.computeFaceNormals();
  4912. tmpGeo.computeVertexNormals();
  4913. // store morph normals
  4914. var faceNormal, vertexNormals;
  4915. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4916. face = this.faces[ f ];
  4917. faceNormal = morphNormals.faceNormals[ f ];
  4918. vertexNormals = morphNormals.vertexNormals[ f ];
  4919. faceNormal.copy( face.normal );
  4920. if ( face instanceof THREE.Face3 ) {
  4921. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4922. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4923. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4924. } else {
  4925. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4926. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4927. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4928. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  4929. }
  4930. }
  4931. }
  4932. // restore original normals
  4933. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4934. face = this.faces[ f ];
  4935. face.normal = face.__originalFaceNormal;
  4936. face.vertexNormals = face.__originalVertexNormals;
  4937. }
  4938. },
  4939. computeTangents: function () {
  4940. // based on http://www.terathon.com/code/tangent.html
  4941. // tangents go to vertices
  4942. var f, fl, v, vl, i, il, vertexIndex,
  4943. face, uv, vA, vB, vC, uvA, uvB, uvC,
  4944. x1, x2, y1, y2, z1, z2,
  4945. s1, s2, t1, t2, r, t, test,
  4946. tan1 = [], tan2 = [],
  4947. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  4948. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  4949. n = new THREE.Vector3(), w;
  4950. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4951. tan1[ v ] = new THREE.Vector3();
  4952. tan2[ v ] = new THREE.Vector3();
  4953. }
  4954. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  4955. vA = context.vertices[ a ];
  4956. vB = context.vertices[ b ];
  4957. vC = context.vertices[ c ];
  4958. uvA = uv[ ua ];
  4959. uvB = uv[ ub ];
  4960. uvC = uv[ uc ];
  4961. x1 = vB.x - vA.x;
  4962. x2 = vC.x - vA.x;
  4963. y1 = vB.y - vA.y;
  4964. y2 = vC.y - vA.y;
  4965. z1 = vB.z - vA.z;
  4966. z2 = vC.z - vA.z;
  4967. s1 = uvB.x - uvA.x;
  4968. s2 = uvC.x - uvA.x;
  4969. t1 = uvB.y - uvA.y;
  4970. t2 = uvC.y - uvA.y;
  4971. r = 1.0 / ( s1 * t2 - s2 * t1 );
  4972. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  4973. ( t2 * y1 - t1 * y2 ) * r,
  4974. ( t2 * z1 - t1 * z2 ) * r );
  4975. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  4976. ( s1 * y2 - s2 * y1 ) * r,
  4977. ( s1 * z2 - s2 * z1 ) * r );
  4978. tan1[ a ].add( sdir );
  4979. tan1[ b ].add( sdir );
  4980. tan1[ c ].add( sdir );
  4981. tan2[ a ].add( tdir );
  4982. tan2[ b ].add( tdir );
  4983. tan2[ c ].add( tdir );
  4984. }
  4985. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4986. face = this.faces[ f ];
  4987. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  4988. if ( face instanceof THREE.Face3 ) {
  4989. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  4990. } else if ( face instanceof THREE.Face4 ) {
  4991. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  4992. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  4993. }
  4994. }
  4995. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  4996. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4997. face = this.faces[ f ];
  4998. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  4999. n.copy( face.vertexNormals[ i ] );
  5000. vertexIndex = face[ faceIndex[ i ] ];
  5001. t = tan1[ vertexIndex ];
  5002. // Gram-Schmidt orthogonalize
  5003. tmp.copy( t );
  5004. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5005. // Calculate handedness
  5006. tmp2.crossVectors( face.vertexNormals[ i ], t );
  5007. test = tmp2.dot( tan2[ vertexIndex ] );
  5008. w = (test < 0.0) ? -1.0 : 1.0;
  5009. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  5010. }
  5011. }
  5012. this.hasTangents = true;
  5013. },
  5014. computeLineDistances: function ( ) {
  5015. var d = 0;
  5016. var vertices = this.vertices;
  5017. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5018. if ( i > 0 ) {
  5019. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  5020. }
  5021. this.lineDistances[ i ] = d;
  5022. }
  5023. },
  5024. computeBoundingBox: function () {
  5025. if ( this.boundingBox === null ) {
  5026. this.boundingBox = new THREE.Box3();
  5027. }
  5028. this.boundingBox.setFromPoints( this.vertices );
  5029. },
  5030. computeBoundingSphere: function () {
  5031. if ( this.boundingSphere === null ) {
  5032. this.boundingSphere = new THREE.Sphere();
  5033. }
  5034. this.boundingSphere.setFromPoints( this.vertices );
  5035. },
  5036. /*
  5037. * Checks for duplicate vertices with hashmap.
  5038. * Duplicated vertices are removed
  5039. * and faces' vertices are updated.
  5040. */
  5041. mergeVertices: function () {
  5042. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  5043. var unique = [], changes = [];
  5044. var v, key;
  5045. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  5046. var precision = Math.pow( 10, precisionPoints );
  5047. var i,il, face;
  5048. var indices, k, j, jl, u;
  5049. // reset cache of vertices as it now will be changing.
  5050. this.__tmpVertices = undefined;
  5051. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  5052. v = this.vertices[ i ];
  5053. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  5054. if ( verticesMap[ key ] === undefined ) {
  5055. verticesMap[ key ] = i;
  5056. unique.push( this.vertices[ i ] );
  5057. changes[ i ] = unique.length - 1;
  5058. } else {
  5059. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  5060. changes[ i ] = changes[ verticesMap[ key ] ];
  5061. }
  5062. };
  5063. // if faces are completely degenerate after merging vertices, we
  5064. // have to remove them from the geometry.
  5065. var faceIndicesToRemove = [];
  5066. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  5067. face = this.faces[ i ];
  5068. if ( face instanceof THREE.Face3 ) {
  5069. face.a = changes[ face.a ];
  5070. face.b = changes[ face.b ];
  5071. face.c = changes[ face.c ];
  5072. indices = [ face.a, face.b, face.c ];
  5073. var dupIndex = -1;
  5074. // if any duplicate vertices are found in a Face3
  5075. // we have to remove the face as nothing can be saved
  5076. for ( var n = 0; n < 3; n ++ ) {
  5077. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  5078. dupIndex = n;
  5079. faceIndicesToRemove.push( i );
  5080. break;
  5081. }
  5082. }
  5083. } else if ( face instanceof THREE.Face4 ) {
  5084. face.a = changes[ face.a ];
  5085. face.b = changes[ face.b ];
  5086. face.c = changes[ face.c ];
  5087. face.d = changes[ face.d ];
  5088. // check dups in (a, b, c, d) and convert to -> face3
  5089. indices = [ face.a, face.b, face.c, face.d ];
  5090. var dupIndex = -1;
  5091. for ( var n = 0; n < 4; n ++ ) {
  5092. if ( indices[ n ] == indices[ ( n + 1 ) % 4 ] ) {
  5093. // if more than one duplicated vertex is found
  5094. // we can't generate any valid Face3's, thus
  5095. // we need to remove this face complete.
  5096. if ( dupIndex >= 0 ) {
  5097. faceIndicesToRemove.push( i );
  5098. }
  5099. dupIndex = n;
  5100. }
  5101. }
  5102. if ( dupIndex >= 0 ) {
  5103. indices.splice( dupIndex, 1 );
  5104. var newFace = new THREE.Face3( indices[0], indices[1], indices[2], face.normal, face.color, face.materialIndex );
  5105. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  5106. u = this.faceVertexUvs[ j ][ i ];
  5107. if ( u ) {
  5108. u.splice( dupIndex, 1 );
  5109. }
  5110. }
  5111. if( face.vertexNormals && face.vertexNormals.length > 0) {
  5112. newFace.vertexNormals = face.vertexNormals;
  5113. newFace.vertexNormals.splice( dupIndex, 1 );
  5114. }
  5115. if( face.vertexColors && face.vertexColors.length > 0 ) {
  5116. newFace.vertexColors = face.vertexColors;
  5117. newFace.vertexColors.splice( dupIndex, 1 );
  5118. }
  5119. this.faces[ i ] = newFace;
  5120. }
  5121. }
  5122. }
  5123. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  5124. this.faces.splice( i, 1 );
  5125. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  5126. this.faceVertexUvs[ j ].splice( i, 1 );
  5127. }
  5128. }
  5129. // Use unique set of vertices
  5130. var diff = this.vertices.length - unique.length;
  5131. this.vertices = unique;
  5132. return diff;
  5133. },
  5134. clone: function () {
  5135. var geometry = new THREE.Geometry();
  5136. var vertices = this.vertices;
  5137. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5138. geometry.vertices.push( vertices[ i ].clone() );
  5139. }
  5140. var faces = this.faces;
  5141. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  5142. geometry.faces.push( faces[ i ].clone() );
  5143. }
  5144. var uvs = this.faceVertexUvs[ 0 ];
  5145. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  5146. var uv = uvs[ i ], uvCopy = [];
  5147. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  5148. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  5149. }
  5150. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  5151. }
  5152. return geometry;
  5153. },
  5154. dispose: function () {
  5155. this.dispatchEvent( { type: 'dispose' } );
  5156. }
  5157. };
  5158. /**
  5159. * @author alteredq / http://alteredqualia.com/
  5160. */
  5161. THREE.BufferGeometry = function () {
  5162. this.id = THREE.Math.generateUUID();
  5163. // attributes
  5164. this.attributes = {};
  5165. // attributes typed arrays are kept only if dynamic flag is set
  5166. this.dynamic = false;
  5167. // offsets for chunks when using indexed elements
  5168. this.offsets = [];
  5169. // boundings
  5170. this.boundingBox = null;
  5171. this.boundingSphere = null;
  5172. this.hasTangents = false;
  5173. // for compatibility
  5174. this.morphTargets = [];
  5175. };
  5176. THREE.BufferGeometry.prototype = {
  5177. constructor: THREE.BufferGeometry,
  5178. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  5179. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  5180. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  5181. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  5182. applyMatrix: function ( matrix ) {
  5183. var positionArray;
  5184. var normalArray;
  5185. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  5186. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  5187. if ( positionArray !== undefined ) {
  5188. matrix.multiplyVector3Array( positionArray );
  5189. this.verticesNeedUpdate = true;
  5190. }
  5191. if ( normalArray !== undefined ) {
  5192. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5193. normalMatrix.multiplyVector3Array( normalArray );
  5194. this.normalizeNormals();
  5195. this.normalsNeedUpdate = true;
  5196. }
  5197. },
  5198. computeBoundingBox: function () {
  5199. if ( this.boundingBox === null ) {
  5200. this.boundingBox = new THREE.Box3();
  5201. }
  5202. var positions = this.attributes[ "position" ].array;
  5203. if ( positions ) {
  5204. var bb = this.boundingBox;
  5205. var x, y, z;
  5206. if( positions.length >= 3 ) {
  5207. bb.min.x = bb.max.x = positions[ 0 ];
  5208. bb.min.y = bb.max.y = positions[ 1 ];
  5209. bb.min.z = bb.max.z = positions[ 2 ];
  5210. }
  5211. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  5212. x = positions[ i ];
  5213. y = positions[ i + 1 ];
  5214. z = positions[ i + 2 ];
  5215. // bounding box
  5216. if ( x < bb.min.x ) {
  5217. bb.min.x = x;
  5218. } else if ( x > bb.max.x ) {
  5219. bb.max.x = x;
  5220. }
  5221. if ( y < bb.min.y ) {
  5222. bb.min.y = y;
  5223. } else if ( y > bb.max.y ) {
  5224. bb.max.y = y;
  5225. }
  5226. if ( z < bb.min.z ) {
  5227. bb.min.z = z;
  5228. } else if ( z > bb.max.z ) {
  5229. bb.max.z = z;
  5230. }
  5231. }
  5232. }
  5233. if ( positions === undefined || positions.length === 0 ) {
  5234. this.boundingBox.min.set( 0, 0, 0 );
  5235. this.boundingBox.max.set( 0, 0, 0 );
  5236. }
  5237. },
  5238. computeBoundingSphere: function () {
  5239. if ( this.boundingSphere === null ) {
  5240. this.boundingSphere = new THREE.Sphere();
  5241. }
  5242. var positions = this.attributes[ "position" ].array;
  5243. if ( positions ) {
  5244. var radiusSq, maxRadiusSq = 0;
  5245. var x, y, z;
  5246. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5247. x = positions[ i ];
  5248. y = positions[ i + 1 ];
  5249. z = positions[ i + 2 ];
  5250. radiusSq = x * x + y * y + z * z;
  5251. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  5252. }
  5253. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5254. }
  5255. },
  5256. computeVertexNormals: function () {
  5257. if ( this.attributes[ "position" ] ) {
  5258. var i, il;
  5259. var j, jl;
  5260. var nVertexElements = this.attributes[ "position" ].array.length;
  5261. if ( this.attributes[ "normal" ] === undefined ) {
  5262. this.attributes[ "normal" ] = {
  5263. itemSize: 3,
  5264. array: new Float32Array( nVertexElements )
  5265. };
  5266. } else {
  5267. // reset existing normals to zero
  5268. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  5269. this.attributes[ "normal" ].array[ i ] = 0;
  5270. }
  5271. }
  5272. var positions = this.attributes[ "position" ].array;
  5273. var normals = this.attributes[ "normal" ].array;
  5274. var vA, vB, vC, x, y, z,
  5275. pA = new THREE.Vector3(),
  5276. pB = new THREE.Vector3(),
  5277. pC = new THREE.Vector3(),
  5278. cb = new THREE.Vector3(),
  5279. ab = new THREE.Vector3();
  5280. // indexed elements
  5281. if ( this.attributes[ "index" ] ) {
  5282. var indices = this.attributes[ "index" ].array;
  5283. var offsets = this.offsets;
  5284. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5285. var start = offsets[ j ].start;
  5286. var count = offsets[ j ].count;
  5287. var index = offsets[ j ].index;
  5288. for ( i = start, il = start + count; i < il; i += 3 ) {
  5289. vA = index + indices[ i ];
  5290. vB = index + indices[ i + 1 ];
  5291. vC = index + indices[ i + 2 ];
  5292. x = positions[ vA * 3 ];
  5293. y = positions[ vA * 3 + 1 ];
  5294. z = positions[ vA * 3 + 2 ];
  5295. pA.set( x, y, z );
  5296. x = positions[ vB * 3 ];
  5297. y = positions[ vB * 3 + 1 ];
  5298. z = positions[ vB * 3 + 2 ];
  5299. pB.set( x, y, z );
  5300. x = positions[ vC * 3 ];
  5301. y = positions[ vC * 3 + 1 ];
  5302. z = positions[ vC * 3 + 2 ];
  5303. pC.set( x, y, z );
  5304. cb.subVectors( pC, pB );
  5305. ab.subVectors( pA, pB );
  5306. cb.cross( ab );
  5307. normals[ vA * 3 ] += cb.x;
  5308. normals[ vA * 3 + 1 ] += cb.y;
  5309. normals[ vA * 3 + 2 ] += cb.z;
  5310. normals[ vB * 3 ] += cb.x;
  5311. normals[ vB * 3 + 1 ] += cb.y;
  5312. normals[ vB * 3 + 2 ] += cb.z;
  5313. normals[ vC * 3 ] += cb.x;
  5314. normals[ vC * 3 + 1 ] += cb.y;
  5315. normals[ vC * 3 + 2 ] += cb.z;
  5316. }
  5317. }
  5318. // non-indexed elements (unconnected triangle soup)
  5319. } else {
  5320. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  5321. x = positions[ i ];
  5322. y = positions[ i + 1 ];
  5323. z = positions[ i + 2 ];
  5324. pA.set( x, y, z );
  5325. x = positions[ i + 3 ];
  5326. y = positions[ i + 4 ];
  5327. z = positions[ i + 5 ];
  5328. pB.set( x, y, z );
  5329. x = positions[ i + 6 ];
  5330. y = positions[ i + 7 ];
  5331. z = positions[ i + 8 ];
  5332. pC.set( x, y, z );
  5333. cb.subVectors( pC, pB );
  5334. ab.subVectors( pA, pB );
  5335. cb.cross( ab );
  5336. normals[ i ] = cb.x;
  5337. normals[ i + 1 ] = cb.y;
  5338. normals[ i + 2 ] = cb.z;
  5339. normals[ i + 3 ] = cb.x;
  5340. normals[ i + 4 ] = cb.y;
  5341. normals[ i + 5 ] = cb.z;
  5342. normals[ i + 6 ] = cb.x;
  5343. normals[ i + 7 ] = cb.y;
  5344. normals[ i + 8 ] = cb.z;
  5345. }
  5346. }
  5347. this.normalizeNormals();
  5348. this.normalsNeedUpdate = true;
  5349. }
  5350. },
  5351. normalizeNormals: function () {
  5352. var normals = this.attributes[ "normal" ].array;
  5353. var x, y, z, n;
  5354. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5355. x = normals[ i ];
  5356. y = normals[ i + 1 ];
  5357. z = normals[ i + 2 ];
  5358. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5359. normals[ i ] *= n;
  5360. normals[ i + 1 ] *= n;
  5361. normals[ i + 2 ] *= n;
  5362. }
  5363. },
  5364. computeTangents: function () {
  5365. // based on http://www.terathon.com/code/tangent.html
  5366. // (per vertex tangents)
  5367. if ( this.attributes[ "index" ] === undefined ||
  5368. this.attributes[ "position" ] === undefined ||
  5369. this.attributes[ "normal" ] === undefined ||
  5370. this.attributes[ "uv" ] === undefined ) {
  5371. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  5372. return;
  5373. }
  5374. var indices = this.attributes[ "index" ].array;
  5375. var positions = this.attributes[ "position" ].array;
  5376. var normals = this.attributes[ "normal" ].array;
  5377. var uvs = this.attributes[ "uv" ].array;
  5378. var nVertices = positions.length / 3;
  5379. if ( this.attributes[ "tangent" ] === undefined ) {
  5380. var nTangentElements = 4 * nVertices;
  5381. this.attributes[ "tangent" ] = {
  5382. itemSize: 4,
  5383. array: new Float32Array( nTangentElements )
  5384. };
  5385. }
  5386. var tangents = this.attributes[ "tangent" ].array;
  5387. var tan1 = [], tan2 = [];
  5388. for ( var k = 0; k < nVertices; k ++ ) {
  5389. tan1[ k ] = new THREE.Vector3();
  5390. tan2[ k ] = new THREE.Vector3();
  5391. }
  5392. var xA, yA, zA,
  5393. xB, yB, zB,
  5394. xC, yC, zC,
  5395. uA, vA,
  5396. uB, vB,
  5397. uC, vC,
  5398. x1, x2, y1, y2, z1, z2,
  5399. s1, s2, t1, t2, r;
  5400. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5401. function handleTriangle( a, b, c ) {
  5402. xA = positions[ a * 3 ];
  5403. yA = positions[ a * 3 + 1 ];
  5404. zA = positions[ a * 3 + 2 ];
  5405. xB = positions[ b * 3 ];
  5406. yB = positions[ b * 3 + 1 ];
  5407. zB = positions[ b * 3 + 2 ];
  5408. xC = positions[ c * 3 ];
  5409. yC = positions[ c * 3 + 1 ];
  5410. zC = positions[ c * 3 + 2 ];
  5411. uA = uvs[ a * 2 ];
  5412. vA = uvs[ a * 2 + 1 ];
  5413. uB = uvs[ b * 2 ];
  5414. vB = uvs[ b * 2 + 1 ];
  5415. uC = uvs[ c * 2 ];
  5416. vC = uvs[ c * 2 + 1 ];
  5417. x1 = xB - xA;
  5418. x2 = xC - xA;
  5419. y1 = yB - yA;
  5420. y2 = yC - yA;
  5421. z1 = zB - zA;
  5422. z2 = zC - zA;
  5423. s1 = uB - uA;
  5424. s2 = uC - uA;
  5425. t1 = vB - vA;
  5426. t2 = vC - vA;
  5427. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5428. sdir.set(
  5429. ( t2 * x1 - t1 * x2 ) * r,
  5430. ( t2 * y1 - t1 * y2 ) * r,
  5431. ( t2 * z1 - t1 * z2 ) * r
  5432. );
  5433. tdir.set(
  5434. ( s1 * x2 - s2 * x1 ) * r,
  5435. ( s1 * y2 - s2 * y1 ) * r,
  5436. ( s1 * z2 - s2 * z1 ) * r
  5437. );
  5438. tan1[ a ].add( sdir );
  5439. tan1[ b ].add( sdir );
  5440. tan1[ c ].add( sdir );
  5441. tan2[ a ].add( tdir );
  5442. tan2[ b ].add( tdir );
  5443. tan2[ c ].add( tdir );
  5444. }
  5445. var i, il;
  5446. var j, jl;
  5447. var iA, iB, iC;
  5448. var offsets = this.offsets;
  5449. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5450. var start = offsets[ j ].start;
  5451. var count = offsets[ j ].count;
  5452. var index = offsets[ j ].index;
  5453. for ( i = start, il = start + count; i < il; i += 3 ) {
  5454. iA = index + indices[ i ];
  5455. iB = index + indices[ i + 1 ];
  5456. iC = index + indices[ i + 2 ];
  5457. handleTriangle( iA, iB, iC );
  5458. }
  5459. }
  5460. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5461. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5462. var w, t, test;
  5463. function handleVertex( v ) {
  5464. n.x = normals[ v * 3 ];
  5465. n.y = normals[ v * 3 + 1 ];
  5466. n.z = normals[ v * 3 + 2 ];
  5467. n2.copy( n );
  5468. t = tan1[ v ];
  5469. // Gram-Schmidt orthogonalize
  5470. tmp.copy( t );
  5471. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5472. // Calculate handedness
  5473. tmp2.crossVectors( n2, t );
  5474. test = tmp2.dot( tan2[ v ] );
  5475. w = ( test < 0.0 ) ? -1.0 : 1.0;
  5476. tangents[ v * 4 ] = tmp.x;
  5477. tangents[ v * 4 + 1 ] = tmp.y;
  5478. tangents[ v * 4 + 2 ] = tmp.z;
  5479. tangents[ v * 4 + 3 ] = w;
  5480. }
  5481. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5482. var start = offsets[ j ].start;
  5483. var count = offsets[ j ].count;
  5484. var index = offsets[ j ].index;
  5485. for ( i = start, il = start + count; i < il; i += 3 ) {
  5486. iA = index + indices[ i ];
  5487. iB = index + indices[ i + 1 ];
  5488. iC = index + indices[ i + 2 ];
  5489. handleVertex( iA );
  5490. handleVertex( iB );
  5491. handleVertex( iC );
  5492. }
  5493. }
  5494. this.hasTangents = true;
  5495. this.tangentsNeedUpdate = true;
  5496. },
  5497. dispose: function () {
  5498. this.dispatchEvent( { type: 'dispose' } );
  5499. }
  5500. };
  5501. /**
  5502. * @author mrdoob / http://mrdoob.com/
  5503. * @author mikael emtinger / http://gomo.se/
  5504. * @author WestLangley / http://github.com/WestLangley
  5505. */
  5506. THREE.Camera = function () {
  5507. THREE.Object3D.call( this );
  5508. this.matrixWorldInverse = new THREE.Matrix4();
  5509. this.projectionMatrix = new THREE.Matrix4();
  5510. this.projectionMatrixInverse = new THREE.Matrix4();
  5511. };
  5512. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  5513. THREE.Camera.prototype.lookAt = function () {
  5514. // This routine does not support cameras with rotated and/or translated parent(s)
  5515. var m1 = new THREE.Matrix4();
  5516. return function ( vector ) {
  5517. m1.lookAt( this.position, vector, this.up );
  5518. this.quaternion.setFromRotationMatrix( m1 );
  5519. };
  5520. }();
  5521. /**
  5522. * @author alteredq / http://alteredqualia.com/
  5523. */
  5524. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  5525. THREE.Camera.call( this );
  5526. this.left = left;
  5527. this.right = right;
  5528. this.top = top;
  5529. this.bottom = bottom;
  5530. this.near = ( near !== undefined ) ? near : 0.1;
  5531. this.far = ( far !== undefined ) ? far : 2000;
  5532. this.updateProjectionMatrix();
  5533. };
  5534. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  5535. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  5536. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  5537. };
  5538. /**
  5539. * @author mrdoob / http://mrdoob.com/
  5540. * @author greggman / http://games.greggman.com/
  5541. * @author zz85 / http://www.lab4games.net/zz85/blog
  5542. */
  5543. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  5544. THREE.Camera.call( this );
  5545. this.fov = fov !== undefined ? fov : 50;
  5546. this.aspect = aspect !== undefined ? aspect : 1;
  5547. this.near = near !== undefined ? near : 0.1;
  5548. this.far = far !== undefined ? far : 2000;
  5549. this.updateProjectionMatrix();
  5550. };
  5551. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  5552. /**
  5553. * Uses Focal Length (in mm) to estimate and set FOV
  5554. * 35mm (fullframe) camera is used if frame size is not specified;
  5555. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  5556. */
  5557. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  5558. if ( frameHeight === undefined ) frameHeight = 24;
  5559. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  5560. this.updateProjectionMatrix();
  5561. }
  5562. /**
  5563. * Sets an offset in a larger frustum. This is useful for multi-window or
  5564. * multi-monitor/multi-machine setups.
  5565. *
  5566. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  5567. * the monitors are in grid like this
  5568. *
  5569. * +---+---+---+
  5570. * | A | B | C |
  5571. * +---+---+---+
  5572. * | D | E | F |
  5573. * +---+---+---+
  5574. *
  5575. * then for each monitor you would call it like this
  5576. *
  5577. * var w = 1920;
  5578. * var h = 1080;
  5579. * var fullWidth = w * 3;
  5580. * var fullHeight = h * 2;
  5581. *
  5582. * --A--
  5583. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  5584. * --B--
  5585. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  5586. * --C--
  5587. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  5588. * --D--
  5589. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  5590. * --E--
  5591. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  5592. * --F--
  5593. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  5594. *
  5595. * Note there is no reason monitors have to be the same size or in a grid.
  5596. */
  5597. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  5598. this.fullWidth = fullWidth;
  5599. this.fullHeight = fullHeight;
  5600. this.x = x;
  5601. this.y = y;
  5602. this.width = width;
  5603. this.height = height;
  5604. this.updateProjectionMatrix();
  5605. };
  5606. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  5607. if ( this.fullWidth ) {
  5608. var aspect = this.fullWidth / this.fullHeight;
  5609. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  5610. var bottom = -top;
  5611. var left = aspect * bottom;
  5612. var right = aspect * top;
  5613. var width = Math.abs( right - left );
  5614. var height = Math.abs( top - bottom );
  5615. this.projectionMatrix.makeFrustum(
  5616. left + this.x * width / this.fullWidth,
  5617. left + ( this.x + this.width ) * width / this.fullWidth,
  5618. top - ( this.y + this.height ) * height / this.fullHeight,
  5619. top - this.y * height / this.fullHeight,
  5620. this.near,
  5621. this.far
  5622. );
  5623. } else {
  5624. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  5625. }
  5626. };
  5627. /**
  5628. * @author mrdoob / http://mrdoob.com/
  5629. * @author alteredq / http://alteredqualia.com/
  5630. */
  5631. THREE.Light = function ( hex ) {
  5632. THREE.Object3D.call( this );
  5633. this.color = new THREE.Color( hex );
  5634. };
  5635. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  5636. THREE.Light.prototype.clone = function ( light ) {
  5637. if ( light === undefined ) light = new THREE.Light();
  5638. THREE.Object3D.prototype.clone.call( this, light );
  5639. light.color.copy( this.color );
  5640. return light;
  5641. };
  5642. /**
  5643. * @author mrdoob / http://mrdoob.com/
  5644. */
  5645. THREE.AmbientLight = function ( hex ) {
  5646. THREE.Light.call( this, hex );
  5647. };
  5648. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  5649. THREE.AmbientLight.prototype.clone = function () {
  5650. var light = new THREE.AmbientLight();
  5651. THREE.Light.prototype.clone.call( this, light );
  5652. return light;
  5653. };
  5654. /**
  5655. * @author MPanknin / http://www.redplant.de/
  5656. * @author alteredq / http://alteredqualia.com/
  5657. */
  5658. THREE.AreaLight = function ( hex, intensity ) {
  5659. THREE.Light.call( this, hex );
  5660. this.normal = new THREE.Vector3( 0, -1, 0 );
  5661. this.right = new THREE.Vector3( 1, 0, 0 );
  5662. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5663. this.width = 1.0;
  5664. this.height = 1.0;
  5665. this.constantAttenuation = 1.5;
  5666. this.linearAttenuation = 0.5;
  5667. this.quadraticAttenuation = 0.1;
  5668. };
  5669. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  5670. /**
  5671. * @author mrdoob / http://mrdoob.com/
  5672. * @author alteredq / http://alteredqualia.com/
  5673. */
  5674. THREE.DirectionalLight = function ( hex, intensity ) {
  5675. THREE.Light.call( this, hex );
  5676. this.position.set( 0, 1, 0 );
  5677. this.target = new THREE.Object3D();
  5678. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5679. this.castShadow = false;
  5680. this.onlyShadow = false;
  5681. //
  5682. this.shadowCameraNear = 50;
  5683. this.shadowCameraFar = 5000;
  5684. this.shadowCameraLeft = -500;
  5685. this.shadowCameraRight = 500;
  5686. this.shadowCameraTop = 500;
  5687. this.shadowCameraBottom = -500;
  5688. this.shadowCameraVisible = false;
  5689. this.shadowBias = 0;
  5690. this.shadowDarkness = 0.5;
  5691. this.shadowMapWidth = 512;
  5692. this.shadowMapHeight = 512;
  5693. //
  5694. this.shadowCascade = false;
  5695. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  5696. this.shadowCascadeCount = 2;
  5697. this.shadowCascadeBias = [ 0, 0, 0 ];
  5698. this.shadowCascadeWidth = [ 512, 512, 512 ];
  5699. this.shadowCascadeHeight = [ 512, 512, 512 ];
  5700. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  5701. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  5702. this.shadowCascadeArray = [];
  5703. //
  5704. this.shadowMap = null;
  5705. this.shadowMapSize = null;
  5706. this.shadowCamera = null;
  5707. this.shadowMatrix = null;
  5708. };
  5709. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  5710. THREE.DirectionalLight.prototype.clone = function () {
  5711. var light = new THREE.DirectionalLight();
  5712. THREE.Light.prototype.clone.call( this, light );
  5713. light.target = this.target.clone();
  5714. light.intensity = this.intensity;
  5715. light.castShadow = this.castShadow;
  5716. light.onlyShadow = this.onlyShadow;
  5717. return light;
  5718. };
  5719. /**
  5720. * @author alteredq / http://alteredqualia.com/
  5721. */
  5722. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  5723. THREE.Light.call( this, skyColorHex );
  5724. this.position.set( 0, 100, 0 );
  5725. this.groundColor = new THREE.Color( groundColorHex );
  5726. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5727. };
  5728. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  5729. THREE.HemisphereLight.prototype.clone = function () {
  5730. var light = new THREE.PointLight();
  5731. THREE.Light.prototype.clone.call( this, light );
  5732. light.groundColor.copy( this.groundColor );
  5733. light.intensity = this.intensity;
  5734. return light;
  5735. };
  5736. /**
  5737. * @author mrdoob / http://mrdoob.com/
  5738. */
  5739. THREE.PointLight = function ( hex, intensity, distance ) {
  5740. THREE.Light.call( this, hex );
  5741. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5742. this.distance = ( distance !== undefined ) ? distance : 0;
  5743. };
  5744. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  5745. THREE.PointLight.prototype.clone = function () {
  5746. var light = new THREE.PointLight();
  5747. THREE.Light.prototype.clone.call( this, light );
  5748. light.intensity = this.intensity;
  5749. light.distance = this.distance;
  5750. return light;
  5751. };
  5752. /**
  5753. * @author alteredq / http://alteredqualia.com/
  5754. */
  5755. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  5756. THREE.Light.call( this, hex );
  5757. this.position.set( 0, 1, 0 );
  5758. this.target = new THREE.Object3D();
  5759. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5760. this.distance = ( distance !== undefined ) ? distance : 0;
  5761. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  5762. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  5763. this.castShadow = false;
  5764. this.onlyShadow = false;
  5765. //
  5766. this.shadowCameraNear = 50;
  5767. this.shadowCameraFar = 5000;
  5768. this.shadowCameraFov = 50;
  5769. this.shadowCameraVisible = false;
  5770. this.shadowBias = 0;
  5771. this.shadowDarkness = 0.5;
  5772. this.shadowMapWidth = 512;
  5773. this.shadowMapHeight = 512;
  5774. //
  5775. this.shadowMap = null;
  5776. this.shadowMapSize = null;
  5777. this.shadowCamera = null;
  5778. this.shadowMatrix = null;
  5779. };
  5780. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  5781. THREE.SpotLight.prototype.clone = function () {
  5782. var light = new THREE.SpotLight();
  5783. THREE.Light.prototype.clone.call( this, light );
  5784. light.target = this.target.clone();
  5785. light.intensity = this.intensity;
  5786. light.distance = this.distance;
  5787. light.angle = this.angle;
  5788. light.exponent = this.exponent;
  5789. light.castShadow = this.castShadow;
  5790. light.onlyShadow = this.onlyShadow;
  5791. return light;
  5792. };
  5793. /**
  5794. * @author alteredq / http://alteredqualia.com/
  5795. */
  5796. THREE.Loader = function ( showStatus ) {
  5797. this.showStatus = showStatus;
  5798. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  5799. this.onLoadStart = function () {};
  5800. this.onLoadProgress = function () {};
  5801. this.onLoadComplete = function () {};
  5802. };
  5803. THREE.Loader.prototype = {
  5804. constructor: THREE.Loader,
  5805. crossOrigin: 'anonymous',
  5806. addStatusElement: function () {
  5807. var e = document.createElement( "div" );
  5808. e.style.position = "absolute";
  5809. e.style.right = "0px";
  5810. e.style.top = "0px";
  5811. e.style.fontSize = "0.8em";
  5812. e.style.textAlign = "left";
  5813. e.style.background = "rgba(0,0,0,0.25)";
  5814. e.style.color = "#fff";
  5815. e.style.width = "120px";
  5816. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  5817. e.style.zIndex = 1000;
  5818. e.innerHTML = "Loading ...";
  5819. return e;
  5820. },
  5821. updateProgress: function ( progress ) {
  5822. var message = "Loaded ";
  5823. if ( progress.total ) {
  5824. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  5825. } else {
  5826. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  5827. }
  5828. this.statusDomElement.innerHTML = message;
  5829. },
  5830. extractUrlBase: function ( url ) {
  5831. var parts = url.split( '/' );
  5832. parts.pop();
  5833. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  5834. },
  5835. initMaterials: function ( materials, texturePath ) {
  5836. var array = [];
  5837. for ( var i = 0; i < materials.length; ++ i ) {
  5838. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  5839. }
  5840. return array;
  5841. },
  5842. needsTangents: function ( materials ) {
  5843. for( var i = 0, il = materials.length; i < il; i ++ ) {
  5844. var m = materials[ i ];
  5845. if ( m instanceof THREE.ShaderMaterial ) return true;
  5846. }
  5847. return false;
  5848. },
  5849. createMaterial: function ( m, texturePath ) {
  5850. var _this = this;
  5851. function is_pow2( n ) {
  5852. var l = Math.log( n ) / Math.LN2;
  5853. return Math.floor( l ) == l;
  5854. }
  5855. function nearest_pow2( n ) {
  5856. var l = Math.log( n ) / Math.LN2;
  5857. return Math.pow( 2, Math.round( l ) );
  5858. }
  5859. function load_image( where, url ) {
  5860. var image = new Image();
  5861. image.onload = function () {
  5862. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  5863. var width = nearest_pow2( this.width );
  5864. var height = nearest_pow2( this.height );
  5865. where.image.width = width;
  5866. where.image.height = height;
  5867. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  5868. } else {
  5869. where.image = this;
  5870. }
  5871. where.needsUpdate = true;
  5872. };
  5873. image.crossOrigin = _this.crossOrigin;
  5874. image.src = url;
  5875. }
  5876. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  5877. var isCompressed = /\.dds$/i.test( sourceFile );
  5878. var fullPath = texturePath + "/" + sourceFile;
  5879. if ( isCompressed ) {
  5880. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  5881. where[ name ] = texture;
  5882. } else {
  5883. var texture = document.createElement( 'canvas' );
  5884. where[ name ] = new THREE.Texture( texture );
  5885. }
  5886. where[ name ].sourceFile = sourceFile;
  5887. if( repeat ) {
  5888. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  5889. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  5890. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  5891. }
  5892. if ( offset ) {
  5893. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  5894. }
  5895. if ( wrap ) {
  5896. var wrapMap = {
  5897. "repeat": THREE.RepeatWrapping,
  5898. "mirror": THREE.MirroredRepeatWrapping
  5899. }
  5900. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  5901. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  5902. }
  5903. if ( anisotropy ) {
  5904. where[ name ].anisotropy = anisotropy;
  5905. }
  5906. if ( ! isCompressed ) {
  5907. load_image( where[ name ], fullPath );
  5908. }
  5909. }
  5910. function rgb2hex( rgb ) {
  5911. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  5912. }
  5913. // defaults
  5914. var mtype = "MeshLambertMaterial";
  5915. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  5916. // parameters from model file
  5917. if ( m.shading ) {
  5918. var shading = m.shading.toLowerCase();
  5919. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  5920. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  5921. }
  5922. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  5923. mpars.blending = THREE[ m.blending ];
  5924. }
  5925. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  5926. mpars.transparent = m.transparent;
  5927. }
  5928. if ( m.depthTest !== undefined ) {
  5929. mpars.depthTest = m.depthTest;
  5930. }
  5931. if ( m.depthWrite !== undefined ) {
  5932. mpars.depthWrite = m.depthWrite;
  5933. }
  5934. if ( m.visible !== undefined ) {
  5935. mpars.visible = m.visible;
  5936. }
  5937. if ( m.flipSided !== undefined ) {
  5938. mpars.side = THREE.BackSide;
  5939. }
  5940. if ( m.doubleSided !== undefined ) {
  5941. mpars.side = THREE.DoubleSide;
  5942. }
  5943. if ( m.wireframe !== undefined ) {
  5944. mpars.wireframe = m.wireframe;
  5945. }
  5946. if ( m.vertexColors !== undefined ) {
  5947. if ( m.vertexColors === "face" ) {
  5948. mpars.vertexColors = THREE.FaceColors;
  5949. } else if ( m.vertexColors ) {
  5950. mpars.vertexColors = THREE.VertexColors;
  5951. }
  5952. }
  5953. // colors
  5954. if ( m.colorDiffuse ) {
  5955. mpars.color = rgb2hex( m.colorDiffuse );
  5956. } else if ( m.DbgColor ) {
  5957. mpars.color = m.DbgColor;
  5958. }
  5959. if ( m.colorSpecular ) {
  5960. mpars.specular = rgb2hex( m.colorSpecular );
  5961. }
  5962. if ( m.colorAmbient ) {
  5963. mpars.ambient = rgb2hex( m.colorAmbient );
  5964. }
  5965. // modifiers
  5966. if ( m.transparency ) {
  5967. mpars.opacity = m.transparency;
  5968. }
  5969. if ( m.specularCoef ) {
  5970. mpars.shininess = m.specularCoef;
  5971. }
  5972. // textures
  5973. if ( m.mapDiffuse && texturePath ) {
  5974. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  5975. }
  5976. if ( m.mapLight && texturePath ) {
  5977. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  5978. }
  5979. if ( m.mapBump && texturePath ) {
  5980. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  5981. }
  5982. if ( m.mapNormal && texturePath ) {
  5983. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  5984. }
  5985. if ( m.mapSpecular && texturePath ) {
  5986. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  5987. }
  5988. //
  5989. if ( m.mapBumpScale ) {
  5990. mpars.bumpScale = m.mapBumpScale;
  5991. }
  5992. // special case for normal mapped material
  5993. if ( m.mapNormal ) {
  5994. var shader = THREE.ShaderLib[ "normalmap" ];
  5995. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5996. uniforms[ "tNormal" ].value = mpars.normalMap;
  5997. if ( m.mapNormalFactor ) {
  5998. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  5999. }
  6000. if ( mpars.map ) {
  6001. uniforms[ "tDiffuse" ].value = mpars.map;
  6002. uniforms[ "enableDiffuse" ].value = true;
  6003. }
  6004. if ( mpars.specularMap ) {
  6005. uniforms[ "tSpecular" ].value = mpars.specularMap;
  6006. uniforms[ "enableSpecular" ].value = true;
  6007. }
  6008. if ( mpars.lightMap ) {
  6009. uniforms[ "tAO" ].value = mpars.lightMap;
  6010. uniforms[ "enableAO" ].value = true;
  6011. }
  6012. // for the moment don't handle displacement texture
  6013. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  6014. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  6015. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  6016. uniforms[ "uShininess" ].value = mpars.shininess;
  6017. if ( mpars.opacity !== undefined ) {
  6018. uniforms[ "uOpacity" ].value = mpars.opacity;
  6019. }
  6020. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6021. var material = new THREE.ShaderMaterial( parameters );
  6022. if ( mpars.transparent ) {
  6023. material.transparent = true;
  6024. }
  6025. } else {
  6026. var material = new THREE[ mtype ]( mpars );
  6027. }
  6028. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  6029. return material;
  6030. }
  6031. };
  6032. /**
  6033. * @author mrdoob / http://mrdoob.com/
  6034. */
  6035. THREE.XHRLoader = function ( manager ) {
  6036. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6037. };
  6038. THREE.XHRLoader.prototype = {
  6039. constructor: THREE.XHRLoader,
  6040. load: function ( url, onLoad, onProgress, onError ) {
  6041. var scope = this;
  6042. var request = new XMLHttpRequest();
  6043. if ( onLoad !== undefined ) {
  6044. request.addEventListener( 'load', function ( event ) {
  6045. scope.manager.itemEnd( url );
  6046. onLoad( event.target.responseText );
  6047. }, false );
  6048. }
  6049. if ( onProgress !== undefined ) {
  6050. request.addEventListener( 'progress', function ( event ) {
  6051. onProgress( event );
  6052. }, false );
  6053. }
  6054. if ( onError !== undefined ) {
  6055. request.addEventListener( 'error', function ( event ) {
  6056. onError( event );
  6057. }, false );
  6058. }
  6059. if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
  6060. request.open( 'GET', url, true );
  6061. request.send( null );
  6062. scope.manager.itemStart( url );
  6063. },
  6064. setCrossOrigin: function ( value ) {
  6065. this.crossOrigin = value;
  6066. }
  6067. };
  6068. /**
  6069. * @author mrdoob / http://mrdoob.com/
  6070. */
  6071. THREE.ImageLoader = function ( manager ) {
  6072. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6073. };
  6074. THREE.ImageLoader.prototype = {
  6075. constructor: THREE.ImageLoader,
  6076. load: function ( url, onLoad, onProgress, onError ) {
  6077. var scope = this;
  6078. var image = document.createElement( 'img' );
  6079. if ( onLoad !== undefined ) {
  6080. image.addEventListener( 'load', function ( event ) {
  6081. scope.manager.itemEnd( url );
  6082. onLoad( this );
  6083. }, false );
  6084. }
  6085. if ( onProgress !== undefined ) {
  6086. image.addEventListener( 'progress', function ( event ) {
  6087. onProgress( event );
  6088. }, false );
  6089. }
  6090. if ( onError !== undefined ) {
  6091. image.addEventListener( 'error', function ( event ) {
  6092. onError( event );
  6093. }, false );
  6094. }
  6095. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  6096. image.src = url;
  6097. scope.manager.itemStart( url );
  6098. },
  6099. setCrossOrigin: function ( value ) {
  6100. this.crossOrigin = value;
  6101. }
  6102. }
  6103. /**
  6104. * @author mrdoob / http://mrdoob.com/
  6105. * @author alteredq / http://alteredqualia.com/
  6106. */
  6107. THREE.JSONLoader = function ( showStatus ) {
  6108. THREE.Loader.call( this, showStatus );
  6109. this.withCredentials = false;
  6110. };
  6111. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  6112. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  6113. var scope = this;
  6114. // todo: unify load API to for easier SceneLoader use
  6115. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  6116. this.onLoadStart();
  6117. this.loadAjaxJSON( this, url, callback, texturePath );
  6118. };
  6119. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  6120. var xhr = new XMLHttpRequest();
  6121. var length = 0;
  6122. xhr.onreadystatechange = function () {
  6123. if ( xhr.readyState === xhr.DONE ) {
  6124. if ( xhr.status === 200 || xhr.status === 0 ) {
  6125. if ( xhr.responseText ) {
  6126. var json = JSON.parse( xhr.responseText );
  6127. var result = context.parse( json, texturePath );
  6128. callback( result.geometry, result.materials );
  6129. } else {
  6130. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  6131. }
  6132. // in context of more complex asset initialization
  6133. // do not block on single failed file
  6134. // maybe should go even one more level up
  6135. context.onLoadComplete();
  6136. } else {
  6137. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  6138. }
  6139. } else if ( xhr.readyState === xhr.LOADING ) {
  6140. if ( callbackProgress ) {
  6141. if ( length === 0 ) {
  6142. length = xhr.getResponseHeader( "Content-Length" );
  6143. }
  6144. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  6145. }
  6146. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  6147. if ( callbackProgress !== undefined ) {
  6148. length = xhr.getResponseHeader( "Content-Length" );
  6149. }
  6150. }
  6151. };
  6152. xhr.open( "GET", url, true );
  6153. xhr.withCredentials = this.withCredentials;
  6154. xhr.send( null );
  6155. };
  6156. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  6157. var scope = this,
  6158. geometry = new THREE.Geometry(),
  6159. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  6160. parseModel( scale );
  6161. parseSkin();
  6162. parseMorphing( scale );
  6163. geometry.computeCentroids();
  6164. geometry.computeFaceNormals();
  6165. function parseModel( scale ) {
  6166. function isBitSet( value, position ) {
  6167. return value & ( 1 << position );
  6168. }
  6169. var i, j, fi,
  6170. offset, zLength, nVertices,
  6171. colorIndex, normalIndex, uvIndex, materialIndex,
  6172. type,
  6173. isQuad,
  6174. hasMaterial,
  6175. hasFaceUv, hasFaceVertexUv,
  6176. hasFaceNormal, hasFaceVertexNormal,
  6177. hasFaceColor, hasFaceVertexColor,
  6178. vertex, face, color, normal,
  6179. uvLayer, uvs, u, v,
  6180. faces = json.faces,
  6181. vertices = json.vertices,
  6182. normals = json.normals,
  6183. colors = json.colors,
  6184. nUvLayers = 0;
  6185. // disregard empty arrays
  6186. for ( i = 0; i < json.uvs.length; i++ ) {
  6187. if ( json.uvs[ i ].length ) nUvLayers ++;
  6188. }
  6189. for ( i = 0; i < nUvLayers; i++ ) {
  6190. geometry.faceUvs[ i ] = [];
  6191. geometry.faceVertexUvs[ i ] = [];
  6192. }
  6193. offset = 0;
  6194. zLength = vertices.length;
  6195. while ( offset < zLength ) {
  6196. vertex = new THREE.Vector3();
  6197. vertex.x = vertices[ offset ++ ] * scale;
  6198. vertex.y = vertices[ offset ++ ] * scale;
  6199. vertex.z = vertices[ offset ++ ] * scale;
  6200. geometry.vertices.push( vertex );
  6201. }
  6202. offset = 0;
  6203. zLength = faces.length;
  6204. while ( offset < zLength ) {
  6205. type = faces[ offset ++ ];
  6206. isQuad = isBitSet( type, 0 );
  6207. hasMaterial = isBitSet( type, 1 );
  6208. hasFaceUv = isBitSet( type, 2 );
  6209. hasFaceVertexUv = isBitSet( type, 3 );
  6210. hasFaceNormal = isBitSet( type, 4 );
  6211. hasFaceVertexNormal = isBitSet( type, 5 );
  6212. hasFaceColor = isBitSet( type, 6 );
  6213. hasFaceVertexColor = isBitSet( type, 7 );
  6214. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  6215. if ( isQuad ) {
  6216. face = new THREE.Face4();
  6217. face.a = faces[ offset ++ ];
  6218. face.b = faces[ offset ++ ];
  6219. face.c = faces[ offset ++ ];
  6220. face.d = faces[ offset ++ ];
  6221. nVertices = 4;
  6222. } else {
  6223. face = new THREE.Face3();
  6224. face.a = faces[ offset ++ ];
  6225. face.b = faces[ offset ++ ];
  6226. face.c = faces[ offset ++ ];
  6227. nVertices = 3;
  6228. }
  6229. if ( hasMaterial ) {
  6230. materialIndex = faces[ offset ++ ];
  6231. face.materialIndex = materialIndex;
  6232. }
  6233. // to get face <=> uv index correspondence
  6234. fi = geometry.faces.length;
  6235. if ( hasFaceUv ) {
  6236. for ( i = 0; i < nUvLayers; i++ ) {
  6237. uvLayer = json.uvs[ i ];
  6238. uvIndex = faces[ offset ++ ];
  6239. u = uvLayer[ uvIndex * 2 ];
  6240. v = uvLayer[ uvIndex * 2 + 1 ];
  6241. geometry.faceUvs[ i ][ fi ] = new THREE.Vector2( u, v );
  6242. }
  6243. }
  6244. if ( hasFaceVertexUv ) {
  6245. for ( i = 0; i < nUvLayers; i++ ) {
  6246. uvLayer = json.uvs[ i ];
  6247. uvs = [];
  6248. for ( j = 0; j < nVertices; j ++ ) {
  6249. uvIndex = faces[ offset ++ ];
  6250. u = uvLayer[ uvIndex * 2 ];
  6251. v = uvLayer[ uvIndex * 2 + 1 ];
  6252. uvs[ j ] = new THREE.Vector2( u, v );
  6253. }
  6254. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  6255. }
  6256. }
  6257. if ( hasFaceNormal ) {
  6258. normalIndex = faces[ offset ++ ] * 3;
  6259. normal = new THREE.Vector3();
  6260. normal.x = normals[ normalIndex ++ ];
  6261. normal.y = normals[ normalIndex ++ ];
  6262. normal.z = normals[ normalIndex ];
  6263. face.normal = normal;
  6264. }
  6265. if ( hasFaceVertexNormal ) {
  6266. for ( i = 0; i < nVertices; i++ ) {
  6267. normalIndex = faces[ offset ++ ] * 3;
  6268. normal = new THREE.Vector3();
  6269. normal.x = normals[ normalIndex ++ ];
  6270. normal.y = normals[ normalIndex ++ ];
  6271. normal.z = normals[ normalIndex ];
  6272. face.vertexNormals.push( normal );
  6273. }
  6274. }
  6275. if ( hasFaceColor ) {
  6276. colorIndex = faces[ offset ++ ];
  6277. color = new THREE.Color( colors[ colorIndex ] );
  6278. face.color = color;
  6279. }
  6280. if ( hasFaceVertexColor ) {
  6281. for ( i = 0; i < nVertices; i++ ) {
  6282. colorIndex = faces[ offset ++ ];
  6283. color = new THREE.Color( colors[ colorIndex ] );
  6284. face.vertexColors.push( color );
  6285. }
  6286. }
  6287. geometry.faces.push( face );
  6288. }
  6289. };
  6290. function parseSkin() {
  6291. var i, l, x, y, z, w, a, b, c, d;
  6292. if ( json.skinWeights ) {
  6293. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  6294. x = json.skinWeights[ i ];
  6295. y = json.skinWeights[ i + 1 ];
  6296. z = 0;
  6297. w = 0;
  6298. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  6299. }
  6300. }
  6301. if ( json.skinIndices ) {
  6302. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  6303. a = json.skinIndices[ i ];
  6304. b = json.skinIndices[ i + 1 ];
  6305. c = 0;
  6306. d = 0;
  6307. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  6308. }
  6309. }
  6310. geometry.bones = json.bones;
  6311. geometry.animation = json.animation;
  6312. };
  6313. function parseMorphing( scale ) {
  6314. if ( json.morphTargets !== undefined ) {
  6315. var i, l, v, vl, dstVertices, srcVertices;
  6316. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  6317. geometry.morphTargets[ i ] = {};
  6318. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  6319. geometry.morphTargets[ i ].vertices = [];
  6320. dstVertices = geometry.morphTargets[ i ].vertices;
  6321. srcVertices = json.morphTargets [ i ].vertices;
  6322. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  6323. var vertex = new THREE.Vector3();
  6324. vertex.x = srcVertices[ v ] * scale;
  6325. vertex.y = srcVertices[ v + 1 ] * scale;
  6326. vertex.z = srcVertices[ v + 2 ] * scale;
  6327. dstVertices.push( vertex );
  6328. }
  6329. }
  6330. }
  6331. if ( json.morphColors !== undefined ) {
  6332. var i, l, c, cl, dstColors, srcColors, color;
  6333. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  6334. geometry.morphColors[ i ] = {};
  6335. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  6336. geometry.morphColors[ i ].colors = [];
  6337. dstColors = geometry.morphColors[ i ].colors;
  6338. srcColors = json.morphColors [ i ].colors;
  6339. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  6340. color = new THREE.Color( 0xffaa00 );
  6341. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  6342. dstColors.push( color );
  6343. }
  6344. }
  6345. }
  6346. };
  6347. if ( json.materials === undefined ) {
  6348. return { geometry: geometry };
  6349. } else {
  6350. var materials = this.initMaterials( json.materials, texturePath );
  6351. if ( this.needsTangents( materials ) ) {
  6352. geometry.computeTangents();
  6353. }
  6354. return { geometry: geometry, materials: materials };
  6355. }
  6356. };
  6357. /**
  6358. * @author mrdoob / http://mrdoob.com/
  6359. */
  6360. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  6361. var scope = this;
  6362. var loaded = 0, total = 0;
  6363. this.onLoad = onLoad;
  6364. this.onProgress = onProgress;
  6365. this.onError = onError;
  6366. this.itemStart = function ( url ) {
  6367. total ++;
  6368. };
  6369. this.itemEnd = function ( url ) {
  6370. loaded ++;
  6371. if ( scope.onProgress !== undefined ) {
  6372. scope.onProgress( url, loaded, total );
  6373. }
  6374. if ( loaded === total && scope.onLoad !== undefined ) {
  6375. scope.onLoad();
  6376. }
  6377. };
  6378. };
  6379. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  6380. /**
  6381. * @author mrdoob / http://mrdoob.com/
  6382. */
  6383. THREE.GeometryLoader = function ( manager ) {
  6384. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6385. };
  6386. THREE.GeometryLoader.prototype = {
  6387. constructor: THREE.GeometryLoader,
  6388. load: function ( url, onLoad, onProgress, onError ) {
  6389. var scope = this;
  6390. var loader = new THREE.XHRLoader();
  6391. loader.setCrossOrigin( this.crossOrigin );
  6392. loader.load( url, function ( text ) {
  6393. onLoad( scope.parse( JSON.parse( text ) ) );
  6394. } );
  6395. },
  6396. setCrossOrigin: function ( value ) {
  6397. this.crossOrigin = value;
  6398. },
  6399. parse: function ( json ) {
  6400. }
  6401. };
  6402. /**
  6403. * @author mrdoob / http://mrdoob.com/
  6404. */
  6405. THREE.MaterialLoader = function ( manager ) {
  6406. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6407. };
  6408. THREE.MaterialLoader.prototype = {
  6409. constructor: THREE.MaterialLoader,
  6410. load: function ( url, onLoad, onProgress, onError ) {
  6411. var scope = this;
  6412. var loader = new THREE.XHRLoader();
  6413. loader.setCrossOrigin( this.crossOrigin );
  6414. loader.load( url, function ( text ) {
  6415. onLoad( scope.parse( JSON.parse( text ) ) );
  6416. } );
  6417. },
  6418. setCrossOrigin: function ( value ) {
  6419. this.crossOrigin = value;
  6420. },
  6421. parse: function ( json ) {
  6422. var material;
  6423. switch ( json.type ) {
  6424. case 'MeshBasicMaterial':
  6425. material = new THREE.MeshBasicMaterial( {
  6426. color: json.color,
  6427. opacity: json.opacity,
  6428. transparent: json.transparent,
  6429. wireframe: json.wireframe
  6430. } );
  6431. break;
  6432. case 'MeshLambertMaterial':
  6433. material = new THREE.MeshLambertMaterial( {
  6434. color: json.color,
  6435. ambient: json.ambient,
  6436. emissive: json.emissive,
  6437. opacity: json.opacity,
  6438. transparent: json.transparent,
  6439. wireframe: json.wireframe
  6440. } );
  6441. break;
  6442. case 'MeshPhongMaterial':
  6443. material = new THREE.MeshPhongMaterial( {
  6444. color: json.color,
  6445. ambient: json.ambient,
  6446. emissive: json.emissive,
  6447. specular: json.specular,
  6448. shininess: json.shininess,
  6449. opacity: json.opacity,
  6450. transparent: json.transparent,
  6451. wireframe: json.wireframe
  6452. } );
  6453. break;
  6454. case 'MeshNormalMaterial':
  6455. material = new THREE.MeshNormalMaterial( {
  6456. opacity: json.opacity,
  6457. transparent: json.transparent,
  6458. wireframe: json.wireframe
  6459. } );
  6460. break;
  6461. case 'MeshDepthMaterial':
  6462. material = new THREE.MeshDepthMaterial( {
  6463. opacity: json.opacity,
  6464. transparent: json.transparent,
  6465. wireframe: json.wireframe
  6466. } );
  6467. break;
  6468. }
  6469. return material;
  6470. }
  6471. };
  6472. /**
  6473. * @author mrdoob / http://mrdoob.com/
  6474. */
  6475. THREE.ObjectLoader = function ( manager ) {
  6476. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6477. };
  6478. THREE.ObjectLoader.prototype = {
  6479. constructor: THREE.ObjectLoader,
  6480. load: function ( url, onLoad, onProgress, onError ) {
  6481. var scope = this;
  6482. var loader = new THREE.XHRLoader( scope.manager );
  6483. loader.setCrossOrigin( this.crossOrigin );
  6484. loader.load( url, function ( text ) {
  6485. onLoad( scope.parse( JSON.parse( text ) ) );
  6486. } );
  6487. },
  6488. setCrossOrigin: function ( value ) {
  6489. this.crossOrigin = value;
  6490. },
  6491. parse: function ( json ) {
  6492. var geometries = this.parseGeometries( json.geometries );
  6493. var materials = this.parseMaterials( json.materials );
  6494. var object = this.parseObject( json.object, geometries, materials );
  6495. return object;
  6496. },
  6497. parseGeometries: function ( json ) {
  6498. var geometries = {};
  6499. if ( json !== undefined ) {
  6500. var loader = new THREE.JSONLoader();
  6501. for ( var i = 0, l = json.length; i < l; i ++ ) {
  6502. var geometry;
  6503. var data = json[ i ];
  6504. switch ( data.type ) {
  6505. case 'PlaneGeometry':
  6506. geometry = new THREE.PlaneGeometry(
  6507. data.width,
  6508. data.height,
  6509. data.widthSegments,
  6510. data.heightSegments
  6511. );
  6512. break;
  6513. case 'CubeGeometry':
  6514. geometry = new THREE.CubeGeometry(
  6515. data.width,
  6516. data.height,
  6517. data.depth,
  6518. data.widthSegments,
  6519. data.heightSegments,
  6520. data.depthSegments
  6521. );
  6522. break;
  6523. case 'CylinderGeometry':
  6524. geometry = new THREE.CylinderGeometry(
  6525. data.radiusTop,
  6526. data.radiusBottom,
  6527. data.height,
  6528. data.radiusSegments,
  6529. data.heightSegments,
  6530. data.openEnded
  6531. );
  6532. break;
  6533. case 'SphereGeometry':
  6534. geometry = new THREE.SphereGeometry(
  6535. data.radius,
  6536. data.widthSegments,
  6537. data.heightSegments,
  6538. data.phiStart,
  6539. data.phiLength,
  6540. data.thetaStart,
  6541. data.thetaLength
  6542. );
  6543. break;
  6544. case 'IcosahedronGeometry':
  6545. geometry = new THREE.IcosahedronGeometry(
  6546. data.radius,
  6547. data.detail
  6548. );
  6549. break;
  6550. case 'TorusGeometry':
  6551. geometry = new THREE.TorusGeometry(
  6552. data.radius,
  6553. data.tube,
  6554. data.radialSegments,
  6555. data.tubularSegments,
  6556. data.arc
  6557. );
  6558. break;
  6559. case 'TorusKnotGeometry':
  6560. geometry = new THREE.TorusKnotGeometry(
  6561. data.radius,
  6562. data.tube,
  6563. data.radialSegments,
  6564. data.tubularSegments,
  6565. data.p,
  6566. data.q,
  6567. data.heightScale
  6568. );
  6569. break;
  6570. case 'Geometry':
  6571. geometry = loader.parse( data.data ).geometry;
  6572. break;
  6573. }
  6574. if ( data.id !== undefined ) geometry.id = data.id;
  6575. if ( data.name !== undefined ) geometry.name = data.name;
  6576. geometries[ data.id ] = geometry;
  6577. }
  6578. }
  6579. return geometries;
  6580. },
  6581. parseMaterials: function ( json ) {
  6582. var materials = {};
  6583. if ( json !== undefined ) {
  6584. var loader = new THREE.MaterialLoader();
  6585. for ( var i = 0, l = json.length; i < l; i ++ ) {
  6586. var data = json[ i ];
  6587. var material = loader.parse( data );
  6588. if ( data.id !== undefined ) material.id = data.id;
  6589. if ( data.name !== undefined ) material.name = data.name;
  6590. materials[ data.id ] = material;
  6591. }
  6592. }
  6593. return materials;
  6594. },
  6595. parseObject: function () {
  6596. var matrix = new THREE.Matrix4();
  6597. return function ( data, geometries, materials ) {
  6598. var object;
  6599. switch ( data.type ) {
  6600. case 'Scene':
  6601. object = new THREE.Scene();
  6602. break;
  6603. case 'PerspectiveCamera':
  6604. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  6605. break;
  6606. case 'OrthographicCamera':
  6607. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  6608. break;
  6609. case 'AmbientLight':
  6610. object = new THREE.AmbientLight( data.color );
  6611. break;
  6612. case 'DirectionalLight':
  6613. object = new THREE.DirectionalLight( data.color, data.intensity );
  6614. break;
  6615. case 'PointLight':
  6616. object = new THREE.PointLight( data.color, data.intensity, data.distance );
  6617. break;
  6618. case 'SpotLight':
  6619. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent );
  6620. break;
  6621. case 'HemisphereLight':
  6622. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  6623. break;
  6624. case 'Mesh':
  6625. object = new THREE.Mesh( geometries[ data.geometry ], materials[ data.material ] );
  6626. break;
  6627. default:
  6628. object = new THREE.Object3D();
  6629. }
  6630. if ( data.matrix !== undefined ) {
  6631. matrix.fromArray( data.matrix );
  6632. matrix.decompose( object.position, object.quaternion, object.scale );
  6633. object.rotation.updateEuler();
  6634. } else {
  6635. if ( data.position !== undefined ) object.position.fromArray( data.position );
  6636. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  6637. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  6638. }
  6639. if ( data.id !== undefined ) object.id = data.id;
  6640. if ( data.name !== undefined ) object.name = data.name;
  6641. if ( data.visible !== undefined ) object.visible = data.visible;
  6642. if ( data.userData !== undefined ) object.userData = data.userData;
  6643. if ( data.children !== undefined ) {
  6644. for ( var child in data.children ) {
  6645. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  6646. }
  6647. }
  6648. return object;
  6649. }
  6650. }()
  6651. };
  6652. /**
  6653. * @author alteredq / http://alteredqualia.com/
  6654. */
  6655. THREE.SceneLoader = function () {
  6656. this.onLoadStart = function () {};
  6657. this.onLoadProgress = function() {};
  6658. this.onLoadComplete = function () {};
  6659. this.callbackSync = function () {};
  6660. this.callbackProgress = function () {};
  6661. this.geometryHandlers = {};
  6662. this.hierarchyHandlers = {};
  6663. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  6664. };
  6665. THREE.SceneLoader.prototype = {
  6666. constructor: THREE.SceneLoader,
  6667. load: function ( url, onLoad, onProgress, onError ) {
  6668. var scope = this;
  6669. var loader = new THREE.XHRLoader( scope.manager );
  6670. loader.setCrossOrigin( this.crossOrigin );
  6671. loader.load( url, function ( text ) {
  6672. scope.parse( JSON.parse( text ), onLoad, url );
  6673. } );
  6674. },
  6675. setCrossOrigin: function ( value ) {
  6676. this.crossOrigin = value;
  6677. },
  6678. addGeometryHandler: function ( typeID, loaderClass ) {
  6679. this.geometryHandlers[ typeID ] = { "loaderClass": loaderClass };
  6680. },
  6681. addHierarchyHandler: function ( typeID, loaderClass ) {
  6682. this.hierarchyHandlers[ typeID ] = { "loaderClass": loaderClass };
  6683. },
  6684. parse: function ( json, callbackFinished, url ) {
  6685. var scope = this;
  6686. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  6687. var geometry, material, camera, fog,
  6688. texture, images, color,
  6689. light, hex, intensity,
  6690. counter_models, counter_textures,
  6691. total_models, total_textures,
  6692. result;
  6693. var target_array = [];
  6694. var data = json;
  6695. // async geometry loaders
  6696. for ( var typeID in this.geometryHandlers ) {
  6697. var loaderClass = this.geometryHandlers[ typeID ][ "loaderClass" ];
  6698. this.geometryHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  6699. }
  6700. // async hierachy loaders
  6701. for ( var typeID in this.hierarchyHandlers ) {
  6702. var loaderClass = this.hierarchyHandlers[ typeID ][ "loaderClass" ];
  6703. this.hierarchyHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  6704. }
  6705. counter_models = 0;
  6706. counter_textures = 0;
  6707. result = {
  6708. scene: new THREE.Scene(),
  6709. geometries: {},
  6710. face_materials: {},
  6711. materials: {},
  6712. textures: {},
  6713. objects: {},
  6714. cameras: {},
  6715. lights: {},
  6716. fogs: {},
  6717. empties: {},
  6718. groups: {}
  6719. };
  6720. if ( data.transform ) {
  6721. var position = data.transform.position,
  6722. rotation = data.transform.rotation,
  6723. scale = data.transform.scale;
  6724. if ( position ) {
  6725. result.scene.position.fromArray( position );
  6726. }
  6727. if ( rotation ) {
  6728. result.scene.rotation.fromArray( rotation );
  6729. }
  6730. if ( scale ) {
  6731. result.scene.scale.fromArray( scale );
  6732. }
  6733. if ( position || rotation || scale ) {
  6734. result.scene.updateMatrix();
  6735. result.scene.updateMatrixWorld();
  6736. }
  6737. }
  6738. function get_url( source_url, url_type ) {
  6739. if ( url_type == "relativeToHTML" ) {
  6740. return source_url;
  6741. } else {
  6742. return urlBase + "/" + source_url;
  6743. }
  6744. };
  6745. // toplevel loader function, delegates to handle_children
  6746. function handle_objects() {
  6747. handle_children( result.scene, data.objects );
  6748. }
  6749. // handle all the children from the loaded json and attach them to given parent
  6750. function handle_children( parent, children ) {
  6751. var mat, dst, pos, rot, scl, quat;
  6752. for ( var objID in children ) {
  6753. // check by id if child has already been handled,
  6754. // if not, create new object
  6755. var object = result.objects[ objID ];
  6756. var objJSON = children[ objID ];
  6757. if ( object === undefined ) {
  6758. // meshes
  6759. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  6760. if ( objJSON.loading === undefined ) {
  6761. var reservedTypes = {
  6762. "type": 1, "url": 1, "material": 1,
  6763. "position": 1, "rotation": 1, "scale" : 1,
  6764. "visible": 1, "children": 1, "userData": 1,
  6765. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1
  6766. };
  6767. var loaderParameters = {};
  6768. for ( var parType in objJSON ) {
  6769. if ( ! ( parType in reservedTypes ) ) {
  6770. loaderParameters[ parType ] = objJSON[ parType ];
  6771. }
  6772. }
  6773. material = result.materials[ objJSON.material ];
  6774. objJSON.loading = true;
  6775. var loader = scope.hierarchyHandlers[ objJSON.type ][ "loaderObject" ];
  6776. // ColladaLoader
  6777. if ( loader.options ) {
  6778. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  6779. // UTF8Loader
  6780. // OBJLoader
  6781. } else {
  6782. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  6783. }
  6784. }
  6785. } else if ( objJSON.geometry !== undefined ) {
  6786. geometry = result.geometries[ objJSON.geometry ];
  6787. // geometry already loaded
  6788. if ( geometry ) {
  6789. var needsTangents = false;
  6790. material = result.materials[ objJSON.material ];
  6791. needsTangents = material instanceof THREE.ShaderMaterial;
  6792. pos = objJSON.position;
  6793. rot = objJSON.rotation;
  6794. scl = objJSON.scale;
  6795. mat = objJSON.matrix;
  6796. quat = objJSON.quaternion;
  6797. // use materials from the model file
  6798. // if there is no material specified in the object
  6799. if ( ! objJSON.material ) {
  6800. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6801. }
  6802. // use materials from the model file
  6803. // if there is just empty face material
  6804. // (must create new material as each model has its own face material)
  6805. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  6806. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6807. }
  6808. if ( material instanceof THREE.MeshFaceMaterial ) {
  6809. for ( var i = 0; i < material.materials.length; i ++ ) {
  6810. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  6811. }
  6812. }
  6813. if ( needsTangents ) {
  6814. geometry.computeTangents();
  6815. }
  6816. if ( objJSON.skin ) {
  6817. object = new THREE.SkinnedMesh( geometry, material );
  6818. } else if ( objJSON.morph ) {
  6819. object = new THREE.MorphAnimMesh( geometry, material );
  6820. if ( objJSON.duration !== undefined ) {
  6821. object.duration = objJSON.duration;
  6822. }
  6823. if ( objJSON.time !== undefined ) {
  6824. object.time = objJSON.time;
  6825. }
  6826. if ( objJSON.mirroredLoop !== undefined ) {
  6827. object.mirroredLoop = objJSON.mirroredLoop;
  6828. }
  6829. if ( material.morphNormals ) {
  6830. geometry.computeMorphNormals();
  6831. }
  6832. } else {
  6833. object = new THREE.Mesh( geometry, material );
  6834. }
  6835. object.name = objID;
  6836. if ( mat ) {
  6837. object.matrixAutoUpdate = false;
  6838. object.matrix.set(
  6839. mat[0], mat[1], mat[2], mat[3],
  6840. mat[4], mat[5], mat[6], mat[7],
  6841. mat[8], mat[9], mat[10], mat[11],
  6842. mat[12], mat[13], mat[14], mat[15]
  6843. );
  6844. } else {
  6845. object.position.fromArray( pos );
  6846. if ( quat ) {
  6847. object.quaternion.fromArray( quat );
  6848. } else {
  6849. object.rotation.fromArray( rot );
  6850. }
  6851. object.scale.fromArray( scl );
  6852. }
  6853. object.visible = objJSON.visible;
  6854. object.castShadow = objJSON.castShadow;
  6855. object.receiveShadow = objJSON.receiveShadow;
  6856. parent.add( object );
  6857. result.objects[ objID ] = object;
  6858. }
  6859. // lights
  6860. } else if ( objJSON.type === "DirectionalLight" || objJSON.type === "PointLight" || objJSON.type === "AmbientLight" ) {
  6861. hex = ( objJSON.color !== undefined ) ? objJSON.color : 0xffffff;
  6862. intensity = ( objJSON.intensity !== undefined ) ? objJSON.intensity : 1;
  6863. if ( objJSON.type === "DirectionalLight" ) {
  6864. pos = objJSON.direction;
  6865. light = new THREE.DirectionalLight( hex, intensity );
  6866. light.position.fromArray( pos );
  6867. if ( objJSON.target ) {
  6868. target_array.push( { "object": light, "targetName" : objJSON.target } );
  6869. // kill existing default target
  6870. // otherwise it gets added to scene when parent gets added
  6871. light.target = null;
  6872. }
  6873. } else if ( objJSON.type === "PointLight" ) {
  6874. pos = objJSON.position;
  6875. dst = objJSON.distance;
  6876. light = new THREE.PointLight( hex, intensity, dst );
  6877. light.position.fromArray( pos );
  6878. } else if ( objJSON.type === "AmbientLight" ) {
  6879. light = new THREE.AmbientLight( hex );
  6880. }
  6881. parent.add( light );
  6882. light.name = objID;
  6883. result.lights[ objID ] = light;
  6884. result.objects[ objID ] = light;
  6885. // cameras
  6886. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  6887. pos = objJSON.position;
  6888. rot = objJSON.rotation;
  6889. quat = objJSON.quaternion;
  6890. if ( objJSON.type === "PerspectiveCamera" ) {
  6891. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  6892. } else if ( objJSON.type === "OrthographicCamera" ) {
  6893. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  6894. }
  6895. camera.name = objID;
  6896. camera.position.fromArray( pos );
  6897. if ( quat !== undefined ) {
  6898. camera.quaternion.fromArray( quat );
  6899. } else if ( rot !== undefined ) {
  6900. camera.rotation.fromArray( rot );
  6901. }
  6902. parent.add( camera );
  6903. result.cameras[ objID ] = camera;
  6904. result.objects[ objID ] = camera;
  6905. // pure Object3D
  6906. } else {
  6907. pos = objJSON.position;
  6908. rot = objJSON.rotation;
  6909. scl = objJSON.scale;
  6910. quat = objJSON.quaternion;
  6911. object = new THREE.Object3D();
  6912. object.name = objID;
  6913. object.position.fromArray( pos );
  6914. if ( quat ) {
  6915. object.quaternion.fromArray( quat );
  6916. } else {
  6917. object.rotation.fromArray( rot );
  6918. }
  6919. object.scale.fromArray( scl );
  6920. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  6921. parent.add( object );
  6922. result.objects[ objID ] = object;
  6923. result.empties[ objID ] = object;
  6924. }
  6925. if ( object ) {
  6926. if ( objJSON.userData !== undefined ) {
  6927. for ( var key in objJSON.userData ) {
  6928. var value = objJSON.userData[ key ];
  6929. object.userData[ key ] = value;
  6930. }
  6931. }
  6932. if ( objJSON.groups !== undefined ) {
  6933. for ( var i = 0; i < objJSON.groups.length; i ++ ) {
  6934. var groupID = objJSON.groups[ i ];
  6935. if ( result.groups[ groupID ] === undefined ) {
  6936. result.groups[ groupID ] = [];
  6937. }
  6938. result.groups[ groupID ].push( objID );
  6939. }
  6940. }
  6941. }
  6942. }
  6943. if ( object !== undefined && objJSON.children !== undefined ) {
  6944. handle_children( object, objJSON.children );
  6945. }
  6946. }
  6947. };
  6948. function handle_mesh( geo, mat, id ) {
  6949. result.geometries[ id ] = geo;
  6950. result.face_materials[ id ] = mat;
  6951. handle_objects();
  6952. };
  6953. function handle_hierarchy( node, id, parent, material, obj ) {
  6954. var p = obj.position;
  6955. var r = obj.rotation;
  6956. var q = obj.quaternion;
  6957. var s = obj.scale;
  6958. node.position.fromArray( p );
  6959. if ( q ) {
  6960. node.quaternion.fromArray( q );
  6961. } else {
  6962. node.rotation.fromArray( r );
  6963. }
  6964. node.scale.fromArray( s );
  6965. // override children materials
  6966. // if object material was specified in JSON explicitly
  6967. if ( material ) {
  6968. node.traverse( function ( child ) {
  6969. child.material = material;
  6970. } );
  6971. }
  6972. // override children visibility
  6973. // with root node visibility as specified in JSON
  6974. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  6975. node.traverse( function ( child ) {
  6976. child.visible = visible;
  6977. } );
  6978. parent.add( node );
  6979. node.name = id;
  6980. result.objects[ id ] = node;
  6981. handle_objects();
  6982. };
  6983. function create_callback_geometry( id ) {
  6984. return function ( geo, mat ) {
  6985. geo.name = id;
  6986. handle_mesh( geo, mat, id );
  6987. counter_models -= 1;
  6988. scope.onLoadComplete();
  6989. async_callback_gate();
  6990. }
  6991. };
  6992. function create_callback_hierachy( id, parent, material, obj ) {
  6993. return function ( event ) {
  6994. var result;
  6995. // loaders which use EventDispatcher
  6996. if ( event.content ) {
  6997. result = event.content;
  6998. // ColladaLoader
  6999. } else if ( event.dae ) {
  7000. result = event.scene;
  7001. // UTF8Loader
  7002. } else {
  7003. result = event;
  7004. }
  7005. handle_hierarchy( result, id, parent, material, obj );
  7006. counter_models -= 1;
  7007. scope.onLoadComplete();
  7008. async_callback_gate();
  7009. }
  7010. };
  7011. function create_callback_embed( id ) {
  7012. return function ( geo, mat ) {
  7013. geo.name = id;
  7014. result.geometries[ id ] = geo;
  7015. result.face_materials[ id ] = mat;
  7016. }
  7017. };
  7018. function async_callback_gate() {
  7019. var progress = {
  7020. totalModels : total_models,
  7021. totalTextures : total_textures,
  7022. loadedModels : total_models - counter_models,
  7023. loadedTextures : total_textures - counter_textures
  7024. };
  7025. scope.callbackProgress( progress, result );
  7026. scope.onLoadProgress();
  7027. if ( counter_models === 0 && counter_textures === 0 ) {
  7028. finalize();
  7029. callbackFinished( result );
  7030. }
  7031. };
  7032. function finalize() {
  7033. // take care of targets which could be asynchronously loaded objects
  7034. for ( var i = 0; i < target_array.length; i ++ ) {
  7035. var ta = target_array[ i ];
  7036. var target = result.objects[ ta.targetName ];
  7037. if ( target ) {
  7038. ta.object.target = target;
  7039. } else {
  7040. // if there was error and target of specified name doesn't exist in the scene file
  7041. // create instead dummy target
  7042. // (target must be added to scene explicitly as parent is already added)
  7043. ta.object.target = new THREE.Object3D();
  7044. result.scene.add( ta.object.target );
  7045. }
  7046. ta.object.target.userData.targetInverse = ta.object;
  7047. }
  7048. };
  7049. var callbackTexture = function ( count ) {
  7050. counter_textures -= count;
  7051. async_callback_gate();
  7052. scope.onLoadComplete();
  7053. };
  7054. // must use this instead of just directly calling callbackTexture
  7055. // because of closure in the calling context loop
  7056. var generateTextureCallback = function ( count ) {
  7057. return function () {
  7058. callbackTexture( count );
  7059. };
  7060. };
  7061. function traverse_json_hierarchy( objJSON, callback ) {
  7062. callback( objJSON );
  7063. if ( objJSON.children !== undefined ) {
  7064. for ( var objChildID in objJSON.children ) {
  7065. traverse_json_hierarchy( objJSON.children[ objChildID ], callback );
  7066. }
  7067. }
  7068. };
  7069. // first go synchronous elements
  7070. // fogs
  7071. var fogID, fogJSON;
  7072. for ( fogID in data.fogs ) {
  7073. fogJSON = data.fogs[ fogID ];
  7074. if ( fogJSON.type === "linear" ) {
  7075. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  7076. } else if ( fogJSON.type === "exp2" ) {
  7077. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  7078. }
  7079. color = fogJSON.color;
  7080. fog.color.setRGB( color[0], color[1], color[2] );
  7081. result.fogs[ fogID ] = fog;
  7082. }
  7083. // now come potentially asynchronous elements
  7084. // geometries
  7085. // count how many geometries will be loaded asynchronously
  7086. var geoID, geoJSON;
  7087. for ( geoID in data.geometries ) {
  7088. geoJSON = data.geometries[ geoID ];
  7089. if ( geoJSON.type in this.geometryHandlers ) {
  7090. counter_models += 1;
  7091. scope.onLoadStart();
  7092. }
  7093. }
  7094. // count how many hierarchies will be loaded asynchronously
  7095. for ( var objID in data.objects ) {
  7096. traverse_json_hierarchy( data.objects[ objID ], function ( objJSON ) {
  7097. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  7098. counter_models += 1;
  7099. scope.onLoadStart();
  7100. }
  7101. });
  7102. }
  7103. total_models = counter_models;
  7104. for ( geoID in data.geometries ) {
  7105. geoJSON = data.geometries[ geoID ];
  7106. if ( geoJSON.type === "cube" ) {
  7107. geometry = new THREE.CubeGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  7108. geometry.name = geoID;
  7109. result.geometries[ geoID ] = geometry;
  7110. } else if ( geoJSON.type === "plane" ) {
  7111. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  7112. geometry.name = geoID;
  7113. result.geometries[ geoID ] = geometry;
  7114. } else if ( geoJSON.type === "sphere" ) {
  7115. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  7116. geometry.name = geoID;
  7117. result.geometries[ geoID ] = geometry;
  7118. } else if ( geoJSON.type === "cylinder" ) {
  7119. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  7120. geometry.name = geoID;
  7121. result.geometries[ geoID ] = geometry;
  7122. } else if ( geoJSON.type === "torus" ) {
  7123. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  7124. geometry.name = geoID;
  7125. result.geometries[ geoID ] = geometry;
  7126. } else if ( geoJSON.type === "icosahedron" ) {
  7127. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  7128. geometry.name = geoID;
  7129. result.geometries[ geoID ] = geometry;
  7130. } else if ( geoJSON.type in this.geometryHandlers ) {
  7131. var loaderParameters = {};
  7132. for ( var parType in geoJSON ) {
  7133. if ( parType !== "type" && parType !== "url" ) {
  7134. loaderParameters[ parType ] = geoJSON[ parType ];
  7135. }
  7136. }
  7137. var loader = this.geometryHandlers[ geoJSON.type ][ "loaderObject" ];
  7138. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  7139. } else if ( geoJSON.type === "embedded" ) {
  7140. var modelJson = data.embeds[ geoJSON.id ],
  7141. texture_path = "";
  7142. // pass metadata along to jsonLoader so it knows the format version
  7143. modelJson.metadata = data.metadata;
  7144. if ( modelJson ) {
  7145. var jsonLoader = this.geometryHandlers[ "ascii" ][ "loaderObject" ];
  7146. var model = jsonLoader.parse( modelJson, texture_path );
  7147. create_callback_embed( geoID )( model.geometry, model.materials );
  7148. }
  7149. }
  7150. }
  7151. // textures
  7152. // count how many textures will be loaded asynchronously
  7153. var textureID, textureJSON;
  7154. for ( textureID in data.textures ) {
  7155. textureJSON = data.textures[ textureID ];
  7156. if ( textureJSON.url instanceof Array ) {
  7157. counter_textures += textureJSON.url.length;
  7158. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  7159. scope.onLoadStart();
  7160. }
  7161. } else {
  7162. counter_textures += 1;
  7163. scope.onLoadStart();
  7164. }
  7165. }
  7166. total_textures = counter_textures;
  7167. for ( textureID in data.textures ) {
  7168. textureJSON = data.textures[ textureID ];
  7169. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  7170. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  7171. }
  7172. if ( textureJSON.url instanceof Array ) {
  7173. var count = textureJSON.url.length;
  7174. var url_array = [];
  7175. for( var i = 0; i < count; i ++ ) {
  7176. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  7177. }
  7178. var isCompressed = /\.dds$/i.test( url_array[ 0 ] );
  7179. if ( isCompressed ) {
  7180. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  7181. } else {
  7182. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  7183. }
  7184. } else {
  7185. var isCompressed = /\.dds$/i.test( textureJSON.url );
  7186. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  7187. var textureCallback = generateTextureCallback( 1 );
  7188. if ( isCompressed ) {
  7189. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  7190. } else {
  7191. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  7192. }
  7193. if ( THREE[ textureJSON.minFilter ] !== undefined )
  7194. texture.minFilter = THREE[ textureJSON.minFilter ];
  7195. if ( THREE[ textureJSON.magFilter ] !== undefined )
  7196. texture.magFilter = THREE[ textureJSON.magFilter ];
  7197. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  7198. if ( textureJSON.repeat ) {
  7199. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  7200. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  7201. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  7202. }
  7203. if ( textureJSON.offset ) {
  7204. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  7205. }
  7206. // handle wrap after repeat so that default repeat can be overriden
  7207. if ( textureJSON.wrap ) {
  7208. var wrapMap = {
  7209. "repeat": THREE.RepeatWrapping,
  7210. "mirror": THREE.MirroredRepeatWrapping
  7211. }
  7212. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  7213. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  7214. }
  7215. }
  7216. result.textures[ textureID ] = texture;
  7217. }
  7218. // materials
  7219. var matID, matJSON;
  7220. var parID;
  7221. for ( matID in data.materials ) {
  7222. matJSON = data.materials[ matID ];
  7223. for ( parID in matJSON.parameters ) {
  7224. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  7225. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  7226. } else if ( parID === "shading" ) {
  7227. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  7228. } else if ( parID === "side" ) {
  7229. if ( matJSON.parameters[ parID ] == "double" ) {
  7230. matJSON.parameters[ parID ] = THREE.DoubleSide;
  7231. } else if ( matJSON.parameters[ parID ] == "back" ) {
  7232. matJSON.parameters[ parID ] = THREE.BackSide;
  7233. } else {
  7234. matJSON.parameters[ parID ] = THREE.FrontSide;
  7235. }
  7236. } else if ( parID === "blending" ) {
  7237. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  7238. } else if ( parID === "combine" ) {
  7239. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  7240. } else if ( parID === "vertexColors" ) {
  7241. if ( matJSON.parameters[ parID ] == "face" ) {
  7242. matJSON.parameters[ parID ] = THREE.FaceColors;
  7243. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  7244. } else if ( matJSON.parameters[ parID ] ) {
  7245. matJSON.parameters[ parID ] = THREE.VertexColors;
  7246. }
  7247. } else if ( parID === "wrapRGB" ) {
  7248. var v3 = matJSON.parameters[ parID ];
  7249. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  7250. }
  7251. }
  7252. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  7253. matJSON.parameters.transparent = true;
  7254. }
  7255. if ( matJSON.parameters.normalMap ) {
  7256. var shader = THREE.ShaderLib[ "normalmap" ];
  7257. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  7258. var diffuse = matJSON.parameters.color;
  7259. var specular = matJSON.parameters.specular;
  7260. var ambient = matJSON.parameters.ambient;
  7261. var shininess = matJSON.parameters.shininess;
  7262. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  7263. if ( matJSON.parameters.normalScale ) {
  7264. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  7265. }
  7266. if ( matJSON.parameters.map ) {
  7267. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  7268. uniforms[ "enableDiffuse" ].value = true;
  7269. }
  7270. if ( matJSON.parameters.envMap ) {
  7271. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  7272. uniforms[ "enableReflection" ].value = true;
  7273. uniforms[ "uReflectivity" ].value = matJSON.parameters.reflectivity;
  7274. }
  7275. if ( matJSON.parameters.lightMap ) {
  7276. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  7277. uniforms[ "enableAO" ].value = true;
  7278. }
  7279. if ( matJSON.parameters.specularMap ) {
  7280. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  7281. uniforms[ "enableSpecular" ].value = true;
  7282. }
  7283. if ( matJSON.parameters.displacementMap ) {
  7284. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  7285. uniforms[ "enableDisplacement" ].value = true;
  7286. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  7287. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  7288. }
  7289. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  7290. uniforms[ "uSpecularColor" ].value.setHex( specular );
  7291. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  7292. uniforms[ "uShininess" ].value = shininess;
  7293. if ( matJSON.parameters.opacity ) {
  7294. uniforms[ "uOpacity" ].value = matJSON.parameters.opacity;
  7295. }
  7296. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  7297. material = new THREE.ShaderMaterial( parameters );
  7298. } else {
  7299. material = new THREE[ matJSON.type ]( matJSON.parameters );
  7300. }
  7301. material.name = matID;
  7302. result.materials[ matID ] = material;
  7303. }
  7304. // second pass through all materials to initialize MeshFaceMaterials
  7305. // that could be referring to other materials out of order
  7306. for ( matID in data.materials ) {
  7307. matJSON = data.materials[ matID ];
  7308. if ( matJSON.parameters.materials ) {
  7309. var materialArray = [];
  7310. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  7311. var label = matJSON.parameters.materials[ i ];
  7312. materialArray.push( result.materials[ label ] );
  7313. }
  7314. result.materials[ matID ].materials = materialArray;
  7315. }
  7316. }
  7317. // objects ( synchronous init of procedural primitives )
  7318. handle_objects();
  7319. // defaults
  7320. if ( result.cameras && data.defaults.camera ) {
  7321. result.currentCamera = result.cameras[ data.defaults.camera ];
  7322. }
  7323. if ( result.fogs && data.defaults.fog ) {
  7324. result.scene.fog = result.fogs[ data.defaults.fog ];
  7325. }
  7326. // synchronous callback
  7327. scope.callbackSync( result );
  7328. // just in case there are no async elements
  7329. async_callback_gate();
  7330. }
  7331. }
  7332. /**
  7333. * @author mrdoob / http://mrdoob.com/
  7334. */
  7335. THREE.TextureLoader = function ( manager ) {
  7336. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7337. };
  7338. THREE.TextureLoader.prototype = {
  7339. constructor: THREE.TextureLoader,
  7340. load: function ( url, onLoad, onProgress, onError ) {
  7341. var scope = this;
  7342. var loader = new THREE.ImageLoader( scope.manager );
  7343. loader.setCrossOrigin( this.crossOrigin );
  7344. loader.load( url, function ( image ) {
  7345. var texture = new THREE.Texture( image );
  7346. texture.needsUpdate = true;
  7347. if ( onLoad !== undefined ) {
  7348. onLoad( texture );
  7349. }
  7350. } );
  7351. },
  7352. setCrossOrigin: function ( value ) {
  7353. this.crossOrigin = value;
  7354. }
  7355. };
  7356. /**
  7357. * @author mrdoob / http://mrdoob.com/
  7358. * @author alteredq / http://alteredqualia.com/
  7359. */
  7360. THREE.Material = function () {
  7361. this.id = THREE.Math.generateUUID();
  7362. this.name = '';
  7363. this.side = THREE.FrontSide;
  7364. this.opacity = 1;
  7365. this.transparent = false;
  7366. this.blending = THREE.NormalBlending;
  7367. this.blendSrc = THREE.SrcAlphaFactor;
  7368. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  7369. this.blendEquation = THREE.AddEquation;
  7370. this.depthTest = true;
  7371. this.depthWrite = true;
  7372. this.polygonOffset = false;
  7373. this.polygonOffsetFactor = 0;
  7374. this.polygonOffsetUnits = 0;
  7375. this.alphaTest = 0;
  7376. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  7377. this.visible = true;
  7378. this.needsUpdate = true;
  7379. };
  7380. THREE.Material.prototype = {
  7381. constructor: THREE.Material,
  7382. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  7383. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  7384. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  7385. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  7386. setValues: function ( values ) {
  7387. if ( values === undefined ) return;
  7388. for ( var key in values ) {
  7389. var newValue = values[ key ];
  7390. if ( newValue === undefined ) {
  7391. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  7392. continue;
  7393. }
  7394. if ( key in this ) {
  7395. var currentValue = this[ key ];
  7396. if ( currentValue instanceof THREE.Color ) {
  7397. currentValue.set( newValue );
  7398. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  7399. currentValue.copy( newValue );
  7400. } else if ( key == 'overdraw') {
  7401. // ensure overdraw is backwards-compatable with legacy boolean type
  7402. this[ key ] = Number(newValue);
  7403. } else {
  7404. this[ key ] = newValue;
  7405. }
  7406. }
  7407. }
  7408. },
  7409. clone: function ( material ) {
  7410. if ( material === undefined ) material = new THREE.Material();
  7411. material.name = this.name;
  7412. material.side = this.side;
  7413. material.opacity = this.opacity;
  7414. material.transparent = this.transparent;
  7415. material.blending = this.blending;
  7416. material.blendSrc = this.blendSrc;
  7417. material.blendDst = this.blendDst;
  7418. material.blendEquation = this.blendEquation;
  7419. material.depthTest = this.depthTest;
  7420. material.depthWrite = this.depthWrite;
  7421. material.polygonOffset = this.polygonOffset;
  7422. material.polygonOffsetFactor = this.polygonOffsetFactor;
  7423. material.polygonOffsetUnits = this.polygonOffsetUnits;
  7424. material.alphaTest = this.alphaTest;
  7425. material.overdraw = this.overdraw;
  7426. material.visible = this.visible;
  7427. return material;
  7428. },
  7429. dispose: function () {
  7430. this.dispatchEvent( { type: 'dispose' } );
  7431. }
  7432. };
  7433. /**
  7434. * @author mrdoob / http://mrdoob.com/
  7435. * @author alteredq / http://alteredqualia.com/
  7436. *
  7437. * parameters = {
  7438. * color: <hex>,
  7439. * opacity: <float>,
  7440. *
  7441. * blending: THREE.NormalBlending,
  7442. * depthTest: <bool>,
  7443. * depthWrite: <bool>,
  7444. *
  7445. * linewidth: <float>,
  7446. * linecap: "round",
  7447. * linejoin: "round",
  7448. *
  7449. * vertexColors: <bool>
  7450. *
  7451. * fog: <bool>
  7452. * }
  7453. */
  7454. THREE.LineBasicMaterial = function ( parameters ) {
  7455. THREE.Material.call( this );
  7456. this.color = new THREE.Color( 0xffffff );
  7457. this.linewidth = 1;
  7458. this.linecap = 'round';
  7459. this.linejoin = 'round';
  7460. this.vertexColors = false;
  7461. this.fog = true;
  7462. this.setValues( parameters );
  7463. };
  7464. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7465. THREE.LineBasicMaterial.prototype.clone = function () {
  7466. var material = new THREE.LineBasicMaterial();
  7467. THREE.Material.prototype.clone.call( this, material );
  7468. material.color.copy( this.color );
  7469. material.linewidth = this.linewidth;
  7470. material.linecap = this.linecap;
  7471. material.linejoin = this.linejoin;
  7472. material.vertexColors = this.vertexColors;
  7473. material.fog = this.fog;
  7474. return material;
  7475. };
  7476. /**
  7477. * @author alteredq / http://alteredqualia.com/
  7478. *
  7479. * parameters = {
  7480. * color: <hex>,
  7481. * opacity: <float>,
  7482. *
  7483. * blending: THREE.NormalBlending,
  7484. * depthTest: <bool>,
  7485. * depthWrite: <bool>,
  7486. *
  7487. * linewidth: <float>,
  7488. *
  7489. * scale: <float>,
  7490. * dashSize: <float>,
  7491. * gapSize: <float>,
  7492. *
  7493. * vertexColors: <bool>
  7494. *
  7495. * fog: <bool>
  7496. * }
  7497. */
  7498. THREE.LineDashedMaterial = function ( parameters ) {
  7499. THREE.Material.call( this );
  7500. this.color = new THREE.Color( 0xffffff );
  7501. this.linewidth = 1;
  7502. this.scale = 1;
  7503. this.dashSize = 3;
  7504. this.gapSize = 1;
  7505. this.vertexColors = false;
  7506. this.fog = true;
  7507. this.setValues( parameters );
  7508. };
  7509. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  7510. THREE.LineDashedMaterial.prototype.clone = function () {
  7511. var material = new THREE.LineDashedMaterial();
  7512. THREE.Material.prototype.clone.call( this, material );
  7513. material.color.copy( this.color );
  7514. material.linewidth = this.linewidth;
  7515. material.scale = this.scale;
  7516. material.dashSize = this.dashSize;
  7517. material.gapSize = this.gapSize;
  7518. material.vertexColors = this.vertexColors;
  7519. material.fog = this.fog;
  7520. return material;
  7521. };
  7522. /**
  7523. * @author mrdoob / http://mrdoob.com/
  7524. * @author alteredq / http://alteredqualia.com/
  7525. *
  7526. * parameters = {
  7527. * color: <hex>,
  7528. * opacity: <float>,
  7529. * map: new THREE.Texture( <Image> ),
  7530. *
  7531. * lightMap: new THREE.Texture( <Image> ),
  7532. *
  7533. * specularMap: new THREE.Texture( <Image> ),
  7534. *
  7535. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7536. * combine: THREE.Multiply,
  7537. * reflectivity: <float>,
  7538. * refractionRatio: <float>,
  7539. *
  7540. * shading: THREE.SmoothShading,
  7541. * blending: THREE.NormalBlending,
  7542. * depthTest: <bool>,
  7543. * depthWrite: <bool>,
  7544. *
  7545. * wireframe: <boolean>,
  7546. * wireframeLinewidth: <float>,
  7547. *
  7548. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7549. *
  7550. * skinning: <bool>,
  7551. * morphTargets: <bool>,
  7552. *
  7553. * fog: <bool>
  7554. * }
  7555. */
  7556. THREE.MeshBasicMaterial = function ( parameters ) {
  7557. THREE.Material.call( this );
  7558. this.color = new THREE.Color( 0xffffff ); // emissive
  7559. this.map = null;
  7560. this.lightMap = null;
  7561. this.specularMap = null;
  7562. this.envMap = null;
  7563. this.combine = THREE.MultiplyOperation;
  7564. this.reflectivity = 1;
  7565. this.refractionRatio = 0.98;
  7566. this.fog = true;
  7567. this.shading = THREE.SmoothShading;
  7568. this.wireframe = false;
  7569. this.wireframeLinewidth = 1;
  7570. this.wireframeLinecap = 'round';
  7571. this.wireframeLinejoin = 'round';
  7572. this.vertexColors = THREE.NoColors;
  7573. this.skinning = false;
  7574. this.morphTargets = false;
  7575. this.setValues( parameters );
  7576. };
  7577. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7578. THREE.MeshBasicMaterial.prototype.clone = function () {
  7579. var material = new THREE.MeshBasicMaterial();
  7580. THREE.Material.prototype.clone.call( this, material );
  7581. material.color.copy( this.color );
  7582. material.map = this.map;
  7583. material.lightMap = this.lightMap;
  7584. material.specularMap = this.specularMap;
  7585. material.envMap = this.envMap;
  7586. material.combine = this.combine;
  7587. material.reflectivity = this.reflectivity;
  7588. material.refractionRatio = this.refractionRatio;
  7589. material.fog = this.fog;
  7590. material.shading = this.shading;
  7591. material.wireframe = this.wireframe;
  7592. material.wireframeLinewidth = this.wireframeLinewidth;
  7593. material.wireframeLinecap = this.wireframeLinecap;
  7594. material.wireframeLinejoin = this.wireframeLinejoin;
  7595. material.vertexColors = this.vertexColors;
  7596. material.skinning = this.skinning;
  7597. material.morphTargets = this.morphTargets;
  7598. return material;
  7599. };
  7600. /**
  7601. * @author mrdoob / http://mrdoob.com/
  7602. * @author alteredq / http://alteredqualia.com/
  7603. *
  7604. * parameters = {
  7605. * color: <hex>,
  7606. * ambient: <hex>,
  7607. * emissive: <hex>,
  7608. * opacity: <float>,
  7609. *
  7610. * map: new THREE.Texture( <Image> ),
  7611. *
  7612. * lightMap: new THREE.Texture( <Image> ),
  7613. *
  7614. * specularMap: new THREE.Texture( <Image> ),
  7615. *
  7616. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7617. * combine: THREE.Multiply,
  7618. * reflectivity: <float>,
  7619. * refractionRatio: <float>,
  7620. *
  7621. * shading: THREE.SmoothShading,
  7622. * blending: THREE.NormalBlending,
  7623. * depthTest: <bool>,
  7624. * depthWrite: <bool>,
  7625. *
  7626. * wireframe: <boolean>,
  7627. * wireframeLinewidth: <float>,
  7628. *
  7629. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7630. *
  7631. * skinning: <bool>,
  7632. * morphTargets: <bool>,
  7633. * morphNormals: <bool>,
  7634. *
  7635. * fog: <bool>
  7636. * }
  7637. */
  7638. THREE.MeshLambertMaterial = function ( parameters ) {
  7639. THREE.Material.call( this );
  7640. this.color = new THREE.Color( 0xffffff ); // diffuse
  7641. this.ambient = new THREE.Color( 0xffffff );
  7642. this.emissive = new THREE.Color( 0x000000 );
  7643. this.wrapAround = false;
  7644. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7645. this.map = null;
  7646. this.lightMap = null;
  7647. this.specularMap = null;
  7648. this.envMap = null;
  7649. this.combine = THREE.MultiplyOperation;
  7650. this.reflectivity = 1;
  7651. this.refractionRatio = 0.98;
  7652. this.fog = true;
  7653. this.shading = THREE.SmoothShading;
  7654. this.wireframe = false;
  7655. this.wireframeLinewidth = 1;
  7656. this.wireframeLinecap = 'round';
  7657. this.wireframeLinejoin = 'round';
  7658. this.vertexColors = THREE.NoColors;
  7659. this.skinning = false;
  7660. this.morphTargets = false;
  7661. this.morphNormals = false;
  7662. this.setValues( parameters );
  7663. };
  7664. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  7665. THREE.MeshLambertMaterial.prototype.clone = function () {
  7666. var material = new THREE.MeshLambertMaterial();
  7667. THREE.Material.prototype.clone.call( this, material );
  7668. material.color.copy( this.color );
  7669. material.ambient.copy( this.ambient );
  7670. material.emissive.copy( this.emissive );
  7671. material.wrapAround = this.wrapAround;
  7672. material.wrapRGB.copy( this.wrapRGB );
  7673. material.map = this.map;
  7674. material.lightMap = this.lightMap;
  7675. material.specularMap = this.specularMap;
  7676. material.envMap = this.envMap;
  7677. material.combine = this.combine;
  7678. material.reflectivity = this.reflectivity;
  7679. material.refractionRatio = this.refractionRatio;
  7680. material.fog = this.fog;
  7681. material.shading = this.shading;
  7682. material.wireframe = this.wireframe;
  7683. material.wireframeLinewidth = this.wireframeLinewidth;
  7684. material.wireframeLinecap = this.wireframeLinecap;
  7685. material.wireframeLinejoin = this.wireframeLinejoin;
  7686. material.vertexColors = this.vertexColors;
  7687. material.skinning = this.skinning;
  7688. material.morphTargets = this.morphTargets;
  7689. material.morphNormals = this.morphNormals;
  7690. return material;
  7691. };
  7692. /**
  7693. * @author mrdoob / http://mrdoob.com/
  7694. * @author alteredq / http://alteredqualia.com/
  7695. *
  7696. * parameters = {
  7697. * color: <hex>,
  7698. * ambient: <hex>,
  7699. * emissive: <hex>,
  7700. * specular: <hex>,
  7701. * shininess: <float>,
  7702. * opacity: <float>,
  7703. *
  7704. * map: new THREE.Texture( <Image> ),
  7705. *
  7706. * lightMap: new THREE.Texture( <Image> ),
  7707. *
  7708. * bumpMap: new THREE.Texture( <Image> ),
  7709. * bumpScale: <float>,
  7710. *
  7711. * normalMap: new THREE.Texture( <Image> ),
  7712. * normalScale: <Vector2>,
  7713. *
  7714. * specularMap: new THREE.Texture( <Image> ),
  7715. *
  7716. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7717. * combine: THREE.Multiply,
  7718. * reflectivity: <float>,
  7719. * refractionRatio: <float>,
  7720. *
  7721. * shading: THREE.SmoothShading,
  7722. * blending: THREE.NormalBlending,
  7723. * depthTest: <bool>,
  7724. * depthWrite: <bool>,
  7725. *
  7726. * wireframe: <boolean>,
  7727. * wireframeLinewidth: <float>,
  7728. *
  7729. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7730. *
  7731. * skinning: <bool>,
  7732. * morphTargets: <bool>,
  7733. * morphNormals: <bool>,
  7734. *
  7735. * fog: <bool>
  7736. * }
  7737. */
  7738. THREE.MeshPhongMaterial = function ( parameters ) {
  7739. THREE.Material.call( this );
  7740. this.color = new THREE.Color( 0xffffff ); // diffuse
  7741. this.ambient = new THREE.Color( 0xffffff );
  7742. this.emissive = new THREE.Color( 0x000000 );
  7743. this.specular = new THREE.Color( 0x111111 );
  7744. this.shininess = 30;
  7745. this.metal = false;
  7746. this.perPixel = true;
  7747. this.wrapAround = false;
  7748. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7749. this.map = null;
  7750. this.lightMap = null;
  7751. this.bumpMap = null;
  7752. this.bumpScale = 1;
  7753. this.normalMap = null;
  7754. this.normalScale = new THREE.Vector2( 1, 1 );
  7755. this.specularMap = null;
  7756. this.envMap = null;
  7757. this.combine = THREE.MultiplyOperation;
  7758. this.reflectivity = 1;
  7759. this.refractionRatio = 0.98;
  7760. this.fog = true;
  7761. this.shading = THREE.SmoothShading;
  7762. this.wireframe = false;
  7763. this.wireframeLinewidth = 1;
  7764. this.wireframeLinecap = 'round';
  7765. this.wireframeLinejoin = 'round';
  7766. this.vertexColors = THREE.NoColors;
  7767. this.skinning = false;
  7768. this.morphTargets = false;
  7769. this.morphNormals = false;
  7770. this.setValues( parameters );
  7771. };
  7772. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  7773. THREE.MeshPhongMaterial.prototype.clone = function () {
  7774. var material = new THREE.MeshPhongMaterial();
  7775. THREE.Material.prototype.clone.call( this, material );
  7776. material.color.copy( this.color );
  7777. material.ambient.copy( this.ambient );
  7778. material.emissive.copy( this.emissive );
  7779. material.specular.copy( this.specular );
  7780. material.shininess = this.shininess;
  7781. material.metal = this.metal;
  7782. material.perPixel = this.perPixel;
  7783. material.wrapAround = this.wrapAround;
  7784. material.wrapRGB.copy( this.wrapRGB );
  7785. material.map = this.map;
  7786. material.lightMap = this.lightMap;
  7787. material.bumpMap = this.bumpMap;
  7788. material.bumpScale = this.bumpScale;
  7789. material.normalMap = this.normalMap;
  7790. material.normalScale.copy( this.normalScale );
  7791. material.specularMap = this.specularMap;
  7792. material.envMap = this.envMap;
  7793. material.combine = this.combine;
  7794. material.reflectivity = this.reflectivity;
  7795. material.refractionRatio = this.refractionRatio;
  7796. material.fog = this.fog;
  7797. material.shading = this.shading;
  7798. material.wireframe = this.wireframe;
  7799. material.wireframeLinewidth = this.wireframeLinewidth;
  7800. material.wireframeLinecap = this.wireframeLinecap;
  7801. material.wireframeLinejoin = this.wireframeLinejoin;
  7802. material.vertexColors = this.vertexColors;
  7803. material.skinning = this.skinning;
  7804. material.morphTargets = this.morphTargets;
  7805. material.morphNormals = this.morphNormals;
  7806. return material;
  7807. };
  7808. /**
  7809. * @author mrdoob / http://mrdoob.com/
  7810. * @author alteredq / http://alteredqualia.com/
  7811. *
  7812. * parameters = {
  7813. * opacity: <float>,
  7814. *
  7815. * blending: THREE.NormalBlending,
  7816. * depthTest: <bool>,
  7817. * depthWrite: <bool>,
  7818. *
  7819. * wireframe: <boolean>,
  7820. * wireframeLinewidth: <float>
  7821. * }
  7822. */
  7823. THREE.MeshDepthMaterial = function ( parameters ) {
  7824. THREE.Material.call( this );
  7825. this.wireframe = false;
  7826. this.wireframeLinewidth = 1;
  7827. this.setValues( parameters );
  7828. };
  7829. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  7830. THREE.MeshDepthMaterial.prototype.clone = function () {
  7831. var material = new THREE.MeshDepthMaterial();
  7832. THREE.Material.prototype.clone.call( this, material );
  7833. material.wireframe = this.wireframe;
  7834. material.wireframeLinewidth = this.wireframeLinewidth;
  7835. return material;
  7836. };
  7837. /**
  7838. * @author mrdoob / http://mrdoob.com/
  7839. *
  7840. * parameters = {
  7841. * opacity: <float>,
  7842. *
  7843. * shading: THREE.FlatShading,
  7844. * blending: THREE.NormalBlending,
  7845. * depthTest: <bool>,
  7846. * depthWrite: <bool>,
  7847. *
  7848. * wireframe: <boolean>,
  7849. * wireframeLinewidth: <float>
  7850. * }
  7851. */
  7852. THREE.MeshNormalMaterial = function ( parameters ) {
  7853. THREE.Material.call( this, parameters );
  7854. this.shading = THREE.FlatShading;
  7855. this.wireframe = false;
  7856. this.wireframeLinewidth = 1;
  7857. this.morphTargets = false;
  7858. this.setValues( parameters );
  7859. };
  7860. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  7861. THREE.MeshNormalMaterial.prototype.clone = function () {
  7862. var material = new THREE.MeshNormalMaterial();
  7863. THREE.Material.prototype.clone.call( this, material );
  7864. material.shading = this.shading;
  7865. material.wireframe = this.wireframe;
  7866. material.wireframeLinewidth = this.wireframeLinewidth;
  7867. return material;
  7868. };
  7869. /**
  7870. * @author mrdoob / http://mrdoob.com/
  7871. */
  7872. THREE.MeshFaceMaterial = function ( materials ) {
  7873. this.materials = materials instanceof Array ? materials : [];
  7874. };
  7875. THREE.MeshFaceMaterial.prototype.clone = function () {
  7876. return new THREE.MeshFaceMaterial( this.materials.slice( 0 ) );
  7877. };
  7878. /**
  7879. * @author mrdoob / http://mrdoob.com/
  7880. * @author alteredq / http://alteredqualia.com/
  7881. *
  7882. * parameters = {
  7883. * color: <hex>,
  7884. * opacity: <float>,
  7885. * map: new THREE.Texture( <Image> ),
  7886. *
  7887. * size: <float>,
  7888. *
  7889. * blending: THREE.NormalBlending,
  7890. * depthTest: <bool>,
  7891. * depthWrite: <bool>,
  7892. *
  7893. * vertexColors: <bool>,
  7894. *
  7895. * fog: <bool>
  7896. * }
  7897. */
  7898. THREE.ParticleBasicMaterial = function ( parameters ) {
  7899. THREE.Material.call( this );
  7900. this.color = new THREE.Color( 0xffffff );
  7901. this.map = null;
  7902. this.size = 1;
  7903. this.sizeAttenuation = true;
  7904. this.vertexColors = false;
  7905. this.fog = true;
  7906. this.setValues( parameters );
  7907. };
  7908. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7909. THREE.ParticleBasicMaterial.prototype.clone = function () {
  7910. var material = new THREE.ParticleBasicMaterial();
  7911. THREE.Material.prototype.clone.call( this, material );
  7912. material.color.copy( this.color );
  7913. material.map = this.map;
  7914. material.size = this.size;
  7915. material.sizeAttenuation = this.sizeAttenuation;
  7916. material.vertexColors = this.vertexColors;
  7917. material.fog = this.fog;
  7918. return material;
  7919. };
  7920. /**
  7921. * @author mrdoob / http://mrdoob.com/
  7922. *
  7923. * parameters = {
  7924. * color: <hex>,
  7925. * program: <function>,
  7926. * opacity: <float>,
  7927. * blending: THREE.NormalBlending
  7928. * }
  7929. */
  7930. THREE.ParticleCanvasMaterial = function ( parameters ) {
  7931. THREE.Material.call( this );
  7932. this.color = new THREE.Color( 0xffffff );
  7933. this.program = function ( context, color ) {};
  7934. this.setValues( parameters );
  7935. };
  7936. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  7937. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  7938. var material = new THREE.ParticleCanvasMaterial();
  7939. THREE.Material.prototype.clone.call( this, material );
  7940. material.color.copy( this.color );
  7941. material.program = this.program;
  7942. return material;
  7943. };
  7944. /**
  7945. * @author alteredq / http://alteredqualia.com/
  7946. *
  7947. * parameters = {
  7948. * fragmentShader: <string>,
  7949. * vertexShader: <string>,
  7950. *
  7951. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  7952. *
  7953. * defines: { "label" : "value" },
  7954. *
  7955. * shading: THREE.SmoothShading,
  7956. * blending: THREE.NormalBlending,
  7957. * depthTest: <bool>,
  7958. * depthWrite: <bool>,
  7959. *
  7960. * wireframe: <boolean>,
  7961. * wireframeLinewidth: <float>,
  7962. *
  7963. * lights: <bool>,
  7964. *
  7965. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7966. *
  7967. * skinning: <bool>,
  7968. * morphTargets: <bool>,
  7969. * morphNormals: <bool>,
  7970. *
  7971. * fog: <bool>
  7972. * }
  7973. */
  7974. THREE.ShaderMaterial = function ( parameters ) {
  7975. THREE.Material.call( this );
  7976. this.fragmentShader = "void main() {}";
  7977. this.vertexShader = "void main() {}";
  7978. this.uniforms = {};
  7979. this.defines = {};
  7980. this.attributes = null;
  7981. this.shading = THREE.SmoothShading;
  7982. this.linewidth = 1;
  7983. this.wireframe = false;
  7984. this.wireframeLinewidth = 1;
  7985. this.fog = false; // set to use scene fog
  7986. this.lights = false; // set to use scene lights
  7987. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  7988. this.skinning = false; // set to use skinning attribute streams
  7989. this.morphTargets = false; // set to use morph targets
  7990. this.morphNormals = false; // set to use morph normals
  7991. this.setValues( parameters );
  7992. };
  7993. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  7994. THREE.ShaderMaterial.prototype.clone = function () {
  7995. var material = new THREE.ShaderMaterial();
  7996. THREE.Material.prototype.clone.call( this, material );
  7997. material.fragmentShader = this.fragmentShader;
  7998. material.vertexShader = this.vertexShader;
  7999. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  8000. material.attributes = this.attributes;
  8001. material.defines = this.defines;
  8002. material.shading = this.shading;
  8003. material.wireframe = this.wireframe;
  8004. material.wireframeLinewidth = this.wireframeLinewidth;
  8005. material.fog = this.fog;
  8006. material.lights = this.lights;
  8007. material.vertexColors = this.vertexColors;
  8008. material.skinning = this.skinning;
  8009. material.morphTargets = this.morphTargets;
  8010. material.morphNormals = this.morphNormals;
  8011. return material;
  8012. };
  8013. /**
  8014. * @author alteredq / http://alteredqualia.com/
  8015. *
  8016. * parameters = {
  8017. * color: <hex>,
  8018. * opacity: <float>,
  8019. * map: new THREE.Texture( <Image> ),
  8020. *
  8021. * blending: THREE.NormalBlending,
  8022. * depthTest: <bool>,
  8023. * depthWrite: <bool>,
  8024. *
  8025. * useScreenCoordinates: <bool>,
  8026. * sizeAttenuation: <bool>,
  8027. * scaleByViewport: <bool>,
  8028. * alignment: THREE.SpriteAlignment.center,
  8029. *
  8030. * uvOffset: new THREE.Vector2(),
  8031. * uvScale: new THREE.Vector2(),
  8032. *
  8033. * fog: <bool>
  8034. * }
  8035. */
  8036. THREE.SpriteMaterial = function ( parameters ) {
  8037. THREE.Material.call( this );
  8038. // defaults
  8039. this.color = new THREE.Color( 0xffffff );
  8040. this.map = new THREE.Texture();
  8041. this.useScreenCoordinates = true;
  8042. this.depthTest = !this.useScreenCoordinates;
  8043. this.sizeAttenuation = !this.useScreenCoordinates;
  8044. this.scaleByViewport = !this.sizeAttenuation;
  8045. this.alignment = THREE.SpriteAlignment.center.clone();
  8046. this.fog = false;
  8047. this.uvOffset = new THREE.Vector2( 0, 0 );
  8048. this.uvScale = new THREE.Vector2( 1, 1 );
  8049. // set parameters
  8050. this.setValues( parameters );
  8051. // override coupled defaults if not specified explicitly by parameters
  8052. parameters = parameters || {};
  8053. if ( parameters.depthTest === undefined ) this.depthTest = !this.useScreenCoordinates;
  8054. if ( parameters.sizeAttenuation === undefined ) this.sizeAttenuation = !this.useScreenCoordinates;
  8055. if ( parameters.scaleByViewport === undefined ) this.scaleByViewport = !this.sizeAttenuation;
  8056. };
  8057. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  8058. THREE.SpriteMaterial.prototype.clone = function () {
  8059. var material = new THREE.SpriteMaterial();
  8060. THREE.Material.prototype.clone.call( this, material );
  8061. material.color.copy( this.color );
  8062. material.map = this.map;
  8063. material.useScreenCoordinates = this.useScreenCoordinates;
  8064. material.sizeAttenuation = this.sizeAttenuation;
  8065. material.scaleByViewport = this.scaleByViewport;
  8066. material.alignment.copy( this.alignment );
  8067. material.uvOffset.copy( this.uvOffset );
  8068. material.uvScale.copy( this.uvScale );
  8069. material.fog = this.fog;
  8070. return material;
  8071. };
  8072. // Alignment enums
  8073. THREE.SpriteAlignment = {};
  8074. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  8075. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  8076. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  8077. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  8078. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  8079. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  8080. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  8081. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  8082. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  8083. /**
  8084. * @author mrdoob / http://mrdoob.com/
  8085. * @author alteredq / http://alteredqualia.com/
  8086. * @author szimek / https://github.com/szimek/
  8087. */
  8088. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8089. this.id = THREE.Math.generateUUID();
  8090. this.name = '';
  8091. this.image = image;
  8092. this.mipmaps = [];
  8093. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  8094. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  8095. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  8096. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  8097. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  8098. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  8099. this.format = format !== undefined ? format : THREE.RGBAFormat;
  8100. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  8101. this.offset = new THREE.Vector2( 0, 0 );
  8102. this.repeat = new THREE.Vector2( 1, 1 );
  8103. this.generateMipmaps = true;
  8104. this.premultiplyAlpha = false;
  8105. this.flipY = true;
  8106. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  8107. this.needsUpdate = false;
  8108. this.onUpdate = null;
  8109. };
  8110. THREE.Texture.prototype = {
  8111. constructor: THREE.Texture,
  8112. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  8113. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  8114. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  8115. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  8116. clone: function ( texture ) {
  8117. if ( texture === undefined ) texture = new THREE.Texture();
  8118. texture.image = this.image;
  8119. texture.mipmaps = this.mipmaps.slice(0);
  8120. texture.mapping = this.mapping;
  8121. texture.wrapS = this.wrapS;
  8122. texture.wrapT = this.wrapT;
  8123. texture.magFilter = this.magFilter;
  8124. texture.minFilter = this.minFilter;
  8125. texture.anisotropy = this.anisotropy;
  8126. texture.format = this.format;
  8127. texture.type = this.type;
  8128. texture.offset.copy( this.offset );
  8129. texture.repeat.copy( this.repeat );
  8130. texture.generateMipmaps = this.generateMipmaps;
  8131. texture.premultiplyAlpha = this.premultiplyAlpha;
  8132. texture.flipY = this.flipY;
  8133. texture.unpackAlignment = this.unpackAlignment;
  8134. return texture;
  8135. },
  8136. dispose: function () {
  8137. this.dispatchEvent( { type: 'dispose' } );
  8138. }
  8139. };
  8140. /**
  8141. * @author alteredq / http://alteredqualia.com/
  8142. */
  8143. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8144. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8145. this.image = { width: width, height: height };
  8146. this.mipmaps = mipmaps;
  8147. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  8148. };
  8149. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  8150. THREE.CompressedTexture.prototype.clone = function () {
  8151. var texture = new THREE.CompressedTexture();
  8152. THREE.Texture.prototype.clone.call( this, texture );
  8153. return texture;
  8154. };
  8155. /**
  8156. * @author alteredq / http://alteredqualia.com/
  8157. */
  8158. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8159. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8160. this.image = { data: data, width: width, height: height };
  8161. };
  8162. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  8163. THREE.DataTexture.prototype.clone = function () {
  8164. var texture = new THREE.DataTexture();
  8165. THREE.Texture.prototype.clone.call( this, texture );
  8166. return texture;
  8167. };
  8168. /**
  8169. * @author mrdoob / http://mrdoob.com/
  8170. */
  8171. THREE.Particle = function ( material ) {
  8172. THREE.Object3D.call( this );
  8173. this.material = material;
  8174. };
  8175. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  8176. THREE.Particle.prototype.clone = function ( object ) {
  8177. if ( object === undefined ) object = new THREE.Particle( this.material );
  8178. THREE.Object3D.prototype.clone.call( this, object );
  8179. return object;
  8180. };
  8181. /**
  8182. * @author alteredq / http://alteredqualia.com/
  8183. */
  8184. THREE.ParticleSystem = function ( geometry, material ) {
  8185. THREE.Object3D.call( this );
  8186. this.geometry = geometry;
  8187. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  8188. this.sortParticles = false;
  8189. if ( this.geometry ) {
  8190. // calc bound radius
  8191. if( this.geometry.boundingSphere === null ) {
  8192. this.geometry.computeBoundingSphere();
  8193. }
  8194. }
  8195. this.frustumCulled = false;
  8196. };
  8197. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  8198. THREE.ParticleSystem.prototype.clone = function ( object ) {
  8199. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  8200. object.sortParticles = this.sortParticles;
  8201. THREE.Object3D.prototype.clone.call( this, object );
  8202. return object;
  8203. };
  8204. /**
  8205. * @author mrdoob / http://mrdoob.com/
  8206. */
  8207. THREE.Line = function ( geometry, material, type ) {
  8208. THREE.Object3D.call( this );
  8209. this.geometry = geometry;
  8210. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  8211. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  8212. if ( this.geometry ) {
  8213. if ( ! this.geometry.boundingSphere ) {
  8214. this.geometry.computeBoundingSphere();
  8215. }
  8216. }
  8217. };
  8218. THREE.LineStrip = 0;
  8219. THREE.LinePieces = 1;
  8220. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  8221. THREE.Line.prototype.clone = function ( object ) {
  8222. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  8223. THREE.Object3D.prototype.clone.call( this, object );
  8224. return object;
  8225. };
  8226. /**
  8227. * @author mrdoob / http://mrdoob.com/
  8228. * @author alteredq / http://alteredqualia.com/
  8229. * @author mikael emtinger / http://gomo.se/
  8230. * @author jonobr1 / http://jonobr1.com/
  8231. */
  8232. THREE.Mesh = function ( geometry, material ) {
  8233. THREE.Object3D.call( this );
  8234. this.geometry = null;
  8235. this.material = null;
  8236. this.setGeometry( geometry );
  8237. this.setMaterial( material );
  8238. };
  8239. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  8240. THREE.Mesh.prototype.setGeometry = function ( geometry ) {
  8241. if ( geometry !== undefined ) {
  8242. this.geometry = geometry;
  8243. if ( this.geometry.boundingSphere === null ) {
  8244. this.geometry.computeBoundingSphere();
  8245. }
  8246. this.updateMorphTargets();
  8247. }
  8248. };
  8249. THREE.Mesh.prototype.setMaterial = function ( material ) {
  8250. if ( material !== undefined ) {
  8251. this.material = material;
  8252. } else {
  8253. this.material = new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  8254. }
  8255. };
  8256. THREE.Mesh.prototype.updateMorphTargets = function () {
  8257. if ( this.geometry.morphTargets.length > 0 ) {
  8258. this.morphTargetBase = -1;
  8259. this.morphTargetForcedOrder = [];
  8260. this.morphTargetInfluences = [];
  8261. this.morphTargetDictionary = {};
  8262. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  8263. this.morphTargetInfluences.push( 0 );
  8264. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  8265. }
  8266. }
  8267. };
  8268. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  8269. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  8270. return this.morphTargetDictionary[ name ];
  8271. }
  8272. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  8273. return 0;
  8274. };
  8275. THREE.Mesh.prototype.clone = function ( object ) {
  8276. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  8277. THREE.Object3D.prototype.clone.call( this, object );
  8278. return object;
  8279. };
  8280. /**
  8281. * @author mikael emtinger / http://gomo.se/
  8282. * @author alteredq / http://alteredqualia.com/
  8283. */
  8284. THREE.Bone = function( belongsToSkin ) {
  8285. THREE.Object3D.call( this );
  8286. this.skin = belongsToSkin;
  8287. this.skinMatrix = new THREE.Matrix4();
  8288. };
  8289. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  8290. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  8291. // update local
  8292. if ( this.matrixAutoUpdate ) {
  8293. forceUpdate |= this.updateMatrix();
  8294. }
  8295. // update skin matrix
  8296. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  8297. if( parentSkinMatrix ) {
  8298. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  8299. } else {
  8300. this.skinMatrix.copy( this.matrix );
  8301. }
  8302. this.matrixWorldNeedsUpdate = false;
  8303. forceUpdate = true;
  8304. }
  8305. // update children
  8306. var child, i, l = this.children.length;
  8307. for ( i = 0; i < l; i ++ ) {
  8308. this.children[ i ].update( this.skinMatrix, forceUpdate );
  8309. }
  8310. };
  8311. /**
  8312. * @author mikael emtinger / http://gomo.se/
  8313. * @author alteredq / http://alteredqualia.com/
  8314. */
  8315. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  8316. THREE.Mesh.call( this, geometry, material );
  8317. //
  8318. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  8319. // init bones
  8320. this.identityMatrix = new THREE.Matrix4();
  8321. this.bones = [];
  8322. this.boneMatrices = [];
  8323. var b, bone, gbone, p, q, s;
  8324. if ( this.geometry && this.geometry.bones !== undefined ) {
  8325. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  8326. gbone = this.geometry.bones[ b ];
  8327. p = gbone.pos;
  8328. q = gbone.rotq;
  8329. s = gbone.scl;
  8330. bone = this.addBone();
  8331. bone.name = gbone.name;
  8332. bone.position.set( p[0], p[1], p[2] );
  8333. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  8334. if ( s !== undefined ) {
  8335. bone.scale.set( s[0], s[1], s[2] );
  8336. } else {
  8337. bone.scale.set( 1, 1, 1 );
  8338. }
  8339. }
  8340. for ( b = 0; b < this.bones.length; b ++ ) {
  8341. gbone = this.geometry.bones[ b ];
  8342. bone = this.bones[ b ];
  8343. if ( gbone.parent === -1 ) {
  8344. this.add( bone );
  8345. } else {
  8346. this.bones[ gbone.parent ].add( bone );
  8347. }
  8348. }
  8349. //
  8350. var nBones = this.bones.length;
  8351. if ( this.useVertexTexture ) {
  8352. // layout (1 matrix = 4 pixels)
  8353. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  8354. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  8355. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  8356. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  8357. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  8358. var size;
  8359. if ( nBones > 256 )
  8360. size = 64;
  8361. else if ( nBones > 64 )
  8362. size = 32;
  8363. else if ( nBones > 16 )
  8364. size = 16;
  8365. else
  8366. size = 8;
  8367. this.boneTextureWidth = size;
  8368. this.boneTextureHeight = size;
  8369. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  8370. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  8371. this.boneTexture.minFilter = THREE.NearestFilter;
  8372. this.boneTexture.magFilter = THREE.NearestFilter;
  8373. this.boneTexture.generateMipmaps = false;
  8374. this.boneTexture.flipY = false;
  8375. } else {
  8376. this.boneMatrices = new Float32Array( 16 * nBones );
  8377. }
  8378. this.pose();
  8379. }
  8380. };
  8381. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  8382. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  8383. if ( bone === undefined ) {
  8384. bone = new THREE.Bone( this );
  8385. }
  8386. this.bones.push( bone );
  8387. return bone;
  8388. };
  8389. THREE.SkinnedMesh.prototype.updateMatrixWorld = function () {
  8390. var offsetMatrix = new THREE.Matrix4();
  8391. return function ( force ) {
  8392. this.matrixAutoUpdate && this.updateMatrix();
  8393. // update matrixWorld
  8394. if ( this.matrixWorldNeedsUpdate || force ) {
  8395. if ( this.parent ) {
  8396. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  8397. } else {
  8398. this.matrixWorld.copy( this.matrix );
  8399. }
  8400. this.matrixWorldNeedsUpdate = false;
  8401. force = true;
  8402. }
  8403. // update children
  8404. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  8405. var child = this.children[ i ];
  8406. if ( child instanceof THREE.Bone ) {
  8407. child.update( this.identityMatrix, false );
  8408. } else {
  8409. child.updateMatrixWorld( true );
  8410. }
  8411. }
  8412. // make a snapshot of the bones' rest position
  8413. if ( this.boneInverses == undefined ) {
  8414. this.boneInverses = [];
  8415. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  8416. var inverse = new THREE.Matrix4();
  8417. inverse.getInverse( this.bones[ b ].skinMatrix );
  8418. this.boneInverses.push( inverse );
  8419. }
  8420. }
  8421. // flatten bone matrices to array
  8422. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  8423. // compute the offset between the current and the original transform;
  8424. // TODO: we could get rid of this multiplication step if the skinMatrix
  8425. // was already representing the offset; however, this requires some
  8426. // major changes to the animation system
  8427. offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  8428. offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  8429. }
  8430. if ( this.useVertexTexture ) {
  8431. this.boneTexture.needsUpdate = true;
  8432. }
  8433. };
  8434. }();
  8435. THREE.SkinnedMesh.prototype.pose = function () {
  8436. this.updateMatrixWorld( true );
  8437. this.normalizeSkinWeights();
  8438. };
  8439. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  8440. if ( this.geometry instanceof THREE.Geometry ) {
  8441. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  8442. var sw = this.geometry.skinWeights[ i ];
  8443. var scale = 1.0 / sw.lengthManhattan();
  8444. if ( scale !== Infinity ) {
  8445. sw.multiplyScalar( scale );
  8446. } else {
  8447. sw.set( 1 ); // this will be normalized by the shader anyway
  8448. }
  8449. }
  8450. } else {
  8451. // skinning weights assumed to be normalized for THREE.BufferGeometry
  8452. }
  8453. };
  8454. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  8455. if ( object === undefined ) {
  8456. object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  8457. }
  8458. THREE.Mesh.prototype.clone.call( this, object );
  8459. return object;
  8460. };
  8461. /**
  8462. * @author alteredq / http://alteredqualia.com/
  8463. */
  8464. THREE.MorphAnimMesh = function ( geometry, material ) {
  8465. THREE.Mesh.call( this, geometry, material );
  8466. // API
  8467. this.duration = 1000; // milliseconds
  8468. this.mirroredLoop = false;
  8469. this.time = 0;
  8470. // internals
  8471. this.lastKeyframe = 0;
  8472. this.currentKeyframe = 0;
  8473. this.direction = 1;
  8474. this.directionBackwards = false;
  8475. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  8476. };
  8477. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  8478. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  8479. this.startKeyframe = start;
  8480. this.endKeyframe = end;
  8481. this.length = this.endKeyframe - this.startKeyframe + 1;
  8482. };
  8483. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  8484. this.direction = 1;
  8485. this.directionBackwards = false;
  8486. };
  8487. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  8488. this.direction = -1;
  8489. this.directionBackwards = true;
  8490. };
  8491. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  8492. var geometry = this.geometry;
  8493. if ( ! geometry.animations ) geometry.animations = {};
  8494. var firstAnimation, animations = geometry.animations;
  8495. var pattern = /([a-z]+)(\d+)/;
  8496. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  8497. var morph = geometry.morphTargets[ i ];
  8498. var parts = morph.name.match( pattern );
  8499. if ( parts && parts.length > 1 ) {
  8500. var label = parts[ 1 ];
  8501. var num = parts[ 2 ];
  8502. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  8503. var animation = animations[ label ];
  8504. if ( i < animation.start ) animation.start = i;
  8505. if ( i > animation.end ) animation.end = i;
  8506. if ( ! firstAnimation ) firstAnimation = label;
  8507. }
  8508. }
  8509. geometry.firstAnimation = firstAnimation;
  8510. };
  8511. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  8512. if ( ! this.geometry.animations ) this.geometry.animations = {};
  8513. this.geometry.animations[ label ] = { start: start, end: end };
  8514. };
  8515. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  8516. var animation = this.geometry.animations[ label ];
  8517. if ( animation ) {
  8518. this.setFrameRange( animation.start, animation.end );
  8519. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  8520. this.time = 0;
  8521. } else {
  8522. console.warn( "animation[" + label + "] undefined" );
  8523. }
  8524. };
  8525. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  8526. var frameTime = this.duration / this.length;
  8527. this.time += this.direction * delta;
  8528. if ( this.mirroredLoop ) {
  8529. if ( this.time > this.duration || this.time < 0 ) {
  8530. this.direction *= -1;
  8531. if ( this.time > this.duration ) {
  8532. this.time = this.duration;
  8533. this.directionBackwards = true;
  8534. }
  8535. if ( this.time < 0 ) {
  8536. this.time = 0;
  8537. this.directionBackwards = false;
  8538. }
  8539. }
  8540. } else {
  8541. this.time = this.time % this.duration;
  8542. if ( this.time < 0 ) this.time += this.duration;
  8543. }
  8544. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  8545. if ( keyframe !== this.currentKeyframe ) {
  8546. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  8547. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  8548. this.morphTargetInfluences[ keyframe ] = 0;
  8549. this.lastKeyframe = this.currentKeyframe;
  8550. this.currentKeyframe = keyframe;
  8551. }
  8552. var mix = ( this.time % frameTime ) / frameTime;
  8553. if ( this.directionBackwards ) {
  8554. mix = 1 - mix;
  8555. }
  8556. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  8557. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  8558. };
  8559. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  8560. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  8561. object.duration = this.duration;
  8562. object.mirroredLoop = this.mirroredLoop;
  8563. object.time = this.time;
  8564. object.lastKeyframe = this.lastKeyframe;
  8565. object.currentKeyframe = this.currentKeyframe;
  8566. object.direction = this.direction;
  8567. object.directionBackwards = this.directionBackwards;
  8568. THREE.Mesh.prototype.clone.call( this, object );
  8569. return object;
  8570. };
  8571. /**
  8572. * @author alteredq / http://alteredqualia.com/
  8573. */
  8574. THREE.Ribbon = function ( geometry, material ) {
  8575. THREE.Object3D.call( this );
  8576. this.geometry = geometry;
  8577. this.material = material;
  8578. };
  8579. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  8580. THREE.Ribbon.prototype.clone = function ( object ) {
  8581. if ( object === undefined ) object = new THREE.Ribbon( this.geometry, this.material );
  8582. THREE.Object3D.prototype.clone.call( this, object );
  8583. return object;
  8584. };
  8585. /**
  8586. * @author mikael emtinger / http://gomo.se/
  8587. * @author alteredq / http://alteredqualia.com/
  8588. * @author mrdoob / http://mrdoob.com/
  8589. */
  8590. THREE.LOD = function () {
  8591. THREE.Object3D.call( this );
  8592. this.objects = [];
  8593. };
  8594. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  8595. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  8596. if ( distance === undefined ) distance = 0;
  8597. distance = Math.abs( distance );
  8598. for ( var l = 0; l < this.objects.length; l ++ ) {
  8599. if ( distance < this.objects[ l ].distance ) {
  8600. break;
  8601. }
  8602. }
  8603. this.objects.splice( l, 0, { distance: distance, object: object } );
  8604. this.add( object );
  8605. };
  8606. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  8607. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  8608. if ( distance < this.objects[ i ].distance ) {
  8609. break;
  8610. }
  8611. }
  8612. return this.objects[ i - 1 ].object;
  8613. };
  8614. THREE.LOD.prototype.update = function () {
  8615. var v1 = new THREE.Vector3();
  8616. var v2 = new THREE.Vector3();
  8617. return function ( camera ) {
  8618. if ( this.objects.length > 1 ) {
  8619. v1.getPositionFromMatrix( camera.matrixWorld );
  8620. v2.getPositionFromMatrix( this.matrixWorld );
  8621. var distance = v1.distanceTo( v2 );
  8622. this.objects[ 0 ].object.visible = true;
  8623. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  8624. if ( distance >= this.objects[ i ].distance ) {
  8625. this.objects[ i - 1 ].object.visible = false;
  8626. this.objects[ i ].object.visible = true;
  8627. } else {
  8628. break;
  8629. }
  8630. }
  8631. for( ; i < l; i ++ ) {
  8632. this.objects[ i ].object.visible = false;
  8633. }
  8634. }
  8635. };
  8636. }();
  8637. THREE.LOD.prototype.clone = function () {
  8638. // TODO
  8639. };
  8640. /**
  8641. * @author mikael emtinger / http://gomo.se/
  8642. * @author alteredq / http://alteredqualia.com/
  8643. */
  8644. THREE.Sprite = function ( material ) {
  8645. THREE.Object3D.call( this );
  8646. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  8647. this.rotation3d = this.rotation;
  8648. this.rotation = 0;
  8649. };
  8650. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  8651. /*
  8652. * Custom update matrix
  8653. */
  8654. THREE.Sprite.prototype.updateMatrix = function () {
  8655. this.rotation3d.set( 0, 0, this.rotation, this.rotation3d.order );
  8656. this.quaternion.setFromEuler( this.rotation3d );
  8657. this.matrix.makeFromPositionQuaternionScale( this.position, this.quaternion, this.scale );
  8658. this.matrixWorldNeedsUpdate = true;
  8659. };
  8660. THREE.Sprite.prototype.clone = function ( object ) {
  8661. if ( object === undefined ) object = new THREE.Sprite( this.material );
  8662. THREE.Object3D.prototype.clone.call( this, object );
  8663. return object;
  8664. };
  8665. /**
  8666. * @author mrdoob / http://mrdoob.com/
  8667. */
  8668. THREE.Scene = function () {
  8669. THREE.Object3D.call( this );
  8670. this.fog = null;
  8671. this.overrideMaterial = null;
  8672. this.autoUpdate = true; // checked by the renderer
  8673. this.matrixAutoUpdate = false;
  8674. this.__objects = [];
  8675. this.__lights = [];
  8676. this.__objectsAdded = [];
  8677. this.__objectsRemoved = [];
  8678. };
  8679. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  8680. THREE.Scene.prototype.__addObject = function ( object ) {
  8681. if ( object instanceof THREE.Light ) {
  8682. if ( this.__lights.indexOf( object ) === - 1 ) {
  8683. this.__lights.push( object );
  8684. }
  8685. if ( object.target && object.target.parent === undefined ) {
  8686. this.add( object.target );
  8687. }
  8688. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  8689. if ( this.__objects.indexOf( object ) === - 1 ) {
  8690. this.__objects.push( object );
  8691. this.__objectsAdded.push( object );
  8692. // check if previously removed
  8693. var i = this.__objectsRemoved.indexOf( object );
  8694. if ( i !== -1 ) {
  8695. this.__objectsRemoved.splice( i, 1 );
  8696. }
  8697. }
  8698. }
  8699. for ( var c = 0; c < object.children.length; c ++ ) {
  8700. this.__addObject( object.children[ c ] );
  8701. }
  8702. };
  8703. THREE.Scene.prototype.__removeObject = function ( object ) {
  8704. if ( object instanceof THREE.Light ) {
  8705. var i = this.__lights.indexOf( object );
  8706. if ( i !== -1 ) {
  8707. this.__lights.splice( i, 1 );
  8708. }
  8709. } else if ( !( object instanceof THREE.Camera ) ) {
  8710. var i = this.__objects.indexOf( object );
  8711. if( i !== -1 ) {
  8712. this.__objects.splice( i, 1 );
  8713. this.__objectsRemoved.push( object );
  8714. // check if previously added
  8715. var ai = this.__objectsAdded.indexOf( object );
  8716. if ( ai !== -1 ) {
  8717. this.__objectsAdded.splice( ai, 1 );
  8718. }
  8719. }
  8720. }
  8721. for ( var c = 0; c < object.children.length; c ++ ) {
  8722. this.__removeObject( object.children[ c ] );
  8723. }
  8724. };
  8725. THREE.Scene.prototype.clone = function ( object ) {
  8726. if ( object === undefined ) object = new THREE.Scene();
  8727. THREE.Object3D.prototype.clone.call(this, object);
  8728. if ( this.fog !== null ) object.fog = this.fog.clone();
  8729. if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone();
  8730. object.autoUpdate = this.autoUpdate;
  8731. object.matrixAutoUpdate = this.matrixAutoUpdate;
  8732. return object;
  8733. };
  8734. /**
  8735. * @author mrdoob / http://mrdoob.com/
  8736. * @author alteredq / http://alteredqualia.com/
  8737. */
  8738. THREE.Fog = function ( hex, near, far ) {
  8739. this.name = '';
  8740. this.color = new THREE.Color( hex );
  8741. this.near = ( near !== undefined ) ? near : 1;
  8742. this.far = ( far !== undefined ) ? far : 1000;
  8743. };
  8744. THREE.Fog.prototype.clone = function () {
  8745. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  8746. };
  8747. /**
  8748. * @author mrdoob / http://mrdoob.com/
  8749. * @author alteredq / http://alteredqualia.com/
  8750. */
  8751. THREE.FogExp2 = function ( hex, density ) {
  8752. this.name = '';
  8753. this.color = new THREE.Color( hex );
  8754. this.density = ( density !== undefined ) ? density : 0.00025;
  8755. };
  8756. THREE.FogExp2.prototype.clone = function () {
  8757. return new THREE.FogExp2( this.color.getHex(), this.density );
  8758. };
  8759. /**
  8760. * @author mrdoob / http://mrdoob.com/
  8761. */
  8762. THREE.CanvasRenderer = function ( parameters ) {
  8763. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  8764. var smoothstep = THREE.Math.smoothstep;
  8765. parameters = parameters || {};
  8766. var _this = this,
  8767. _renderData, _elements, _lights,
  8768. _projector = new THREE.Projector(),
  8769. _canvas = parameters.canvas !== undefined
  8770. ? parameters.canvas
  8771. : document.createElement( 'canvas' ),
  8772. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  8773. _context = _canvas.getContext( '2d' ),
  8774. _clearColor = new THREE.Color( 0x000000 ),
  8775. _clearAlpha = 0,
  8776. _contextGlobalAlpha = 1,
  8777. _contextGlobalCompositeOperation = 0,
  8778. _contextStrokeStyle = null,
  8779. _contextFillStyle = null,
  8780. _contextLineWidth = null,
  8781. _contextLineCap = null,
  8782. _contextLineJoin = null,
  8783. _contextDashSize = null,
  8784. _contextGapSize = 0,
  8785. _camera,
  8786. _v1, _v2, _v3, _v4,
  8787. _v5 = new THREE.RenderableVertex(),
  8788. _v6 = new THREE.RenderableVertex(),
  8789. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  8790. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  8791. _color = new THREE.Color(),
  8792. _color1 = new THREE.Color(),
  8793. _color2 = new THREE.Color(),
  8794. _color3 = new THREE.Color(),
  8795. _color4 = new THREE.Color(),
  8796. _diffuseColor = new THREE.Color(),
  8797. _emissiveColor = new THREE.Color(),
  8798. _lightColor = new THREE.Color(),
  8799. _patterns = {}, _imagedatas = {},
  8800. _near, _far,
  8801. _image, _uvs,
  8802. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  8803. _clipBox = new THREE.Box2(),
  8804. _clearBox = new THREE.Box2(),
  8805. _elemBox = new THREE.Box2(),
  8806. _ambientLight = new THREE.Color(),
  8807. _directionalLights = new THREE.Color(),
  8808. _pointLights = new THREE.Color(),
  8809. _vector3 = new THREE.Vector3(), // Needed for PointLight
  8810. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  8811. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  8812. _pixelMap = document.createElement( 'canvas' );
  8813. _pixelMap.width = _pixelMap.height = 2;
  8814. _pixelMapContext = _pixelMap.getContext( '2d' );
  8815. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  8816. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  8817. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  8818. _pixelMapData = _pixelMapImage.data;
  8819. _gradientMap = document.createElement( 'canvas' );
  8820. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  8821. _gradientMapContext = _gradientMap.getContext( '2d' );
  8822. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  8823. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  8824. _gradientMapQuality --; // Fix UVs
  8825. // dash+gap fallbacks for Firefox and everything else
  8826. if ( _context.setLineDash === undefined ) {
  8827. if ( _context.mozDash !== undefined ) {
  8828. _context.setLineDash = function ( values ) {
  8829. _context.mozDash = values[ 0 ] !== null ? values : null;
  8830. }
  8831. } else {
  8832. _context.setLineDash = function () {}
  8833. }
  8834. }
  8835. this.domElement = _canvas;
  8836. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  8837. ? parameters.devicePixelRatio
  8838. : window.devicePixelRatio !== undefined
  8839. ? window.devicePixelRatio
  8840. : 1;
  8841. this.autoClear = true;
  8842. this.sortObjects = true;
  8843. this.sortElements = true;
  8844. this.info = {
  8845. render: {
  8846. vertices: 0,
  8847. faces: 0
  8848. }
  8849. }
  8850. // WebGLRenderer compatibility
  8851. this.supportsVertexTextures = function () {};
  8852. this.setFaceCulling = function () {};
  8853. this.setSize = function ( width, height, updateStyle ) {
  8854. _canvasWidth = width * this.devicePixelRatio;
  8855. _canvasHeight = height * this.devicePixelRatio;
  8856. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  8857. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  8858. _canvas.width = _canvasWidth;
  8859. _canvas.height = _canvasHeight;
  8860. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  8861. _canvas.style.width = width + 'px';
  8862. _canvas.style.height = height + 'px';
  8863. }
  8864. _clipBox.set(
  8865. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8866. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8867. );
  8868. _clearBox.set(
  8869. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8870. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8871. );
  8872. _contextGlobalAlpha = 1;
  8873. _contextGlobalCompositeOperation = 0;
  8874. _contextStrokeStyle = null;
  8875. _contextFillStyle = null;
  8876. _contextLineWidth = null;
  8877. _contextLineCap = null;
  8878. _contextLineJoin = null;
  8879. };
  8880. this.setClearColor = function ( color, alpha ) {
  8881. _clearColor.set( color );
  8882. _clearAlpha = alpha !== undefined ? alpha : 1;
  8883. _clearBox.set(
  8884. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8885. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8886. );
  8887. };
  8888. this.setClearColorHex = function ( hex, alpha ) {
  8889. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  8890. this.setClearColor( hex, alpha );
  8891. };
  8892. this.getMaxAnisotropy = function () {
  8893. return 0;
  8894. };
  8895. this.clear = function () {
  8896. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8897. if ( _clearBox.empty() === false ) {
  8898. _clearBox.intersect( _clipBox );
  8899. _clearBox.expandByScalar( 2 );
  8900. if ( _clearAlpha < 1 ) {
  8901. _context.clearRect(
  8902. _clearBox.min.x | 0,
  8903. _clearBox.min.y | 0,
  8904. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  8905. ( _clearBox.max.y - _clearBox.min.y ) | 0
  8906. );
  8907. }
  8908. if ( _clearAlpha > 0 ) {
  8909. setBlending( THREE.NormalBlending );
  8910. setOpacity( 1 );
  8911. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearAlpha + ')' );
  8912. _context.fillRect(
  8913. _clearBox.min.x | 0,
  8914. _clearBox.min.y | 0,
  8915. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  8916. ( _clearBox.max.y - _clearBox.min.y ) | 0
  8917. );
  8918. }
  8919. _clearBox.makeEmpty();
  8920. }
  8921. };
  8922. this.render = function ( scene, camera ) {
  8923. if ( camera instanceof THREE.Camera === false ) {
  8924. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  8925. return;
  8926. }
  8927. if ( this.autoClear === true ) this.clear();
  8928. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8929. _this.info.render.vertices = 0;
  8930. _this.info.render.faces = 0;
  8931. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  8932. _elements = _renderData.elements;
  8933. _lights = _renderData.lights;
  8934. _camera = camera;
  8935. /* DEBUG
  8936. setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
  8937. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  8938. */
  8939. calculateLights();
  8940. for ( var e = 0, el = _elements.length; e < el; e++ ) {
  8941. var element = _elements[ e ];
  8942. var material = element.material;
  8943. if ( material === undefined || material.visible === false ) continue;
  8944. _elemBox.makeEmpty();
  8945. if ( element instanceof THREE.RenderableParticle ) {
  8946. _v1 = element;
  8947. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  8948. renderParticle( _v1, element, material );
  8949. } else if ( element instanceof THREE.RenderableLine ) {
  8950. _v1 = element.v1; _v2 = element.v2;
  8951. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8952. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8953. _elemBox.setFromPoints( [
  8954. _v1.positionScreen,
  8955. _v2.positionScreen
  8956. ] );
  8957. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8958. renderLine( _v1, _v2, element, material );
  8959. }
  8960. } else if ( element instanceof THREE.RenderableFace3 ) {
  8961. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  8962. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  8963. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  8964. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  8965. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8966. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8967. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8968. if ( material.overdraw > 0 ) {
  8969. expand( _v1.positionScreen, _v2.positionScreen, material.overdraw );
  8970. expand( _v2.positionScreen, _v3.positionScreen, material.overdraw );
  8971. expand( _v3.positionScreen, _v1.positionScreen, material.overdraw );
  8972. }
  8973. _elemBox.setFromPoints( [
  8974. _v1.positionScreen,
  8975. _v2.positionScreen,
  8976. _v3.positionScreen
  8977. ] );
  8978. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8979. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material );
  8980. }
  8981. } else if ( element instanceof THREE.RenderableFace4 ) {
  8982. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  8983. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  8984. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  8985. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  8986. if ( _v4.positionScreen.z < -1 || _v4.positionScreen.z > 1 ) continue;
  8987. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8988. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8989. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8990. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  8991. _v5.positionScreen.copy( _v2.positionScreen );
  8992. _v6.positionScreen.copy( _v4.positionScreen );
  8993. if ( material.overdraw > 0 ) {
  8994. expand( _v1.positionScreen, _v2.positionScreen, material.overdraw );
  8995. expand( _v2.positionScreen, _v4.positionScreen, material.overdraw );
  8996. expand( _v4.positionScreen, _v1.positionScreen, material.overdraw );
  8997. expand( _v3.positionScreen, _v5.positionScreen, material.overdraw );
  8998. expand( _v3.positionScreen, _v6.positionScreen, material.overdraw );
  8999. }
  9000. _elemBox.setFromPoints( [
  9001. _v1.positionScreen,
  9002. _v2.positionScreen,
  9003. _v3.positionScreen,
  9004. _v4.positionScreen
  9005. ] );
  9006. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  9007. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material );
  9008. }
  9009. }
  9010. /* DEBUG
  9011. setLineWidth( 1 );
  9012. setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
  9013. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  9014. */
  9015. _clearBox.union( _elemBox );
  9016. }
  9017. /* DEBUG
  9018. setLineWidth( 1 );
  9019. setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
  9020. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  9021. */
  9022. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  9023. };
  9024. //
  9025. function calculateLights() {
  9026. _ambientLight.setRGB( 0, 0, 0 );
  9027. _directionalLights.setRGB( 0, 0, 0 );
  9028. _pointLights.setRGB( 0, 0, 0 );
  9029. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9030. var light = _lights[ l ];
  9031. var lightColor = light.color;
  9032. if ( light instanceof THREE.AmbientLight ) {
  9033. _ambientLight.add( lightColor );
  9034. } else if ( light instanceof THREE.DirectionalLight ) {
  9035. // for particles
  9036. _directionalLights.add( lightColor );
  9037. } else if ( light instanceof THREE.PointLight ) {
  9038. // for particles
  9039. _pointLights.add( lightColor );
  9040. }
  9041. }
  9042. }
  9043. function calculateLight( position, normal, color ) {
  9044. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9045. var light = _lights[ l ];
  9046. _lightColor.copy( light.color );
  9047. if ( light instanceof THREE.DirectionalLight ) {
  9048. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld ).normalize();
  9049. var amount = normal.dot( lightPosition );
  9050. if ( amount <= 0 ) continue;
  9051. amount *= light.intensity;
  9052. color.add( _lightColor.multiplyScalar( amount ) );
  9053. } else if ( light instanceof THREE.PointLight ) {
  9054. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld );
  9055. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  9056. if ( amount <= 0 ) continue;
  9057. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  9058. if ( amount == 0 ) continue;
  9059. amount *= light.intensity;
  9060. color.add( _lightColor.multiplyScalar( amount ) );
  9061. }
  9062. }
  9063. }
  9064. function renderParticle( v1, element, material ) {
  9065. setOpacity( material.opacity );
  9066. setBlending( material.blending );
  9067. var width, height, scaleX, scaleY,
  9068. bitmap, bitmapWidth, bitmapHeight;
  9069. if ( material instanceof THREE.ParticleBasicMaterial ) {
  9070. if ( material.map === null ) {
  9071. scaleX = element.object.scale.x;
  9072. scaleY = element.object.scale.y;
  9073. // TODO: Be able to disable this
  9074. scaleX *= element.scale.x * _canvasWidthHalf;
  9075. scaleY *= element.scale.y * _canvasHeightHalf;
  9076. _elemBox.min.set( v1.x - scaleX, v1.y - scaleY );
  9077. _elemBox.max.set( v1.x + scaleX, v1.y + scaleY );
  9078. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  9079. _elemBox.makeEmpty();
  9080. return;
  9081. }
  9082. setFillStyle( material.color.getStyle() );
  9083. _context.save();
  9084. _context.translate( v1.x, v1.y );
  9085. _context.rotate( - element.rotation );
  9086. _context.scale( scaleX, scaleY );
  9087. _context.fillRect( -1, -1, 2, 2 );
  9088. _context.restore();
  9089. } else {
  9090. bitmap = material.map.image;
  9091. bitmapWidth = bitmap.width >> 1;
  9092. bitmapHeight = bitmap.height >> 1;
  9093. scaleX = element.scale.x * _canvasWidthHalf;
  9094. scaleY = element.scale.y * _canvasHeightHalf;
  9095. width = scaleX * bitmapWidth;
  9096. height = scaleY * bitmapHeight;
  9097. // TODO: Rotations break this...
  9098. _elemBox.min.set( v1.x - width, v1.y - height );
  9099. _elemBox.max.set( v1.x + width, v1.y + height );
  9100. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  9101. _elemBox.makeEmpty();
  9102. return;
  9103. }
  9104. _context.save();
  9105. _context.translate( v1.x, v1.y );
  9106. _context.rotate( - element.rotation );
  9107. _context.scale( scaleX, - scaleY );
  9108. _context.translate( - bitmapWidth, - bitmapHeight );
  9109. _context.drawImage( bitmap, 0, 0 );
  9110. _context.restore();
  9111. }
  9112. /* DEBUG
  9113. setStrokeStyle( 'rgb(255,255,0)' );
  9114. _context.beginPath();
  9115. _context.moveTo( v1.x - 10, v1.y );
  9116. _context.lineTo( v1.x + 10, v1.y );
  9117. _context.moveTo( v1.x, v1.y - 10 );
  9118. _context.lineTo( v1.x, v1.y + 10 );
  9119. _context.stroke();
  9120. */
  9121. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  9122. width = element.scale.x * _canvasWidthHalf;
  9123. height = element.scale.y * _canvasHeightHalf;
  9124. _elemBox.min.set( v1.x - width, v1.y - height );
  9125. _elemBox.max.set( v1.x + width, v1.y + height );
  9126. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  9127. _elemBox.makeEmpty();
  9128. return;
  9129. }
  9130. setStrokeStyle( material.color.getStyle() );
  9131. setFillStyle( material.color.getStyle() );
  9132. _context.save();
  9133. _context.translate( v1.x, v1.y );
  9134. _context.rotate( - element.rotation );
  9135. _context.scale( width, height );
  9136. material.program( _context );
  9137. _context.restore();
  9138. }
  9139. }
  9140. function renderLine( v1, v2, element, material ) {
  9141. setOpacity( material.opacity );
  9142. setBlending( material.blending );
  9143. _context.beginPath();
  9144. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  9145. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  9146. if ( material instanceof THREE.LineBasicMaterial ) {
  9147. setLineWidth( material.linewidth );
  9148. setLineCap( material.linecap );
  9149. setLineJoin( material.linejoin );
  9150. if ( material.vertexColors !== THREE.VertexColors ) {
  9151. setStrokeStyle( material.color.getStyle() );
  9152. } else {
  9153. var colorStyle1 = element.vertexColors[0].getStyle();
  9154. var colorStyle2 = element.vertexColors[1].getStyle();
  9155. if ( colorStyle1 === colorStyle2 ) {
  9156. setStrokeStyle( colorStyle1 );
  9157. } else {
  9158. try {
  9159. var grad = _context.createLinearGradient(
  9160. v1.positionScreen.x,
  9161. v1.positionScreen.y,
  9162. v2.positionScreen.x,
  9163. v2.positionScreen.y
  9164. );
  9165. grad.addColorStop( 0, colorStyle1 );
  9166. grad.addColorStop( 1, colorStyle2 );
  9167. } catch ( exception ) {
  9168. grad = colorStyle1;
  9169. }
  9170. setStrokeStyle( grad );
  9171. }
  9172. }
  9173. _context.stroke();
  9174. _elemBox.expandByScalar( material.linewidth * 2 );
  9175. } else if ( material instanceof THREE.LineDashedMaterial ) {
  9176. setLineWidth( material.linewidth );
  9177. setLineCap( material.linecap );
  9178. setLineJoin( material.linejoin );
  9179. setStrokeStyle( material.color.getStyle() );
  9180. setDashAndGap( material.dashSize, material.gapSize );
  9181. _context.stroke();
  9182. _elemBox.expandByScalar( material.linewidth * 2 );
  9183. setDashAndGap( null, null );
  9184. }
  9185. }
  9186. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material ) {
  9187. _this.info.render.vertices += 3;
  9188. _this.info.render.faces ++;
  9189. setOpacity( material.opacity );
  9190. setBlending( material.blending );
  9191. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  9192. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  9193. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  9194. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  9195. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) {
  9196. _diffuseColor.copy( material.color );
  9197. _emissiveColor.copy( material.emissive );
  9198. if ( material.vertexColors === THREE.FaceColors ) {
  9199. _diffuseColor.multiply( element.color );
  9200. }
  9201. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  9202. _color1.copy( _ambientLight );
  9203. _color2.copy( _ambientLight );
  9204. _color3.copy( _ambientLight );
  9205. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  9206. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  9207. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color3 );
  9208. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  9209. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  9210. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  9211. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9212. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9213. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9214. } else {
  9215. _color.copy( _ambientLight );
  9216. calculateLight( element.centroidModel, element.normalModel, _color );
  9217. _color.multiply( _diffuseColor ).add( _emissiveColor );
  9218. material.wireframe === true
  9219. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9220. : fillPath( _color );
  9221. }
  9222. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  9223. if ( material.map !== null ) {
  9224. if ( material.map.mapping instanceof THREE.UVMapping ) {
  9225. _uvs = element.uvs[ 0 ];
  9226. 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 );
  9227. }
  9228. } else if ( material.envMap !== null ) {
  9229. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  9230. _vector3.copy( element.vertexNormalsModelView[ uv1 ] );
  9231. _uv1x = 0.5 * _vector3.x + 0.5;
  9232. _uv1y = 0.5 * _vector3.y + 0.5;
  9233. _vector3.copy( element.vertexNormalsModelView[ uv2 ] );
  9234. _uv2x = 0.5 * _vector3.x + 0.5;
  9235. _uv2y = 0.5 * _vector3.y + 0.5;
  9236. _vector3.copy( element.vertexNormalsModelView[ uv3 ] );
  9237. _uv3x = 0.5 * _vector3.x + 0.5;
  9238. _uv3y = 0.5 * _vector3.y + 0.5;
  9239. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  9240. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  9241. }*/
  9242. } else {
  9243. _color.copy( material.color );
  9244. if ( material.vertexColors === THREE.FaceColors ) {
  9245. _color.multiply( element.color );
  9246. }
  9247. material.wireframe === true
  9248. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9249. : fillPath( _color );
  9250. }
  9251. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  9252. _near = _camera.near;
  9253. _far = _camera.far;
  9254. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  9255. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  9256. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  9257. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9258. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9259. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9260. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  9261. var normal;
  9262. if ( material.shading == THREE.FlatShading ) {
  9263. normal = element.normalModelView;
  9264. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9265. material.wireframe === true
  9266. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9267. : fillPath( _color );
  9268. } else if ( material.shading == THREE.SmoothShading ) {
  9269. normal = element.vertexNormalsModelView[ uv1 ];
  9270. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9271. normal = element.vertexNormalsModelView[ uv2 ];
  9272. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9273. normal = element.vertexNormalsModelView[ uv3 ];
  9274. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9275. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9276. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9277. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9278. }
  9279. }
  9280. }
  9281. function renderFace4( v1, v2, v3, v4, v5, v6, element, material ) {
  9282. _this.info.render.vertices += 4;
  9283. _this.info.render.faces ++;
  9284. setOpacity( material.opacity );
  9285. setBlending( material.blending );
  9286. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  9287. // Let renderFace3() handle this
  9288. renderFace3( v1, v2, v4, 0, 1, 3, element, material );
  9289. renderFace3( v5, v3, v6, 1, 2, 3, element, material );
  9290. return;
  9291. }
  9292. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  9293. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  9294. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  9295. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  9296. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  9297. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  9298. if ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  9299. _diffuseColor.copy( material.color );
  9300. _emissiveColor.copy( material.emissive );
  9301. if ( material.vertexColors === THREE.FaceColors ) {
  9302. _diffuseColor.multiply( element.color );
  9303. }
  9304. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  9305. _color1.copy( _ambientLight );
  9306. _color2.copy( _ambientLight );
  9307. _color3.copy( _ambientLight );
  9308. _color4.copy( _ambientLight );
  9309. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  9310. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  9311. calculateLight( element.v4.positionWorld, element.vertexNormalsModel[ 3 ], _color3 );
  9312. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color4 );
  9313. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  9314. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  9315. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  9316. _color4.multiply( _diffuseColor ).add( _emissiveColor );
  9317. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9318. // TODO: UVs are incorrect, v4->v3?
  9319. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  9320. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  9321. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  9322. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  9323. } else {
  9324. _color.copy( _ambientLight );
  9325. calculateLight( element.centroidModel, element.normalModel, _color );
  9326. _color.multiply( _diffuseColor ).add( _emissiveColor );
  9327. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  9328. material.wireframe === true
  9329. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9330. : fillPath( _color );
  9331. }
  9332. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  9333. _color.copy( material.color );
  9334. if ( material.vertexColors === THREE.FaceColors ) {
  9335. _color.multiply( element.color );
  9336. }
  9337. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  9338. material.wireframe === true
  9339. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9340. : fillPath( _color );
  9341. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  9342. var normal;
  9343. if ( material.shading == THREE.FlatShading ) {
  9344. normal = element.normalModelView;
  9345. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9346. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  9347. material.wireframe === true
  9348. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9349. : fillPath( _color );
  9350. } else if ( material.shading == THREE.SmoothShading ) {
  9351. normal = element.vertexNormalsModelView[ 0 ];
  9352. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9353. normal = element.vertexNormalsModelView[ 1 ];
  9354. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9355. normal = element.vertexNormalsModelView[ 3 ];
  9356. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9357. normal = element.vertexNormalsModelView[ 2 ];
  9358. _color4.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9359. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9360. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  9361. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  9362. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  9363. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  9364. }
  9365. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  9366. _near = _camera.near;
  9367. _far = _camera.far;
  9368. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  9369. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  9370. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z * v4.positionScreen.w, _near, _far );
  9371. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  9372. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9373. // TODO: UVs are incorrect, v4->v3?
  9374. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  9375. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  9376. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  9377. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  9378. }
  9379. }
  9380. //
  9381. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  9382. _context.beginPath();
  9383. _context.moveTo( x0, y0 );
  9384. _context.lineTo( x1, y1 );
  9385. _context.lineTo( x2, y2 );
  9386. _context.closePath();
  9387. }
  9388. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  9389. _context.beginPath();
  9390. _context.moveTo( x0, y0 );
  9391. _context.lineTo( x1, y1 );
  9392. _context.lineTo( x2, y2 );
  9393. _context.lineTo( x3, y3 );
  9394. _context.closePath();
  9395. }
  9396. function strokePath( color, linewidth, linecap, linejoin ) {
  9397. setLineWidth( linewidth );
  9398. setLineCap( linecap );
  9399. setLineJoin( linejoin );
  9400. setStrokeStyle( color.getStyle() );
  9401. _context.stroke();
  9402. _elemBox.expandByScalar( linewidth * 2 );
  9403. }
  9404. function fillPath( color ) {
  9405. setFillStyle( color.getStyle() );
  9406. _context.fill();
  9407. }
  9408. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  9409. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  9410. if ( texture.needsUpdate === true ) {
  9411. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  9412. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  9413. _patterns[ texture.id ] = _context.createPattern(
  9414. texture.image, repeatX === true && repeatY === true
  9415. ? 'repeat'
  9416. : repeatX === true && repeatY === false
  9417. ? 'repeat-x'
  9418. : repeatX === false && repeatY === true
  9419. ? 'repeat-y'
  9420. : 'no-repeat'
  9421. );
  9422. texture.needsUpdate = false;
  9423. }
  9424. _patterns[ texture.id ] === undefined
  9425. ? setFillStyle( 'rgba(0,0,0,1)' )
  9426. : setFillStyle( _patterns[ texture.id ] );
  9427. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9428. var a, b, c, d, e, f, det, idet,
  9429. offsetX = texture.offset.x / texture.repeat.x,
  9430. offsetY = texture.offset.y / texture.repeat.y,
  9431. width = texture.image.width * texture.repeat.x,
  9432. height = texture.image.height * texture.repeat.y;
  9433. u0 = ( u0 + offsetX ) * width;
  9434. v0 = ( 1.0 - v0 + offsetY ) * height;
  9435. u1 = ( u1 + offsetX ) * width;
  9436. v1 = ( 1.0 - v1 + offsetY ) * height;
  9437. u2 = ( u2 + offsetX ) * width;
  9438. v2 = ( 1.0 - v2 + offsetY ) * height;
  9439. x1 -= x0; y1 -= y0;
  9440. x2 -= x0; y2 -= y0;
  9441. u1 -= u0; v1 -= v0;
  9442. u2 -= u0; v2 -= v0;
  9443. det = u1 * v2 - u2 * v1;
  9444. if ( det === 0 ) {
  9445. if ( _imagedatas[ texture.id ] === undefined ) {
  9446. var canvas = document.createElement( 'canvas' )
  9447. canvas.width = texture.image.width;
  9448. canvas.height = texture.image.height;
  9449. var context = canvas.getContext( '2d' );
  9450. context.drawImage( texture.image, 0, 0 );
  9451. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  9452. }
  9453. var data = _imagedatas[ texture.id ];
  9454. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  9455. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  9456. fillPath( _color );
  9457. return;
  9458. }
  9459. idet = 1 / det;
  9460. a = ( v2 * x1 - v1 * x2 ) * idet;
  9461. b = ( v2 * y1 - v1 * y2 ) * idet;
  9462. c = ( u1 * x2 - u2 * x1 ) * idet;
  9463. d = ( u1 * y2 - u2 * y1 ) * idet;
  9464. e = x0 - a * u0 - c * v0;
  9465. f = y0 - b * u0 - d * v0;
  9466. _context.save();
  9467. _context.transform( a, b, c, d, e, f );
  9468. _context.fill();
  9469. _context.restore();
  9470. }
  9471. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  9472. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9473. var a, b, c, d, e, f, det, idet,
  9474. width = image.width - 1,
  9475. height = image.height - 1;
  9476. u0 *= width; v0 *= height;
  9477. u1 *= width; v1 *= height;
  9478. u2 *= width; v2 *= height;
  9479. x1 -= x0; y1 -= y0;
  9480. x2 -= x0; y2 -= y0;
  9481. u1 -= u0; v1 -= v0;
  9482. u2 -= u0; v2 -= v0;
  9483. det = u1 * v2 - u2 * v1;
  9484. idet = 1 / det;
  9485. a = ( v2 * x1 - v1 * x2 ) * idet;
  9486. b = ( v2 * y1 - v1 * y2 ) * idet;
  9487. c = ( u1 * x2 - u2 * x1 ) * idet;
  9488. d = ( u1 * y2 - u2 * y1 ) * idet;
  9489. e = x0 - a * u0 - c * v0;
  9490. f = y0 - b * u0 - d * v0;
  9491. _context.save();
  9492. _context.transform( a, b, c, d, e, f );
  9493. _context.clip();
  9494. _context.drawImage( image, 0, 0 );
  9495. _context.restore();
  9496. }
  9497. function getGradientTexture( color1, color2, color3, color4 ) {
  9498. // http://mrdoob.com/blog/post/710
  9499. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  9500. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  9501. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  9502. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  9503. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  9504. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  9505. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  9506. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  9507. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  9508. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  9509. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  9510. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  9511. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  9512. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  9513. return _gradientMap;
  9514. }
  9515. // Hide anti-alias gaps
  9516. function expand( v1, v2, pixels ) {
  9517. var x = v2.x - v1.x, y = v2.y - v1.y,
  9518. det = x * x + y * y, idet;
  9519. if ( det === 0 ) return;
  9520. idet = pixels / Math.sqrt( det );
  9521. x *= idet; y *= idet;
  9522. v2.x += x; v2.y += y;
  9523. v1.x -= x; v1.y -= y;
  9524. }
  9525. // Context cached methods.
  9526. function setOpacity( value ) {
  9527. if ( _contextGlobalAlpha !== value ) {
  9528. _context.globalAlpha = value;
  9529. _contextGlobalAlpha = value;
  9530. }
  9531. }
  9532. function setBlending( value ) {
  9533. if ( _contextGlobalCompositeOperation !== value ) {
  9534. if ( value === THREE.NormalBlending ) {
  9535. _context.globalCompositeOperation = 'source-over';
  9536. } else if ( value === THREE.AdditiveBlending ) {
  9537. _context.globalCompositeOperation = 'lighter';
  9538. } else if ( value === THREE.SubtractiveBlending ) {
  9539. _context.globalCompositeOperation = 'darker';
  9540. }
  9541. _contextGlobalCompositeOperation = value;
  9542. }
  9543. }
  9544. function setLineWidth( value ) {
  9545. if ( _contextLineWidth !== value ) {
  9546. _context.lineWidth = value;
  9547. _contextLineWidth = value;
  9548. }
  9549. }
  9550. function setLineCap( value ) {
  9551. // "butt", "round", "square"
  9552. if ( _contextLineCap !== value ) {
  9553. _context.lineCap = value;
  9554. _contextLineCap = value;
  9555. }
  9556. }
  9557. function setLineJoin( value ) {
  9558. // "round", "bevel", "miter"
  9559. if ( _contextLineJoin !== value ) {
  9560. _context.lineJoin = value;
  9561. _contextLineJoin = value;
  9562. }
  9563. }
  9564. function setStrokeStyle( value ) {
  9565. if ( _contextStrokeStyle !== value ) {
  9566. _context.strokeStyle = value;
  9567. _contextStrokeStyle = value;
  9568. }
  9569. }
  9570. function setFillStyle( value ) {
  9571. if ( _contextFillStyle !== value ) {
  9572. _context.fillStyle = value;
  9573. _contextFillStyle = value;
  9574. }
  9575. }
  9576. function setDashAndGap( dashSizeValue, gapSizeValue ) {
  9577. if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) {
  9578. _context.setLineDash( [ dashSizeValue, gapSizeValue ] );
  9579. _contextDashSize = dashSizeValue;
  9580. _contextGapSize = gapSizeValue;
  9581. }
  9582. }
  9583. };
  9584. /**
  9585. * @author alteredq / http://alteredqualia.com/
  9586. * @author mrdoob / http://mrdoob.com/
  9587. * @author mikael emtinger / http://gomo.se/
  9588. */
  9589. THREE.ShaderChunk = {
  9590. // FOG
  9591. fog_pars_fragment: [
  9592. "#ifdef USE_FOG",
  9593. "uniform vec3 fogColor;",
  9594. "#ifdef FOG_EXP2",
  9595. "uniform float fogDensity;",
  9596. "#else",
  9597. "uniform float fogNear;",
  9598. "uniform float fogFar;",
  9599. "#endif",
  9600. "#endif"
  9601. ].join("\n"),
  9602. fog_fragment: [
  9603. "#ifdef USE_FOG",
  9604. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  9605. "#ifdef FOG_EXP2",
  9606. "const float LOG2 = 1.442695;",
  9607. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  9608. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  9609. "#else",
  9610. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  9611. "#endif",
  9612. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  9613. "#endif"
  9614. ].join("\n"),
  9615. // ENVIRONMENT MAP
  9616. envmap_pars_fragment: [
  9617. "#ifdef USE_ENVMAP",
  9618. "uniform float reflectivity;",
  9619. "uniform samplerCube envMap;",
  9620. "uniform float flipEnvMap;",
  9621. "uniform int combine;",
  9622. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9623. "uniform bool useRefract;",
  9624. "uniform float refractionRatio;",
  9625. "#else",
  9626. "varying vec3 vReflect;",
  9627. "#endif",
  9628. "#endif"
  9629. ].join("\n"),
  9630. envmap_fragment: [
  9631. "#ifdef USE_ENVMAP",
  9632. "vec3 reflectVec;",
  9633. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9634. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  9635. "if ( useRefract ) {",
  9636. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  9637. "} else { ",
  9638. "reflectVec = reflect( cameraToVertex, normal );",
  9639. "}",
  9640. "#else",
  9641. "reflectVec = vReflect;",
  9642. "#endif",
  9643. "#ifdef DOUBLE_SIDED",
  9644. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9645. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9646. "#else",
  9647. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9648. "#endif",
  9649. "#ifdef GAMMA_INPUT",
  9650. "cubeColor.xyz *= cubeColor.xyz;",
  9651. "#endif",
  9652. "if ( combine == 1 ) {",
  9653. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  9654. "} else if ( combine == 2 ) {",
  9655. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  9656. "} else {",
  9657. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  9658. "}",
  9659. "#endif"
  9660. ].join("\n"),
  9661. envmap_pars_vertex: [
  9662. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9663. "varying vec3 vReflect;",
  9664. "uniform float refractionRatio;",
  9665. "uniform bool useRefract;",
  9666. "#endif"
  9667. ].join("\n"),
  9668. worldpos_vertex : [
  9669. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  9670. "#ifdef USE_SKINNING",
  9671. "vec4 worldPosition = modelMatrix * skinned;",
  9672. "#endif",
  9673. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9674. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  9675. "#endif",
  9676. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9677. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  9678. "#endif",
  9679. "#endif"
  9680. ].join("\n"),
  9681. envmap_vertex : [
  9682. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9683. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  9684. "worldNormal = normalize( worldNormal );",
  9685. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  9686. "if ( useRefract ) {",
  9687. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  9688. "} else {",
  9689. "vReflect = reflect( cameraToVertex, worldNormal );",
  9690. "}",
  9691. "#endif"
  9692. ].join("\n"),
  9693. // COLOR MAP (particles)
  9694. map_particle_pars_fragment: [
  9695. "#ifdef USE_MAP",
  9696. "uniform sampler2D map;",
  9697. "#endif"
  9698. ].join("\n"),
  9699. map_particle_fragment: [
  9700. "#ifdef USE_MAP",
  9701. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  9702. "#endif"
  9703. ].join("\n"),
  9704. // COLOR MAP (triangles)
  9705. map_pars_vertex: [
  9706. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9707. "varying vec2 vUv;",
  9708. "uniform vec4 offsetRepeat;",
  9709. "#endif"
  9710. ].join("\n"),
  9711. map_pars_fragment: [
  9712. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9713. "varying vec2 vUv;",
  9714. "#endif",
  9715. "#ifdef USE_MAP",
  9716. "uniform sampler2D map;",
  9717. "#endif"
  9718. ].join("\n"),
  9719. map_vertex: [
  9720. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9721. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  9722. "#endif"
  9723. ].join("\n"),
  9724. map_fragment: [
  9725. "#ifdef USE_MAP",
  9726. "vec4 texelColor = texture2D( map, vUv );",
  9727. "#ifdef GAMMA_INPUT",
  9728. "texelColor.xyz *= texelColor.xyz;",
  9729. "#endif",
  9730. "gl_FragColor = gl_FragColor * texelColor;",
  9731. "#endif"
  9732. ].join("\n"),
  9733. // LIGHT MAP
  9734. lightmap_pars_fragment: [
  9735. "#ifdef USE_LIGHTMAP",
  9736. "varying vec2 vUv2;",
  9737. "uniform sampler2D lightMap;",
  9738. "#endif"
  9739. ].join("\n"),
  9740. lightmap_pars_vertex: [
  9741. "#ifdef USE_LIGHTMAP",
  9742. "varying vec2 vUv2;",
  9743. "#endif"
  9744. ].join("\n"),
  9745. lightmap_fragment: [
  9746. "#ifdef USE_LIGHTMAP",
  9747. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  9748. "#endif"
  9749. ].join("\n"),
  9750. lightmap_vertex: [
  9751. "#ifdef USE_LIGHTMAP",
  9752. "vUv2 = uv2;",
  9753. "#endif"
  9754. ].join("\n"),
  9755. // BUMP MAP
  9756. bumpmap_pars_fragment: [
  9757. "#ifdef USE_BUMPMAP",
  9758. "uniform sampler2D bumpMap;",
  9759. "uniform float bumpScale;",
  9760. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  9761. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  9762. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  9763. "vec2 dHdxy_fwd() {",
  9764. "vec2 dSTdx = dFdx( vUv );",
  9765. "vec2 dSTdy = dFdy( vUv );",
  9766. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  9767. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  9768. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  9769. "return vec2( dBx, dBy );",
  9770. "}",
  9771. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  9772. "vec3 vSigmaX = dFdx( surf_pos );",
  9773. "vec3 vSigmaY = dFdy( surf_pos );",
  9774. "vec3 vN = surf_norm;", // normalized
  9775. "vec3 R1 = cross( vSigmaY, vN );",
  9776. "vec3 R2 = cross( vN, vSigmaX );",
  9777. "float fDet = dot( vSigmaX, R1 );",
  9778. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  9779. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  9780. "}",
  9781. "#endif"
  9782. ].join("\n"),
  9783. // NORMAL MAP
  9784. normalmap_pars_fragment: [
  9785. "#ifdef USE_NORMALMAP",
  9786. "uniform sampler2D normalMap;",
  9787. "uniform vec2 normalScale;",
  9788. // Per-Pixel Tangent Space Normal Mapping
  9789. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  9790. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  9791. "vec3 q0 = dFdx( eye_pos.xyz );",
  9792. "vec3 q1 = dFdy( eye_pos.xyz );",
  9793. "vec2 st0 = dFdx( vUv.st );",
  9794. "vec2 st1 = dFdy( vUv.st );",
  9795. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  9796. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  9797. "vec3 N = normalize( surf_norm );",
  9798. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  9799. "mapN.xy = normalScale * mapN.xy;",
  9800. "mat3 tsn = mat3( S, T, N );",
  9801. "return normalize( tsn * mapN );",
  9802. "}",
  9803. "#endif"
  9804. ].join("\n"),
  9805. // SPECULAR MAP
  9806. specularmap_pars_fragment: [
  9807. "#ifdef USE_SPECULARMAP",
  9808. "uniform sampler2D specularMap;",
  9809. "#endif"
  9810. ].join("\n"),
  9811. specularmap_fragment: [
  9812. "float specularStrength;",
  9813. "#ifdef USE_SPECULARMAP",
  9814. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  9815. "specularStrength = texelSpecular.r;",
  9816. "#else",
  9817. "specularStrength = 1.0;",
  9818. "#endif"
  9819. ].join("\n"),
  9820. // LIGHTS LAMBERT
  9821. lights_lambert_pars_vertex: [
  9822. "uniform vec3 ambient;",
  9823. "uniform vec3 diffuse;",
  9824. "uniform vec3 emissive;",
  9825. "uniform vec3 ambientLightColor;",
  9826. "#if MAX_DIR_LIGHTS > 0",
  9827. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9828. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9829. "#endif",
  9830. "#if MAX_HEMI_LIGHTS > 0",
  9831. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9832. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9833. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9834. "#endif",
  9835. "#if MAX_POINT_LIGHTS > 0",
  9836. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9837. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9838. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9839. "#endif",
  9840. "#if MAX_SPOT_LIGHTS > 0",
  9841. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9842. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9843. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9844. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9845. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9846. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9847. "#endif",
  9848. "#ifdef WRAP_AROUND",
  9849. "uniform vec3 wrapRGB;",
  9850. "#endif"
  9851. ].join("\n"),
  9852. lights_lambert_vertex: [
  9853. "vLightFront = vec3( 0.0 );",
  9854. "#ifdef DOUBLE_SIDED",
  9855. "vLightBack = vec3( 0.0 );",
  9856. "#endif",
  9857. "transformedNormal = normalize( transformedNormal );",
  9858. "#if MAX_DIR_LIGHTS > 0",
  9859. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9860. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9861. "vec3 dirVector = normalize( lDirection.xyz );",
  9862. "float dotProduct = dot( transformedNormal, dirVector );",
  9863. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9864. "#ifdef DOUBLE_SIDED",
  9865. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9866. "#ifdef WRAP_AROUND",
  9867. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9868. "#endif",
  9869. "#endif",
  9870. "#ifdef WRAP_AROUND",
  9871. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9872. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  9873. "#ifdef DOUBLE_SIDED",
  9874. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  9875. "#endif",
  9876. "#endif",
  9877. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  9878. "#ifdef DOUBLE_SIDED",
  9879. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  9880. "#endif",
  9881. "}",
  9882. "#endif",
  9883. "#if MAX_POINT_LIGHTS > 0",
  9884. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9885. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9886. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9887. "float lDistance = 1.0;",
  9888. "if ( pointLightDistance[ i ] > 0.0 )",
  9889. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9890. "lVector = normalize( lVector );",
  9891. "float dotProduct = dot( transformedNormal, lVector );",
  9892. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9893. "#ifdef DOUBLE_SIDED",
  9894. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9895. "#ifdef WRAP_AROUND",
  9896. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9897. "#endif",
  9898. "#endif",
  9899. "#ifdef WRAP_AROUND",
  9900. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9901. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  9902. "#ifdef DOUBLE_SIDED",
  9903. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  9904. "#endif",
  9905. "#endif",
  9906. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  9907. "#ifdef DOUBLE_SIDED",
  9908. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  9909. "#endif",
  9910. "}",
  9911. "#endif",
  9912. "#if MAX_SPOT_LIGHTS > 0",
  9913. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9914. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9915. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9916. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  9917. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9918. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9919. "float lDistance = 1.0;",
  9920. "if ( spotLightDistance[ i ] > 0.0 )",
  9921. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9922. "lVector = normalize( lVector );",
  9923. "float dotProduct = dot( transformedNormal, lVector );",
  9924. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9925. "#ifdef DOUBLE_SIDED",
  9926. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9927. "#ifdef WRAP_AROUND",
  9928. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9929. "#endif",
  9930. "#endif",
  9931. "#ifdef WRAP_AROUND",
  9932. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9933. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  9934. "#ifdef DOUBLE_SIDED",
  9935. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  9936. "#endif",
  9937. "#endif",
  9938. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  9939. "#ifdef DOUBLE_SIDED",
  9940. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  9941. "#endif",
  9942. "}",
  9943. "}",
  9944. "#endif",
  9945. "#if MAX_HEMI_LIGHTS > 0",
  9946. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9947. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9948. "vec3 lVector = normalize( lDirection.xyz );",
  9949. "float dotProduct = dot( transformedNormal, lVector );",
  9950. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9951. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  9952. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9953. "#ifdef DOUBLE_SIDED",
  9954. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  9955. "#endif",
  9956. "}",
  9957. "#endif",
  9958. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  9959. "#ifdef DOUBLE_SIDED",
  9960. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  9961. "#endif"
  9962. ].join("\n"),
  9963. // LIGHTS PHONG
  9964. lights_phong_pars_vertex: [
  9965. "#ifndef PHONG_PER_PIXEL",
  9966. "#if MAX_POINT_LIGHTS > 0",
  9967. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9968. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9969. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9970. "#endif",
  9971. "#if MAX_SPOT_LIGHTS > 0",
  9972. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9973. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9974. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9975. "#endif",
  9976. "#endif",
  9977. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9978. "varying vec3 vWorldPosition;",
  9979. "#endif"
  9980. ].join("\n"),
  9981. lights_phong_vertex: [
  9982. "#ifndef PHONG_PER_PIXEL",
  9983. "#if MAX_POINT_LIGHTS > 0",
  9984. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9985. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9986. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9987. "float lDistance = 1.0;",
  9988. "if ( pointLightDistance[ i ] > 0.0 )",
  9989. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9990. "vPointLight[ i ] = vec4( lVector, lDistance );",
  9991. "}",
  9992. "#endif",
  9993. "#if MAX_SPOT_LIGHTS > 0",
  9994. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9995. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9996. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9997. "float lDistance = 1.0;",
  9998. "if ( spotLightDistance[ i ] > 0.0 )",
  9999. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10000. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  10001. "}",
  10002. "#endif",
  10003. "#endif",
  10004. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10005. "vWorldPosition = worldPosition.xyz;",
  10006. "#endif"
  10007. ].join("\n"),
  10008. lights_phong_pars_fragment: [
  10009. "uniform vec3 ambientLightColor;",
  10010. "#if MAX_DIR_LIGHTS > 0",
  10011. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10012. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10013. "#endif",
  10014. "#if MAX_HEMI_LIGHTS > 0",
  10015. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10016. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10017. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10018. "#endif",
  10019. "#if MAX_POINT_LIGHTS > 0",
  10020. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10021. "#ifdef PHONG_PER_PIXEL",
  10022. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10023. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10024. "#else",
  10025. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  10026. "#endif",
  10027. "#endif",
  10028. "#if MAX_SPOT_LIGHTS > 0",
  10029. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10030. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10031. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10032. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10033. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10034. "#ifdef PHONG_PER_PIXEL",
  10035. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10036. "#else",
  10037. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  10038. "#endif",
  10039. "#endif",
  10040. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10041. "varying vec3 vWorldPosition;",
  10042. "#endif",
  10043. "#ifdef WRAP_AROUND",
  10044. "uniform vec3 wrapRGB;",
  10045. "#endif",
  10046. "varying vec3 vViewPosition;",
  10047. "varying vec3 vNormal;"
  10048. ].join("\n"),
  10049. lights_phong_fragment: [
  10050. "vec3 normal = normalize( vNormal );",
  10051. "vec3 viewPosition = normalize( vViewPosition );",
  10052. "#ifdef DOUBLE_SIDED",
  10053. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  10054. "#endif",
  10055. "#ifdef USE_NORMALMAP",
  10056. "normal = perturbNormal2Arb( -vViewPosition, normal );",
  10057. "#elif defined( USE_BUMPMAP )",
  10058. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  10059. "#endif",
  10060. "#if MAX_POINT_LIGHTS > 0",
  10061. "vec3 pointDiffuse = vec3( 0.0 );",
  10062. "vec3 pointSpecular = vec3( 0.0 );",
  10063. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10064. "#ifdef PHONG_PER_PIXEL",
  10065. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10066. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10067. "float lDistance = 1.0;",
  10068. "if ( pointLightDistance[ i ] > 0.0 )",
  10069. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10070. "lVector = normalize( lVector );",
  10071. "#else",
  10072. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  10073. "float lDistance = vPointLight[ i ].w;",
  10074. "#endif",
  10075. // diffuse
  10076. "float dotProduct = dot( normal, lVector );",
  10077. "#ifdef WRAP_AROUND",
  10078. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  10079. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10080. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  10081. "#else",
  10082. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  10083. "#endif",
  10084. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  10085. // specular
  10086. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  10087. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  10088. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  10089. "#ifdef PHYSICALLY_BASED_SHADING",
  10090. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10091. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10092. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  10093. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  10094. "#else",
  10095. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  10096. "#endif",
  10097. "}",
  10098. "#endif",
  10099. "#if MAX_SPOT_LIGHTS > 0",
  10100. "vec3 spotDiffuse = vec3( 0.0 );",
  10101. "vec3 spotSpecular = vec3( 0.0 );",
  10102. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10103. "#ifdef PHONG_PER_PIXEL",
  10104. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10105. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10106. "float lDistance = 1.0;",
  10107. "if ( spotLightDistance[ i ] > 0.0 )",
  10108. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10109. "lVector = normalize( lVector );",
  10110. "#else",
  10111. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  10112. "float lDistance = vSpotLight[ i ].w;",
  10113. "#endif",
  10114. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  10115. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10116. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10117. // diffuse
  10118. "float dotProduct = dot( normal, lVector );",
  10119. "#ifdef WRAP_AROUND",
  10120. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  10121. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10122. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  10123. "#else",
  10124. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  10125. "#endif",
  10126. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  10127. // specular
  10128. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  10129. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  10130. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  10131. "#ifdef PHYSICALLY_BASED_SHADING",
  10132. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10133. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10134. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  10135. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  10136. "#else",
  10137. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  10138. "#endif",
  10139. "}",
  10140. "}",
  10141. "#endif",
  10142. "#if MAX_DIR_LIGHTS > 0",
  10143. "vec3 dirDiffuse = vec3( 0.0 );",
  10144. "vec3 dirSpecular = vec3( 0.0 );" ,
  10145. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10146. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10147. "vec3 dirVector = normalize( lDirection.xyz );",
  10148. // diffuse
  10149. "float dotProduct = dot( normal, dirVector );",
  10150. "#ifdef WRAP_AROUND",
  10151. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  10152. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10153. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  10154. "#else",
  10155. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  10156. "#endif",
  10157. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  10158. // specular
  10159. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  10160. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  10161. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  10162. "#ifdef PHYSICALLY_BASED_SHADING",
  10163. /*
  10164. // fresnel term from skin shader
  10165. "const float F0 = 0.128;",
  10166. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  10167. "float exponential = pow( base, 5.0 );",
  10168. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  10169. */
  10170. /*
  10171. // fresnel term from fresnel shader
  10172. "const float mFresnelBias = 0.08;",
  10173. "const float mFresnelScale = 0.3;",
  10174. "const float mFresnelPower = 5.0;",
  10175. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  10176. */
  10177. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10178. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10179. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  10180. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  10181. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  10182. "#else",
  10183. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  10184. "#endif",
  10185. "}",
  10186. "#endif",
  10187. "#if MAX_HEMI_LIGHTS > 0",
  10188. "vec3 hemiDiffuse = vec3( 0.0 );",
  10189. "vec3 hemiSpecular = vec3( 0.0 );" ,
  10190. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10191. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10192. "vec3 lVector = normalize( lDirection.xyz );",
  10193. // diffuse
  10194. "float dotProduct = dot( normal, lVector );",
  10195. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10196. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10197. "hemiDiffuse += diffuse * hemiColor;",
  10198. // specular (sky light)
  10199. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  10200. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  10201. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  10202. // specular (ground light)
  10203. "vec3 lVectorGround = -lVector;",
  10204. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  10205. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  10206. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  10207. "#ifdef PHYSICALLY_BASED_SHADING",
  10208. "float dotProductGround = dot( normal, lVectorGround );",
  10209. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10210. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10211. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  10212. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  10213. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  10214. "#else",
  10215. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  10216. "#endif",
  10217. "}",
  10218. "#endif",
  10219. "vec3 totalDiffuse = vec3( 0.0 );",
  10220. "vec3 totalSpecular = vec3( 0.0 );",
  10221. "#if MAX_DIR_LIGHTS > 0",
  10222. "totalDiffuse += dirDiffuse;",
  10223. "totalSpecular += dirSpecular;",
  10224. "#endif",
  10225. "#if MAX_HEMI_LIGHTS > 0",
  10226. "totalDiffuse += hemiDiffuse;",
  10227. "totalSpecular += hemiSpecular;",
  10228. "#endif",
  10229. "#if MAX_POINT_LIGHTS > 0",
  10230. "totalDiffuse += pointDiffuse;",
  10231. "totalSpecular += pointSpecular;",
  10232. "#endif",
  10233. "#if MAX_SPOT_LIGHTS > 0",
  10234. "totalDiffuse += spotDiffuse;",
  10235. "totalSpecular += spotSpecular;",
  10236. "#endif",
  10237. "#ifdef METAL",
  10238. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  10239. "#else",
  10240. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  10241. "#endif"
  10242. ].join("\n"),
  10243. // VERTEX COLORS
  10244. color_pars_fragment: [
  10245. "#ifdef USE_COLOR",
  10246. "varying vec3 vColor;",
  10247. "#endif"
  10248. ].join("\n"),
  10249. color_fragment: [
  10250. "#ifdef USE_COLOR",
  10251. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  10252. "#endif"
  10253. ].join("\n"),
  10254. color_pars_vertex: [
  10255. "#ifdef USE_COLOR",
  10256. "varying vec3 vColor;",
  10257. "#endif"
  10258. ].join("\n"),
  10259. color_vertex: [
  10260. "#ifdef USE_COLOR",
  10261. "#ifdef GAMMA_INPUT",
  10262. "vColor = color * color;",
  10263. "#else",
  10264. "vColor = color;",
  10265. "#endif",
  10266. "#endif"
  10267. ].join("\n"),
  10268. // SKINNING
  10269. skinning_pars_vertex: [
  10270. "#ifdef USE_SKINNING",
  10271. "#ifdef BONE_TEXTURE",
  10272. "uniform sampler2D boneTexture;",
  10273. "mat4 getBoneMatrix( const in float i ) {",
  10274. "float j = i * 4.0;",
  10275. "float x = mod( j, N_BONE_PIXEL_X );",
  10276. "float y = floor( j / N_BONE_PIXEL_X );",
  10277. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  10278. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  10279. "y = dy * ( y + 0.5 );",
  10280. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  10281. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  10282. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  10283. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  10284. "mat4 bone = mat4( v1, v2, v3, v4 );",
  10285. "return bone;",
  10286. "}",
  10287. "#else",
  10288. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  10289. "mat4 getBoneMatrix( const in float i ) {",
  10290. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  10291. "return bone;",
  10292. "}",
  10293. "#endif",
  10294. "#endif"
  10295. ].join("\n"),
  10296. skinbase_vertex: [
  10297. "#ifdef USE_SKINNING",
  10298. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  10299. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  10300. "#endif"
  10301. ].join("\n"),
  10302. skinning_vertex: [
  10303. "#ifdef USE_SKINNING",
  10304. "#ifdef USE_MORPHTARGETS",
  10305. "vec4 skinVertex = vec4( morphed, 1.0 );",
  10306. "#else",
  10307. "vec4 skinVertex = vec4( position, 1.0 );",
  10308. "#endif",
  10309. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10310. "skinned += boneMatY * skinVertex * skinWeight.y;",
  10311. "#endif"
  10312. ].join("\n"),
  10313. // MORPHING
  10314. morphtarget_pars_vertex: [
  10315. "#ifdef USE_MORPHTARGETS",
  10316. "#ifndef USE_MORPHNORMALS",
  10317. "uniform float morphTargetInfluences[ 8 ];",
  10318. "#else",
  10319. "uniform float morphTargetInfluences[ 4 ];",
  10320. "#endif",
  10321. "#endif"
  10322. ].join("\n"),
  10323. morphtarget_vertex: [
  10324. "#ifdef USE_MORPHTARGETS",
  10325. "vec3 morphed = vec3( 0.0 );",
  10326. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  10327. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  10328. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  10329. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  10330. "#ifndef USE_MORPHNORMALS",
  10331. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  10332. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  10333. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  10334. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  10335. "#endif",
  10336. "morphed += position;",
  10337. "#endif"
  10338. ].join("\n"),
  10339. default_vertex : [
  10340. "vec4 mvPosition;",
  10341. "#ifdef USE_SKINNING",
  10342. "mvPosition = modelViewMatrix * skinned;",
  10343. "#endif",
  10344. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  10345. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  10346. "#endif",
  10347. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  10348. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10349. "#endif",
  10350. "gl_Position = projectionMatrix * mvPosition;"
  10351. ].join("\n"),
  10352. morphnormal_vertex: [
  10353. "#ifdef USE_MORPHNORMALS",
  10354. "vec3 morphedNormal = vec3( 0.0 );",
  10355. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  10356. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  10357. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  10358. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  10359. "morphedNormal += normal;",
  10360. "#endif"
  10361. ].join("\n"),
  10362. skinnormal_vertex: [
  10363. "#ifdef USE_SKINNING",
  10364. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  10365. "skinMatrix += skinWeight.y * boneMatY;",
  10366. "#ifdef USE_MORPHNORMALS",
  10367. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  10368. "#else",
  10369. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  10370. "#endif",
  10371. "#endif"
  10372. ].join("\n"),
  10373. defaultnormal_vertex: [
  10374. "vec3 objectNormal;",
  10375. "#ifdef USE_SKINNING",
  10376. "objectNormal = skinnedNormal.xyz;",
  10377. "#endif",
  10378. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  10379. "objectNormal = morphedNormal;",
  10380. "#endif",
  10381. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  10382. "objectNormal = normal;",
  10383. "#endif",
  10384. "#ifdef FLIP_SIDED",
  10385. "objectNormal = -objectNormal;",
  10386. "#endif",
  10387. "vec3 transformedNormal = normalMatrix * objectNormal;"
  10388. ].join("\n"),
  10389. // SHADOW MAP
  10390. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  10391. // http://spidergl.org/example.php?id=6
  10392. // http://fabiensanglard.net/shadowmapping
  10393. shadowmap_pars_fragment: [
  10394. "#ifdef USE_SHADOWMAP",
  10395. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  10396. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  10397. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  10398. "uniform float shadowBias[ MAX_SHADOWS ];",
  10399. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10400. "float unpackDepth( const in vec4 rgba_depth ) {",
  10401. "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 );",
  10402. "float depth = dot( rgba_depth, bit_shift );",
  10403. "return depth;",
  10404. "}",
  10405. "#endif"
  10406. ].join("\n"),
  10407. shadowmap_fragment: [
  10408. "#ifdef USE_SHADOWMAP",
  10409. "#ifdef SHADOWMAP_DEBUG",
  10410. "vec3 frustumColors[3];",
  10411. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  10412. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  10413. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  10414. "#endif",
  10415. "#ifdef SHADOWMAP_CASCADE",
  10416. "int inFrustumCount = 0;",
  10417. "#endif",
  10418. "float fDepth;",
  10419. "vec3 shadowColor = vec3( 1.0 );",
  10420. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10421. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  10422. // "if ( something && something )" breaks ATI OpenGL shader compiler
  10423. // "if ( all( something, something ) )" using this instead
  10424. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  10425. "bool inFrustum = all( inFrustumVec );",
  10426. // don't shadow pixels outside of light frustum
  10427. // use just first frustum (for cascades)
  10428. // don't shadow pixels behind far plane of light frustum
  10429. "#ifdef SHADOWMAP_CASCADE",
  10430. "inFrustumCount += int( inFrustum );",
  10431. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  10432. "#else",
  10433. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  10434. "#endif",
  10435. "bool frustumTest = all( frustumTestVec );",
  10436. "if ( frustumTest ) {",
  10437. "shadowCoord.z += shadowBias[ i ];",
  10438. "#if defined( SHADOWMAP_TYPE_PCF )",
  10439. // Percentage-close filtering
  10440. // (9 pixel kernel)
  10441. // http://fabiensanglard.net/shadowmappingPCF/
  10442. "float shadow = 0.0;",
  10443. /*
  10444. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  10445. // must enroll loop manually
  10446. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  10447. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  10448. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  10449. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  10450. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  10451. "float fDepth = unpackDepth( rgbaDepth );",
  10452. "if ( fDepth < shadowCoord.z )",
  10453. "shadow += 1.0;",
  10454. "}",
  10455. "shadow /= 9.0;",
  10456. */
  10457. "const float shadowDelta = 1.0 / 9.0;",
  10458. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10459. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10460. "float dx0 = -1.25 * xPixelOffset;",
  10461. "float dy0 = -1.25 * yPixelOffset;",
  10462. "float dx1 = 1.25 * xPixelOffset;",
  10463. "float dy1 = 1.25 * yPixelOffset;",
  10464. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10465. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10466. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10467. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10468. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10469. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10470. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10471. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10472. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10473. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10474. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10475. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10476. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10477. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10478. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10479. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10480. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10481. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10482. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10483. "#elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  10484. // Percentage-close filtering
  10485. // (9 pixel kernel)
  10486. // http://fabiensanglard.net/shadowmappingPCF/
  10487. "float shadow = 0.0;",
  10488. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10489. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10490. "float dx0 = -1.0 * xPixelOffset;",
  10491. "float dy0 = -1.0 * yPixelOffset;",
  10492. "float dx1 = 1.0 * xPixelOffset;",
  10493. "float dy1 = 1.0 * yPixelOffset;",
  10494. "mat3 shadowKernel;",
  10495. "mat3 depthKernel;",
  10496. "depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10497. "depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10498. "depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10499. "depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10500. "depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10501. "depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10502. "depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10503. "depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10504. "depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10505. "vec3 shadowZ = vec3( shadowCoord.z );",
  10506. "shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));",
  10507. "shadowKernel[0] *= vec3(0.25);",
  10508. "shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));",
  10509. "shadowKernel[1] *= vec3(0.25);",
  10510. "shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));",
  10511. "shadowKernel[2] *= vec3(0.25);",
  10512. "vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  10513. "shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  10514. "shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  10515. "vec4 shadowValues;",
  10516. "shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  10517. "shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  10518. "shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  10519. "shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  10520. "shadow = dot( shadowValues, vec4( 1.0 ) );",
  10521. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10522. "#else",
  10523. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  10524. "float fDepth = unpackDepth( rgbaDepth );",
  10525. "if ( fDepth < shadowCoord.z )",
  10526. // spot with multiple shadows is darker
  10527. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  10528. // spot with multiple shadows has the same color as single shadow spot
  10529. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  10530. "#endif",
  10531. "}",
  10532. "#ifdef SHADOWMAP_DEBUG",
  10533. "#ifdef SHADOWMAP_CASCADE",
  10534. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  10535. "#else",
  10536. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  10537. "#endif",
  10538. "#endif",
  10539. "}",
  10540. "#ifdef GAMMA_OUTPUT",
  10541. "shadowColor *= shadowColor;",
  10542. "#endif",
  10543. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  10544. "#endif"
  10545. ].join("\n"),
  10546. shadowmap_pars_vertex: [
  10547. "#ifdef USE_SHADOWMAP",
  10548. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10549. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  10550. "#endif"
  10551. ].join("\n"),
  10552. shadowmap_vertex: [
  10553. "#ifdef USE_SHADOWMAP",
  10554. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10555. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  10556. "}",
  10557. "#endif"
  10558. ].join("\n"),
  10559. // ALPHATEST
  10560. alphatest_fragment: [
  10561. "#ifdef ALPHATEST",
  10562. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  10563. "#endif"
  10564. ].join("\n"),
  10565. // LINEAR SPACE
  10566. linear_to_gamma_fragment: [
  10567. "#ifdef GAMMA_OUTPUT",
  10568. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  10569. "#endif"
  10570. ].join("\n")
  10571. };
  10572. THREE.UniformsUtils = {
  10573. merge: function ( uniforms ) {
  10574. var u, p, tmp, merged = {};
  10575. for ( u = 0; u < uniforms.length; u ++ ) {
  10576. tmp = this.clone( uniforms[ u ] );
  10577. for ( p in tmp ) {
  10578. merged[ p ] = tmp[ p ];
  10579. }
  10580. }
  10581. return merged;
  10582. },
  10583. clone: function ( uniforms_src ) {
  10584. var u, p, parameter, parameter_src, uniforms_dst = {};
  10585. for ( u in uniforms_src ) {
  10586. uniforms_dst[ u ] = {};
  10587. for ( p in uniforms_src[ u ] ) {
  10588. parameter_src = uniforms_src[ u ][ p ];
  10589. if ( parameter_src instanceof THREE.Color ||
  10590. parameter_src instanceof THREE.Vector2 ||
  10591. parameter_src instanceof THREE.Vector3 ||
  10592. parameter_src instanceof THREE.Vector4 ||
  10593. parameter_src instanceof THREE.Matrix4 ||
  10594. parameter_src instanceof THREE.Texture ) {
  10595. uniforms_dst[ u ][ p ] = parameter_src.clone();
  10596. } else if ( parameter_src instanceof Array ) {
  10597. uniforms_dst[ u ][ p ] = parameter_src.slice();
  10598. } else {
  10599. uniforms_dst[ u ][ p ] = parameter_src;
  10600. }
  10601. }
  10602. }
  10603. return uniforms_dst;
  10604. }
  10605. };
  10606. THREE.UniformsLib = {
  10607. common: {
  10608. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10609. "opacity" : { type: "f", value: 1.0 },
  10610. "map" : { type: "t", value: null },
  10611. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  10612. "lightMap" : { type: "t", value: null },
  10613. "specularMap" : { type: "t", value: null },
  10614. "envMap" : { type: "t", value: null },
  10615. "flipEnvMap" : { type: "f", value: -1 },
  10616. "useRefract" : { type: "i", value: 0 },
  10617. "reflectivity" : { type: "f", value: 1.0 },
  10618. "refractionRatio" : { type: "f", value: 0.98 },
  10619. "combine" : { type: "i", value: 0 },
  10620. "morphTargetInfluences" : { type: "f", value: 0 }
  10621. },
  10622. bump: {
  10623. "bumpMap" : { type: "t", value: null },
  10624. "bumpScale" : { type: "f", value: 1 }
  10625. },
  10626. normalmap: {
  10627. "normalMap" : { type: "t", value: null },
  10628. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  10629. },
  10630. fog : {
  10631. "fogDensity" : { type: "f", value: 0.00025 },
  10632. "fogNear" : { type: "f", value: 1 },
  10633. "fogFar" : { type: "f", value: 2000 },
  10634. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10635. },
  10636. lights: {
  10637. "ambientLightColor" : { type: "fv", value: [] },
  10638. "directionalLightDirection" : { type: "fv", value: [] },
  10639. "directionalLightColor" : { type: "fv", value: [] },
  10640. "hemisphereLightDirection" : { type: "fv", value: [] },
  10641. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  10642. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  10643. "pointLightColor" : { type: "fv", value: [] },
  10644. "pointLightPosition" : { type: "fv", value: [] },
  10645. "pointLightDistance" : { type: "fv1", value: [] },
  10646. "spotLightColor" : { type: "fv", value: [] },
  10647. "spotLightPosition" : { type: "fv", value: [] },
  10648. "spotLightDirection" : { type: "fv", value: [] },
  10649. "spotLightDistance" : { type: "fv1", value: [] },
  10650. "spotLightAngleCos" : { type: "fv1", value: [] },
  10651. "spotLightExponent" : { type: "fv1", value: [] }
  10652. },
  10653. particle: {
  10654. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10655. "opacity" : { type: "f", value: 1.0 },
  10656. "size" : { type: "f", value: 1.0 },
  10657. "scale" : { type: "f", value: 1.0 },
  10658. "map" : { type: "t", value: null },
  10659. "fogDensity" : { type: "f", value: 0.00025 },
  10660. "fogNear" : { type: "f", value: 1 },
  10661. "fogFar" : { type: "f", value: 2000 },
  10662. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10663. },
  10664. shadowmap: {
  10665. "shadowMap": { type: "tv", value: [] },
  10666. "shadowMapSize": { type: "v2v", value: [] },
  10667. "shadowBias" : { type: "fv1", value: [] },
  10668. "shadowDarkness": { type: "fv1", value: [] },
  10669. "shadowMatrix" : { type: "m4v", value: [] }
  10670. }
  10671. };
  10672. THREE.ShaderLib = {
  10673. 'basic': {
  10674. uniforms: THREE.UniformsUtils.merge( [
  10675. THREE.UniformsLib[ "common" ],
  10676. THREE.UniformsLib[ "fog" ],
  10677. THREE.UniformsLib[ "shadowmap" ]
  10678. ] ),
  10679. vertexShader: [
  10680. THREE.ShaderChunk[ "map_pars_vertex" ],
  10681. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10682. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10683. THREE.ShaderChunk[ "color_pars_vertex" ],
  10684. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10685. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10686. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10687. "void main() {",
  10688. THREE.ShaderChunk[ "map_vertex" ],
  10689. THREE.ShaderChunk[ "lightmap_vertex" ],
  10690. THREE.ShaderChunk[ "color_vertex" ],
  10691. THREE.ShaderChunk[ "skinbase_vertex" ],
  10692. "#ifdef USE_ENVMAP",
  10693. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10694. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10695. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10696. "#endif",
  10697. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10698. THREE.ShaderChunk[ "skinning_vertex" ],
  10699. THREE.ShaderChunk[ "default_vertex" ],
  10700. THREE.ShaderChunk[ "worldpos_vertex" ],
  10701. THREE.ShaderChunk[ "envmap_vertex" ],
  10702. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10703. "}"
  10704. ].join("\n"),
  10705. fragmentShader: [
  10706. "uniform vec3 diffuse;",
  10707. "uniform float opacity;",
  10708. THREE.ShaderChunk[ "color_pars_fragment" ],
  10709. THREE.ShaderChunk[ "map_pars_fragment" ],
  10710. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10711. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10712. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10713. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10714. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10715. "void main() {",
  10716. "gl_FragColor = vec4( diffuse, opacity );",
  10717. THREE.ShaderChunk[ "map_fragment" ],
  10718. THREE.ShaderChunk[ "alphatest_fragment" ],
  10719. THREE.ShaderChunk[ "specularmap_fragment" ],
  10720. THREE.ShaderChunk[ "lightmap_fragment" ],
  10721. THREE.ShaderChunk[ "color_fragment" ],
  10722. THREE.ShaderChunk[ "envmap_fragment" ],
  10723. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10724. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10725. THREE.ShaderChunk[ "fog_fragment" ],
  10726. "}"
  10727. ].join("\n")
  10728. },
  10729. 'lambert': {
  10730. uniforms: THREE.UniformsUtils.merge( [
  10731. THREE.UniformsLib[ "common" ],
  10732. THREE.UniformsLib[ "fog" ],
  10733. THREE.UniformsLib[ "lights" ],
  10734. THREE.UniformsLib[ "shadowmap" ],
  10735. {
  10736. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10737. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10738. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10739. }
  10740. ] ),
  10741. vertexShader: [
  10742. "#define LAMBERT",
  10743. "varying vec3 vLightFront;",
  10744. "#ifdef DOUBLE_SIDED",
  10745. "varying vec3 vLightBack;",
  10746. "#endif",
  10747. THREE.ShaderChunk[ "map_pars_vertex" ],
  10748. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10749. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10750. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  10751. THREE.ShaderChunk[ "color_pars_vertex" ],
  10752. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10753. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10754. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10755. "void main() {",
  10756. THREE.ShaderChunk[ "map_vertex" ],
  10757. THREE.ShaderChunk[ "lightmap_vertex" ],
  10758. THREE.ShaderChunk[ "color_vertex" ],
  10759. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10760. THREE.ShaderChunk[ "skinbase_vertex" ],
  10761. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10762. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10763. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10764. THREE.ShaderChunk[ "skinning_vertex" ],
  10765. THREE.ShaderChunk[ "default_vertex" ],
  10766. THREE.ShaderChunk[ "worldpos_vertex" ],
  10767. THREE.ShaderChunk[ "envmap_vertex" ],
  10768. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  10769. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10770. "}"
  10771. ].join("\n"),
  10772. fragmentShader: [
  10773. "uniform float opacity;",
  10774. "varying vec3 vLightFront;",
  10775. "#ifdef DOUBLE_SIDED",
  10776. "varying vec3 vLightBack;",
  10777. "#endif",
  10778. THREE.ShaderChunk[ "color_pars_fragment" ],
  10779. THREE.ShaderChunk[ "map_pars_fragment" ],
  10780. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10781. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10782. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10783. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10784. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10785. "void main() {",
  10786. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10787. THREE.ShaderChunk[ "map_fragment" ],
  10788. THREE.ShaderChunk[ "alphatest_fragment" ],
  10789. THREE.ShaderChunk[ "specularmap_fragment" ],
  10790. "#ifdef DOUBLE_SIDED",
  10791. //"float isFront = float( gl_FrontFacing );",
  10792. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  10793. "if ( gl_FrontFacing )",
  10794. "gl_FragColor.xyz *= vLightFront;",
  10795. "else",
  10796. "gl_FragColor.xyz *= vLightBack;",
  10797. "#else",
  10798. "gl_FragColor.xyz *= vLightFront;",
  10799. "#endif",
  10800. THREE.ShaderChunk[ "lightmap_fragment" ],
  10801. THREE.ShaderChunk[ "color_fragment" ],
  10802. THREE.ShaderChunk[ "envmap_fragment" ],
  10803. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10804. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10805. THREE.ShaderChunk[ "fog_fragment" ],
  10806. "}"
  10807. ].join("\n")
  10808. },
  10809. 'phong': {
  10810. uniforms: THREE.UniformsUtils.merge( [
  10811. THREE.UniformsLib[ "common" ],
  10812. THREE.UniformsLib[ "bump" ],
  10813. THREE.UniformsLib[ "normalmap" ],
  10814. THREE.UniformsLib[ "fog" ],
  10815. THREE.UniformsLib[ "lights" ],
  10816. THREE.UniformsLib[ "shadowmap" ],
  10817. {
  10818. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10819. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10820. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  10821. "shininess": { type: "f", value: 30 },
  10822. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10823. }
  10824. ] ),
  10825. vertexShader: [
  10826. "#define PHONG",
  10827. "varying vec3 vViewPosition;",
  10828. "varying vec3 vNormal;",
  10829. THREE.ShaderChunk[ "map_pars_vertex" ],
  10830. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10831. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10832. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  10833. THREE.ShaderChunk[ "color_pars_vertex" ],
  10834. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10835. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10836. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10837. "void main() {",
  10838. THREE.ShaderChunk[ "map_vertex" ],
  10839. THREE.ShaderChunk[ "lightmap_vertex" ],
  10840. THREE.ShaderChunk[ "color_vertex" ],
  10841. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10842. THREE.ShaderChunk[ "skinbase_vertex" ],
  10843. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10844. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10845. "vNormal = normalize( transformedNormal );",
  10846. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10847. THREE.ShaderChunk[ "skinning_vertex" ],
  10848. THREE.ShaderChunk[ "default_vertex" ],
  10849. "vViewPosition = -mvPosition.xyz;",
  10850. THREE.ShaderChunk[ "worldpos_vertex" ],
  10851. THREE.ShaderChunk[ "envmap_vertex" ],
  10852. THREE.ShaderChunk[ "lights_phong_vertex" ],
  10853. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10854. "}"
  10855. ].join("\n"),
  10856. fragmentShader: [
  10857. "uniform vec3 diffuse;",
  10858. "uniform float opacity;",
  10859. "uniform vec3 ambient;",
  10860. "uniform vec3 emissive;",
  10861. "uniform vec3 specular;",
  10862. "uniform float shininess;",
  10863. THREE.ShaderChunk[ "color_pars_fragment" ],
  10864. THREE.ShaderChunk[ "map_pars_fragment" ],
  10865. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10866. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10867. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10868. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  10869. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10870. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  10871. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  10872. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10873. "void main() {",
  10874. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10875. THREE.ShaderChunk[ "map_fragment" ],
  10876. THREE.ShaderChunk[ "alphatest_fragment" ],
  10877. THREE.ShaderChunk[ "specularmap_fragment" ],
  10878. THREE.ShaderChunk[ "lights_phong_fragment" ],
  10879. THREE.ShaderChunk[ "lightmap_fragment" ],
  10880. THREE.ShaderChunk[ "color_fragment" ],
  10881. THREE.ShaderChunk[ "envmap_fragment" ],
  10882. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10883. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10884. THREE.ShaderChunk[ "fog_fragment" ],
  10885. "}"
  10886. ].join("\n")
  10887. },
  10888. 'particle_basic': {
  10889. uniforms: THREE.UniformsUtils.merge( [
  10890. THREE.UniformsLib[ "particle" ],
  10891. THREE.UniformsLib[ "shadowmap" ]
  10892. ] ),
  10893. vertexShader: [
  10894. "uniform float size;",
  10895. "uniform float scale;",
  10896. THREE.ShaderChunk[ "color_pars_vertex" ],
  10897. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10898. "void main() {",
  10899. THREE.ShaderChunk[ "color_vertex" ],
  10900. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10901. "#ifdef USE_SIZEATTENUATION",
  10902. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  10903. "#else",
  10904. "gl_PointSize = size;",
  10905. "#endif",
  10906. "gl_Position = projectionMatrix * mvPosition;",
  10907. THREE.ShaderChunk[ "worldpos_vertex" ],
  10908. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10909. "}"
  10910. ].join("\n"),
  10911. fragmentShader: [
  10912. "uniform vec3 psColor;",
  10913. "uniform float opacity;",
  10914. THREE.ShaderChunk[ "color_pars_fragment" ],
  10915. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  10916. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10917. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10918. "void main() {",
  10919. "gl_FragColor = vec4( psColor, opacity );",
  10920. THREE.ShaderChunk[ "map_particle_fragment" ],
  10921. THREE.ShaderChunk[ "alphatest_fragment" ],
  10922. THREE.ShaderChunk[ "color_fragment" ],
  10923. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10924. THREE.ShaderChunk[ "fog_fragment" ],
  10925. "}"
  10926. ].join("\n")
  10927. },
  10928. 'dashed': {
  10929. uniforms: THREE.UniformsUtils.merge( [
  10930. THREE.UniformsLib[ "common" ],
  10931. THREE.UniformsLib[ "fog" ],
  10932. {
  10933. "scale": { type: "f", value: 1 },
  10934. "dashSize": { type: "f", value: 1 },
  10935. "totalSize": { type: "f", value: 2 }
  10936. }
  10937. ] ),
  10938. vertexShader: [
  10939. "uniform float scale;",
  10940. "attribute float lineDistance;",
  10941. "varying float vLineDistance;",
  10942. THREE.ShaderChunk[ "color_pars_vertex" ],
  10943. "void main() {",
  10944. THREE.ShaderChunk[ "color_vertex" ],
  10945. "vLineDistance = scale * lineDistance;",
  10946. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10947. "gl_Position = projectionMatrix * mvPosition;",
  10948. "}"
  10949. ].join("\n"),
  10950. fragmentShader: [
  10951. "uniform vec3 diffuse;",
  10952. "uniform float opacity;",
  10953. "uniform float dashSize;",
  10954. "uniform float totalSize;",
  10955. "varying float vLineDistance;",
  10956. THREE.ShaderChunk[ "color_pars_fragment" ],
  10957. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10958. "void main() {",
  10959. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  10960. "discard;",
  10961. "}",
  10962. "gl_FragColor = vec4( diffuse, opacity );",
  10963. THREE.ShaderChunk[ "color_fragment" ],
  10964. THREE.ShaderChunk[ "fog_fragment" ],
  10965. "}"
  10966. ].join("\n")
  10967. },
  10968. 'depth': {
  10969. uniforms: {
  10970. "mNear": { type: "f", value: 1.0 },
  10971. "mFar" : { type: "f", value: 2000.0 },
  10972. "opacity" : { type: "f", value: 1.0 }
  10973. },
  10974. vertexShader: [
  10975. "void main() {",
  10976. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  10977. "}"
  10978. ].join("\n"),
  10979. fragmentShader: [
  10980. "uniform float mNear;",
  10981. "uniform float mFar;",
  10982. "uniform float opacity;",
  10983. "void main() {",
  10984. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  10985. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  10986. "gl_FragColor = vec4( vec3( color ), opacity );",
  10987. "}"
  10988. ].join("\n")
  10989. },
  10990. 'normal': {
  10991. uniforms: {
  10992. "opacity" : { type: "f", value: 1.0 }
  10993. },
  10994. vertexShader: [
  10995. "varying vec3 vNormal;",
  10996. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10997. "void main() {",
  10998. "vNormal = normalize( normalMatrix * normal );",
  10999. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11000. THREE.ShaderChunk[ "default_vertex" ],
  11001. "}"
  11002. ].join("\n"),
  11003. fragmentShader: [
  11004. "uniform float opacity;",
  11005. "varying vec3 vNormal;",
  11006. "void main() {",
  11007. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  11008. "}"
  11009. ].join("\n")
  11010. },
  11011. /* -------------------------------------------------------------------------
  11012. // Normal map shader
  11013. // - Blinn-Phong
  11014. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  11015. // - point and directional lights (use with "lights: true" material option)
  11016. ------------------------------------------------------------------------- */
  11017. 'normalmap' : {
  11018. uniforms: THREE.UniformsUtils.merge( [
  11019. THREE.UniformsLib[ "fog" ],
  11020. THREE.UniformsLib[ "lights" ],
  11021. THREE.UniformsLib[ "shadowmap" ],
  11022. {
  11023. "enableAO" : { type: "i", value: 0 },
  11024. "enableDiffuse" : { type: "i", value: 0 },
  11025. "enableSpecular" : { type: "i", value: 0 },
  11026. "enableReflection": { type: "i", value: 0 },
  11027. "enableDisplacement": { type: "i", value: 0 },
  11028. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  11029. "tDiffuse" : { type: "t", value: null },
  11030. "tCube" : { type: "t", value: null },
  11031. "tNormal" : { type: "t", value: null },
  11032. "tSpecular" : { type: "t", value: null },
  11033. "tAO" : { type: "t", value: null },
  11034. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11035. "uDisplacementBias": { type: "f", value: 0.0 },
  11036. "uDisplacementScale": { type: "f", value: 1.0 },
  11037. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  11038. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  11039. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  11040. "uShininess": { type: "f", value: 30 },
  11041. "uOpacity": { type: "f", value: 1 },
  11042. "useRefract": { type: "i", value: 0 },
  11043. "uRefractionRatio": { type: "f", value: 0.98 },
  11044. "uReflectivity": { type: "f", value: 0.5 },
  11045. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  11046. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11047. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11048. }
  11049. ] ),
  11050. fragmentShader: [
  11051. "uniform vec3 uAmbientColor;",
  11052. "uniform vec3 uDiffuseColor;",
  11053. "uniform vec3 uSpecularColor;",
  11054. "uniform float uShininess;",
  11055. "uniform float uOpacity;",
  11056. "uniform bool enableDiffuse;",
  11057. "uniform bool enableSpecular;",
  11058. "uniform bool enableAO;",
  11059. "uniform bool enableReflection;",
  11060. "uniform sampler2D tDiffuse;",
  11061. "uniform sampler2D tNormal;",
  11062. "uniform sampler2D tSpecular;",
  11063. "uniform sampler2D tAO;",
  11064. "uniform samplerCube tCube;",
  11065. "uniform vec2 uNormalScale;",
  11066. "uniform bool useRefract;",
  11067. "uniform float uRefractionRatio;",
  11068. "uniform float uReflectivity;",
  11069. "varying vec3 vTangent;",
  11070. "varying vec3 vBinormal;",
  11071. "varying vec3 vNormal;",
  11072. "varying vec2 vUv;",
  11073. "uniform vec3 ambientLightColor;",
  11074. "#if MAX_DIR_LIGHTS > 0",
  11075. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  11076. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  11077. "#endif",
  11078. "#if MAX_HEMI_LIGHTS > 0",
  11079. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  11080. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  11081. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  11082. "#endif",
  11083. "#if MAX_POINT_LIGHTS > 0",
  11084. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  11085. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  11086. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  11087. "#endif",
  11088. "#if MAX_SPOT_LIGHTS > 0",
  11089. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  11090. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  11091. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  11092. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  11093. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  11094. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  11095. "#endif",
  11096. "#ifdef WRAP_AROUND",
  11097. "uniform vec3 wrapRGB;",
  11098. "#endif",
  11099. "varying vec3 vWorldPosition;",
  11100. "varying vec3 vViewPosition;",
  11101. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11102. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11103. "void main() {",
  11104. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  11105. "vec3 specularTex = vec3( 1.0 );",
  11106. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  11107. "normalTex.xy *= uNormalScale;",
  11108. "normalTex = normalize( normalTex );",
  11109. "if( enableDiffuse ) {",
  11110. "#ifdef GAMMA_INPUT",
  11111. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  11112. "texelColor.xyz *= texelColor.xyz;",
  11113. "gl_FragColor = gl_FragColor * texelColor;",
  11114. "#else",
  11115. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  11116. "#endif",
  11117. "}",
  11118. "if( enableAO ) {",
  11119. "#ifdef GAMMA_INPUT",
  11120. "vec4 aoColor = texture2D( tAO, vUv );",
  11121. "aoColor.xyz *= aoColor.xyz;",
  11122. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  11123. "#else",
  11124. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  11125. "#endif",
  11126. "}",
  11127. "if( enableSpecular )",
  11128. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  11129. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  11130. "vec3 finalNormal = tsb * normalTex;",
  11131. "#ifdef FLIP_SIDED",
  11132. "finalNormal = -finalNormal;",
  11133. "#endif",
  11134. "vec3 normal = normalize( finalNormal );",
  11135. "vec3 viewPosition = normalize( vViewPosition );",
  11136. // point lights
  11137. "#if MAX_POINT_LIGHTS > 0",
  11138. "vec3 pointDiffuse = vec3( 0.0 );",
  11139. "vec3 pointSpecular = vec3( 0.0 );",
  11140. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  11141. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  11142. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  11143. "float pointDistance = 1.0;",
  11144. "if ( pointLightDistance[ i ] > 0.0 )",
  11145. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  11146. "pointVector = normalize( pointVector );",
  11147. // diffuse
  11148. "#ifdef WRAP_AROUND",
  11149. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  11150. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  11151. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  11152. "#else",
  11153. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  11154. "#endif",
  11155. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  11156. // specular
  11157. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  11158. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  11159. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  11160. "#ifdef PHYSICALLY_BASED_SHADING",
  11161. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11162. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11163. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  11164. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  11165. "#else",
  11166. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  11167. "#endif",
  11168. "}",
  11169. "#endif",
  11170. // spot lights
  11171. "#if MAX_SPOT_LIGHTS > 0",
  11172. "vec3 spotDiffuse = vec3( 0.0 );",
  11173. "vec3 spotSpecular = vec3( 0.0 );",
  11174. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  11175. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  11176. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  11177. "float spotDistance = 1.0;",
  11178. "if ( spotLightDistance[ i ] > 0.0 )",
  11179. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  11180. "spotVector = normalize( spotVector );",
  11181. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  11182. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  11183. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  11184. // diffuse
  11185. "#ifdef WRAP_AROUND",
  11186. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  11187. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  11188. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  11189. "#else",
  11190. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  11191. "#endif",
  11192. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  11193. // specular
  11194. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  11195. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  11196. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  11197. "#ifdef PHYSICALLY_BASED_SHADING",
  11198. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11199. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11200. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  11201. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  11202. "#else",
  11203. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  11204. "#endif",
  11205. "}",
  11206. "}",
  11207. "#endif",
  11208. // directional lights
  11209. "#if MAX_DIR_LIGHTS > 0",
  11210. "vec3 dirDiffuse = vec3( 0.0 );",
  11211. "vec3 dirSpecular = vec3( 0.0 );",
  11212. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  11213. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  11214. "vec3 dirVector = normalize( lDirection.xyz );",
  11215. // diffuse
  11216. "#ifdef WRAP_AROUND",
  11217. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  11218. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  11219. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  11220. "#else",
  11221. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  11222. "#endif",
  11223. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  11224. // specular
  11225. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  11226. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  11227. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  11228. "#ifdef PHYSICALLY_BASED_SHADING",
  11229. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11230. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11231. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  11232. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  11233. "#else",
  11234. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  11235. "#endif",
  11236. "}",
  11237. "#endif",
  11238. // hemisphere lights
  11239. "#if MAX_HEMI_LIGHTS > 0",
  11240. "vec3 hemiDiffuse = vec3( 0.0 );",
  11241. "vec3 hemiSpecular = vec3( 0.0 );" ,
  11242. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  11243. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  11244. "vec3 lVector = normalize( lDirection.xyz );",
  11245. // diffuse
  11246. "float dotProduct = dot( normal, lVector );",
  11247. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  11248. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  11249. "hemiDiffuse += uDiffuseColor * hemiColor;",
  11250. // specular (sky light)
  11251. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  11252. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  11253. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  11254. // specular (ground light)
  11255. "vec3 lVectorGround = -lVector;",
  11256. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  11257. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  11258. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  11259. "#ifdef PHYSICALLY_BASED_SHADING",
  11260. "float dotProductGround = dot( normal, lVectorGround );",
  11261. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11262. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11263. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  11264. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  11265. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  11266. "#else",
  11267. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  11268. "#endif",
  11269. "}",
  11270. "#endif",
  11271. // all lights contribution summation
  11272. "vec3 totalDiffuse = vec3( 0.0 );",
  11273. "vec3 totalSpecular = vec3( 0.0 );",
  11274. "#if MAX_DIR_LIGHTS > 0",
  11275. "totalDiffuse += dirDiffuse;",
  11276. "totalSpecular += dirSpecular;",
  11277. "#endif",
  11278. "#if MAX_HEMI_LIGHTS > 0",
  11279. "totalDiffuse += hemiDiffuse;",
  11280. "totalSpecular += hemiSpecular;",
  11281. "#endif",
  11282. "#if MAX_POINT_LIGHTS > 0",
  11283. "totalDiffuse += pointDiffuse;",
  11284. "totalSpecular += pointSpecular;",
  11285. "#endif",
  11286. "#if MAX_SPOT_LIGHTS > 0",
  11287. "totalDiffuse += spotDiffuse;",
  11288. "totalSpecular += spotSpecular;",
  11289. "#endif",
  11290. "#ifdef METAL",
  11291. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  11292. "#else",
  11293. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  11294. "#endif",
  11295. "if ( enableReflection ) {",
  11296. "vec3 vReflect;",
  11297. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  11298. "if ( useRefract ) {",
  11299. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  11300. "} else {",
  11301. "vReflect = reflect( cameraToVertex, normal );",
  11302. "}",
  11303. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  11304. "#ifdef GAMMA_INPUT",
  11305. "cubeColor.xyz *= cubeColor.xyz;",
  11306. "#endif",
  11307. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  11308. "}",
  11309. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11310. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11311. THREE.ShaderChunk[ "fog_fragment" ],
  11312. "}"
  11313. ].join("\n"),
  11314. vertexShader: [
  11315. "attribute vec4 tangent;",
  11316. "uniform vec2 uOffset;",
  11317. "uniform vec2 uRepeat;",
  11318. "uniform bool enableDisplacement;",
  11319. "#ifdef VERTEX_TEXTURES",
  11320. "uniform sampler2D tDisplacement;",
  11321. "uniform float uDisplacementScale;",
  11322. "uniform float uDisplacementBias;",
  11323. "#endif",
  11324. "varying vec3 vTangent;",
  11325. "varying vec3 vBinormal;",
  11326. "varying vec3 vNormal;",
  11327. "varying vec2 vUv;",
  11328. "varying vec3 vWorldPosition;",
  11329. "varying vec3 vViewPosition;",
  11330. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11331. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11332. "void main() {",
  11333. THREE.ShaderChunk[ "skinbase_vertex" ],
  11334. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11335. // normal, tangent and binormal vectors
  11336. "#ifdef USE_SKINNING",
  11337. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  11338. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  11339. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  11340. "#else",
  11341. "vNormal = normalize( normalMatrix * normal );",
  11342. "vTangent = normalize( normalMatrix * tangent.xyz );",
  11343. "#endif",
  11344. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  11345. "vUv = uv * uRepeat + uOffset;",
  11346. // displacement mapping
  11347. "vec3 displacedPosition;",
  11348. "#ifdef VERTEX_TEXTURES",
  11349. "if ( enableDisplacement ) {",
  11350. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  11351. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  11352. "displacedPosition = position + normalize( normal ) * df;",
  11353. "} else {",
  11354. "#ifdef USE_SKINNING",
  11355. "vec4 skinVertex = vec4( position, 1.0 );",
  11356. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11357. "skinned += boneMatY * skinVertex * skinWeight.y;",
  11358. "displacedPosition = skinned.xyz;",
  11359. "#else",
  11360. "displacedPosition = position;",
  11361. "#endif",
  11362. "}",
  11363. "#else",
  11364. "#ifdef USE_SKINNING",
  11365. "vec4 skinVertex = vec4( position, 1.0 );",
  11366. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11367. "skinned += boneMatY * skinVertex * skinWeight.y;",
  11368. "displacedPosition = skinned.xyz;",
  11369. "#else",
  11370. "displacedPosition = position;",
  11371. "#endif",
  11372. "#endif",
  11373. //
  11374. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  11375. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  11376. "gl_Position = projectionMatrix * mvPosition;",
  11377. //
  11378. "vWorldPosition = worldPosition.xyz;",
  11379. "vViewPosition = -mvPosition.xyz;",
  11380. // shadows
  11381. "#ifdef USE_SHADOWMAP",
  11382. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  11383. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  11384. "}",
  11385. "#endif",
  11386. "}"
  11387. ].join("\n")
  11388. },
  11389. /* -------------------------------------------------------------------------
  11390. // Cube map shader
  11391. ------------------------------------------------------------------------- */
  11392. 'cube': {
  11393. uniforms: { "tCube": { type: "t", value: null },
  11394. "tFlip": { type: "f", value: -1 } },
  11395. vertexShader: [
  11396. "varying vec3 vWorldPosition;",
  11397. "void main() {",
  11398. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  11399. "vWorldPosition = worldPosition.xyz;",
  11400. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11401. "}"
  11402. ].join("\n"),
  11403. fragmentShader: [
  11404. "uniform samplerCube tCube;",
  11405. "uniform float tFlip;",
  11406. "varying vec3 vWorldPosition;",
  11407. "void main() {",
  11408. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  11409. "}"
  11410. ].join("\n")
  11411. },
  11412. // Depth encoding into RGBA texture
  11413. // based on SpiderGL shadow map example
  11414. // http://spidergl.org/example.php?id=6
  11415. // originally from
  11416. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  11417. // see also here:
  11418. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  11419. 'depthRGBA': {
  11420. uniforms: {},
  11421. vertexShader: [
  11422. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11423. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11424. "void main() {",
  11425. THREE.ShaderChunk[ "skinbase_vertex" ],
  11426. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11427. THREE.ShaderChunk[ "skinning_vertex" ],
  11428. THREE.ShaderChunk[ "default_vertex" ],
  11429. "}"
  11430. ].join("\n"),
  11431. fragmentShader: [
  11432. "vec4 pack_depth( const in float depth ) {",
  11433. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  11434. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  11435. "vec4 res = fract( depth * bit_shift );",
  11436. "res -= res.xxyz * bit_mask;",
  11437. "return res;",
  11438. "}",
  11439. "void main() {",
  11440. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  11441. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  11442. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  11443. //"gl_FragData[ 0 ] = pack_depth( z );",
  11444. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  11445. "}"
  11446. ].join("\n")
  11447. }
  11448. };
  11449. /**
  11450. * @author supereggbert / http://www.paulbrunt.co.uk/
  11451. * @author mrdoob / http://mrdoob.com/
  11452. * @author alteredq / http://alteredqualia.com/
  11453. * @author szimek / https://github.com/szimek/
  11454. */
  11455. THREE.WebGLRenderer = function ( parameters ) {
  11456. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  11457. parameters = parameters || {};
  11458. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  11459. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  11460. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  11461. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  11462. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  11463. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  11464. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  11465. _clearColor = new THREE.Color( 0x000000 ),
  11466. _clearAlpha = 0;
  11467. if ( parameters.clearColor !== undefined ) {
  11468. console.warn( 'DEPRECATED: clearColor in WebGLRenderer constructor parameters is being removed. Use .setClearColor() instead.' );
  11469. _clearColor.setHex( parameters.clearColor );
  11470. }
  11471. if ( parameters.clearAlpha !== undefined ) {
  11472. console.warn( 'DEPRECATED: clearAlpha in WebGLRenderer constructor parameters is being removed. Use .setClearColor() instead.' );
  11473. _clearAlpha = parameters.clearAlpha;
  11474. }
  11475. // public properties
  11476. this.domElement = _canvas;
  11477. this.context = null;
  11478. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  11479. ? parameters.devicePixelRatio
  11480. : window.devicePixelRatio !== undefined
  11481. ? window.devicePixelRatio
  11482. : 1;
  11483. // clearing
  11484. this.autoClear = true;
  11485. this.autoClearColor = true;
  11486. this.autoClearDepth = true;
  11487. this.autoClearStencil = true;
  11488. // scene graph
  11489. this.sortObjects = true;
  11490. this.autoUpdateObjects = true;
  11491. // physically based shading
  11492. this.gammaInput = false;
  11493. this.gammaOutput = false;
  11494. this.physicallyBasedShading = false;
  11495. // shadow map
  11496. this.shadowMapEnabled = false;
  11497. this.shadowMapAutoUpdate = true;
  11498. this.shadowMapType = THREE.PCFShadowMap;
  11499. this.shadowMapCullFace = THREE.CullFaceFront;
  11500. this.shadowMapDebug = false;
  11501. this.shadowMapCascade = false;
  11502. // morphs
  11503. this.maxMorphTargets = 8;
  11504. this.maxMorphNormals = 4;
  11505. // flags
  11506. this.autoScaleCubemaps = true;
  11507. // custom render plugins
  11508. this.renderPluginsPre = [];
  11509. this.renderPluginsPost = [];
  11510. // info
  11511. this.info = {
  11512. memory: {
  11513. programs: 0,
  11514. geometries: 0,
  11515. textures: 0
  11516. },
  11517. render: {
  11518. calls: 0,
  11519. vertices: 0,
  11520. faces: 0,
  11521. points: 0
  11522. }
  11523. };
  11524. // internal properties
  11525. var _this = this,
  11526. _programs = [],
  11527. _programs_counter = 0,
  11528. // internal state cache
  11529. _currentProgram = null,
  11530. _currentFramebuffer = null,
  11531. _currentMaterialId = -1,
  11532. _currentGeometryGroupHash = null,
  11533. _currentCamera = null,
  11534. _geometryGroupCounter = 0,
  11535. _usedTextureUnits = 0,
  11536. // GL state cache
  11537. _oldDoubleSided = -1,
  11538. _oldFlipSided = -1,
  11539. _oldBlending = -1,
  11540. _oldBlendEquation = -1,
  11541. _oldBlendSrc = -1,
  11542. _oldBlendDst = -1,
  11543. _oldDepthTest = -1,
  11544. _oldDepthWrite = -1,
  11545. _oldPolygonOffset = null,
  11546. _oldPolygonOffsetFactor = null,
  11547. _oldPolygonOffsetUnits = null,
  11548. _oldLineWidth = null,
  11549. _viewportX = 0,
  11550. _viewportY = 0,
  11551. _viewportWidth = 0,
  11552. _viewportHeight = 0,
  11553. _currentWidth = 0,
  11554. _currentHeight = 0,
  11555. _enabledAttributes = {},
  11556. // frustum
  11557. _frustum = new THREE.Frustum(),
  11558. // camera matrices cache
  11559. _projScreenMatrix = new THREE.Matrix4(),
  11560. _projScreenMatrixPS = new THREE.Matrix4(),
  11561. _vector3 = new THREE.Vector3(),
  11562. // light arrays cache
  11563. _direction = new THREE.Vector3(),
  11564. _lightsNeedUpdate = true,
  11565. _lights = {
  11566. ambient: [ 0, 0, 0 ],
  11567. directional: { length: 0, colors: new Array(), positions: new Array() },
  11568. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  11569. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  11570. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  11571. };
  11572. // initialize
  11573. var _gl;
  11574. var _glExtensionTextureFloat;
  11575. var _glExtensionTextureFloatLinear;
  11576. var _glExtensionStandardDerivatives;
  11577. var _glExtensionTextureFilterAnisotropic;
  11578. var _glExtensionCompressedTextureS3TC;
  11579. initGL();
  11580. setDefaultGLState();
  11581. this.context = _gl;
  11582. // GPU capabilities
  11583. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  11584. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  11585. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  11586. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  11587. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  11588. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  11589. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  11590. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  11591. //
  11592. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  11593. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  11594. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  11595. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  11596. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  11597. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  11598. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  11599. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  11600. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  11601. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  11602. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  11603. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  11604. // clamp precision to maximum available
  11605. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  11606. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  11607. if ( _precision === "highp" && ! highpAvailable ) {
  11608. if ( mediumpAvailable ) {
  11609. _precision = "mediump";
  11610. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  11611. } else {
  11612. _precision = "lowp";
  11613. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  11614. }
  11615. }
  11616. if ( _precision === "mediump" && ! mediumpAvailable ) {
  11617. _precision = "lowp";
  11618. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  11619. }
  11620. // API
  11621. this.getContext = function () {
  11622. return _gl;
  11623. };
  11624. this.supportsVertexTextures = function () {
  11625. return _supportsVertexTextures;
  11626. };
  11627. this.supportsFloatTextures = function () {
  11628. return _glExtensionTextureFloat;
  11629. };
  11630. this.supportsStandardDerivatives = function () {
  11631. return _glExtensionStandardDerivatives;
  11632. };
  11633. this.supportsCompressedTextureS3TC = function () {
  11634. return _glExtensionCompressedTextureS3TC;
  11635. };
  11636. this.getMaxAnisotropy = function () {
  11637. return _maxAnisotropy;
  11638. };
  11639. this.getPrecision = function () {
  11640. return _precision;
  11641. };
  11642. this.setSize = function ( width, height, updateStyle ) {
  11643. _canvas.width = width * this.devicePixelRatio;
  11644. _canvas.height = height * this.devicePixelRatio;
  11645. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  11646. _canvas.style.width = width + 'px';
  11647. _canvas.style.height = height + 'px';
  11648. }
  11649. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  11650. };
  11651. this.setViewport = function ( x, y, width, height ) {
  11652. _viewportX = x !== undefined ? x : 0;
  11653. _viewportY = y !== undefined ? y : 0;
  11654. _viewportWidth = width !== undefined ? width : _canvas.width;
  11655. _viewportHeight = height !== undefined ? height : _canvas.height;
  11656. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  11657. };
  11658. this.setScissor = function ( x, y, width, height ) {
  11659. _gl.scissor( x, y, width, height );
  11660. };
  11661. this.enableScissorTest = function ( enable ) {
  11662. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  11663. };
  11664. // Clearing
  11665. this.setClearColor = function ( color, alpha ) {
  11666. _clearColor.set( color );
  11667. _clearAlpha = alpha !== undefined ? alpha : 1;
  11668. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11669. };
  11670. this.setClearColorHex = function ( hex, alpha ) {
  11671. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  11672. this.setClearColor( hex, alpha );
  11673. };
  11674. this.getClearColor = function () {
  11675. return _clearColor;
  11676. };
  11677. this.getClearAlpha = function () {
  11678. return _clearAlpha;
  11679. };
  11680. this.clear = function ( color, depth, stencil ) {
  11681. var bits = 0;
  11682. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  11683. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  11684. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  11685. _gl.clear( bits );
  11686. };
  11687. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  11688. this.setRenderTarget( renderTarget );
  11689. this.clear( color, depth, stencil );
  11690. };
  11691. // Plugins
  11692. this.addPostPlugin = function ( plugin ) {
  11693. plugin.init( this );
  11694. this.renderPluginsPost.push( plugin );
  11695. };
  11696. this.addPrePlugin = function ( plugin ) {
  11697. plugin.init( this );
  11698. this.renderPluginsPre.push( plugin );
  11699. };
  11700. // Rendering
  11701. this.updateShadowMap = function ( scene, camera ) {
  11702. _currentProgram = null;
  11703. _oldBlending = -1;
  11704. _oldDepthTest = -1;
  11705. _oldDepthWrite = -1;
  11706. _currentGeometryGroupHash = -1;
  11707. _currentMaterialId = -1;
  11708. _lightsNeedUpdate = true;
  11709. _oldDoubleSided = -1;
  11710. _oldFlipSided = -1;
  11711. this.shadowMapPlugin.update( scene, camera );
  11712. };
  11713. // Internal functions
  11714. // Buffer allocation
  11715. function createParticleBuffers ( geometry ) {
  11716. geometry.__webglVertexBuffer = _gl.createBuffer();
  11717. geometry.__webglColorBuffer = _gl.createBuffer();
  11718. _this.info.memory.geometries ++;
  11719. };
  11720. function createLineBuffers ( geometry ) {
  11721. geometry.__webglVertexBuffer = _gl.createBuffer();
  11722. geometry.__webglColorBuffer = _gl.createBuffer();
  11723. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  11724. _this.info.memory.geometries ++;
  11725. };
  11726. function createRibbonBuffers ( geometry ) {
  11727. geometry.__webglVertexBuffer = _gl.createBuffer();
  11728. geometry.__webglColorBuffer = _gl.createBuffer();
  11729. geometry.__webglNormalBuffer = _gl.createBuffer();
  11730. _this.info.memory.geometries ++;
  11731. };
  11732. function createMeshBuffers ( geometryGroup ) {
  11733. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  11734. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  11735. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  11736. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  11737. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  11738. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  11739. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  11740. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  11741. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  11742. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  11743. var m, ml;
  11744. if ( geometryGroup.numMorphTargets ) {
  11745. geometryGroup.__webglMorphTargetsBuffers = [];
  11746. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11747. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  11748. }
  11749. }
  11750. if ( geometryGroup.numMorphNormals ) {
  11751. geometryGroup.__webglMorphNormalsBuffers = [];
  11752. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11753. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  11754. }
  11755. }
  11756. _this.info.memory.geometries ++;
  11757. };
  11758. // Events
  11759. var onGeometryDispose = function ( event ) {
  11760. var geometry = event.target;
  11761. geometry.removeEventListener( 'dispose', onGeometryDispose );
  11762. deallocateGeometry( geometry );
  11763. _this.info.memory.geometries --;
  11764. };
  11765. var onTextureDispose = function ( event ) {
  11766. var texture = event.target;
  11767. texture.removeEventListener( 'dispose', onTextureDispose );
  11768. deallocateTexture( texture );
  11769. _this.info.memory.textures --;
  11770. };
  11771. var onRenderTargetDispose = function ( event ) {
  11772. var renderTarget = event.target;
  11773. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  11774. deallocateRenderTarget( renderTarget );
  11775. _this.info.memory.textures --;
  11776. };
  11777. var onMaterialDispose = function ( event ) {
  11778. var material = event.target;
  11779. material.removeEventListener( 'dispose', onMaterialDispose );
  11780. deallocateMaterial( material );
  11781. };
  11782. // Buffer deallocation
  11783. var deallocateGeometry = function ( geometry ) {
  11784. geometry.__webglInit = undefined;
  11785. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  11786. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  11787. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  11788. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  11789. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  11790. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  11791. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  11792. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  11793. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  11794. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  11795. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  11796. // geometry groups
  11797. if ( geometry.geometryGroups !== undefined ) {
  11798. for ( var g in geometry.geometryGroups ) {
  11799. var geometryGroup = geometry.geometryGroups[ g ];
  11800. if ( geometryGroup.numMorphTargets !== undefined ) {
  11801. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11802. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  11803. }
  11804. }
  11805. if ( geometryGroup.numMorphNormals !== undefined ) {
  11806. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11807. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  11808. }
  11809. }
  11810. deleteCustomAttributesBuffers( geometryGroup );
  11811. }
  11812. }
  11813. deleteCustomAttributesBuffers( geometry );
  11814. };
  11815. var deallocateTexture = function ( texture ) {
  11816. if ( texture.image && texture.image.__webglTextureCube ) {
  11817. // cube texture
  11818. _gl.deleteTexture( texture.image.__webglTextureCube );
  11819. } else {
  11820. // 2D texture
  11821. if ( ! texture.__webglInit ) return;
  11822. texture.__webglInit = false;
  11823. _gl.deleteTexture( texture.__webglTexture );
  11824. }
  11825. };
  11826. var deallocateRenderTarget = function ( renderTarget ) {
  11827. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  11828. _gl.deleteTexture( renderTarget.__webglTexture );
  11829. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  11830. for ( var i = 0; i < 6; i ++ ) {
  11831. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  11832. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  11833. }
  11834. } else {
  11835. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  11836. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  11837. }
  11838. };
  11839. var deallocateMaterial = function ( material ) {
  11840. var program = material.program;
  11841. if ( program === undefined ) return;
  11842. material.program = undefined;
  11843. // only deallocate GL program if this was the last use of shared program
  11844. // assumed there is only single copy of any program in the _programs list
  11845. // (that's how it's constructed)
  11846. var i, il, programInfo;
  11847. var deleteProgram = false;
  11848. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11849. programInfo = _programs[ i ];
  11850. if ( programInfo.program === program ) {
  11851. programInfo.usedTimes --;
  11852. if ( programInfo.usedTimes === 0 ) {
  11853. deleteProgram = true;
  11854. }
  11855. break;
  11856. }
  11857. }
  11858. if ( deleteProgram === true ) {
  11859. // avoid using array.splice, this is costlier than creating new array from scratch
  11860. var newPrograms = [];
  11861. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11862. programInfo = _programs[ i ];
  11863. if ( programInfo.program !== program ) {
  11864. newPrograms.push( programInfo );
  11865. }
  11866. }
  11867. _programs = newPrograms;
  11868. _gl.deleteProgram( program );
  11869. _this.info.memory.programs --;
  11870. }
  11871. };
  11872. //
  11873. function deleteCustomAttributesBuffers( geometry ) {
  11874. if ( geometry.__webglCustomAttributesList ) {
  11875. for ( var id in geometry.__webglCustomAttributesList ) {
  11876. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  11877. }
  11878. }
  11879. };
  11880. // Buffer initialization
  11881. function initCustomAttributes ( geometry, object ) {
  11882. var nvertices = geometry.vertices.length;
  11883. var material = object.material;
  11884. if ( material.attributes ) {
  11885. if ( geometry.__webglCustomAttributesList === undefined ) {
  11886. geometry.__webglCustomAttributesList = [];
  11887. }
  11888. for ( var a in material.attributes ) {
  11889. var attribute = material.attributes[ a ];
  11890. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  11891. attribute.__webglInitialized = true;
  11892. var size = 1; // "f" and "i"
  11893. if ( attribute.type === "v2" ) size = 2;
  11894. else if ( attribute.type === "v3" ) size = 3;
  11895. else if ( attribute.type === "v4" ) size = 4;
  11896. else if ( attribute.type === "c" ) size = 3;
  11897. attribute.size = size;
  11898. attribute.array = new Float32Array( nvertices * size );
  11899. attribute.buffer = _gl.createBuffer();
  11900. attribute.buffer.belongsToAttribute = a;
  11901. attribute.needsUpdate = true;
  11902. }
  11903. geometry.__webglCustomAttributesList.push( attribute );
  11904. }
  11905. }
  11906. };
  11907. function initParticleBuffers ( geometry, object ) {
  11908. var nvertices = geometry.vertices.length;
  11909. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11910. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11911. geometry.__sortArray = [];
  11912. geometry.__webglParticleCount = nvertices;
  11913. initCustomAttributes ( geometry, object );
  11914. };
  11915. function initLineBuffers ( geometry, object ) {
  11916. var nvertices = geometry.vertices.length;
  11917. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11918. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11919. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  11920. geometry.__webglLineCount = nvertices;
  11921. initCustomAttributes ( geometry, object );
  11922. };
  11923. function initRibbonBuffers ( geometry, object ) {
  11924. var nvertices = geometry.vertices.length;
  11925. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11926. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11927. geometry.__normalArray = new Float32Array( nvertices * 3 );
  11928. geometry.__webglVertexCount = nvertices;
  11929. initCustomAttributes ( geometry, object );
  11930. };
  11931. function initMeshBuffers ( geometryGroup, object ) {
  11932. var geometry = object.geometry,
  11933. faces3 = geometryGroup.faces3,
  11934. faces4 = geometryGroup.faces4,
  11935. nvertices = faces3.length * 3 + faces4.length * 4,
  11936. ntris = faces3.length * 1 + faces4.length * 2,
  11937. nlines = faces3.length * 3 + faces4.length * 4,
  11938. material = getBufferMaterial( object, geometryGroup ),
  11939. uvType = bufferGuessUVType( material ),
  11940. normalType = bufferGuessNormalType( material ),
  11941. vertexColorType = bufferGuessVertexColorType( material );
  11942. // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  11943. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  11944. if ( normalType ) {
  11945. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  11946. }
  11947. if ( geometry.hasTangents ) {
  11948. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  11949. }
  11950. if ( vertexColorType ) {
  11951. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  11952. }
  11953. if ( uvType ) {
  11954. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  11955. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  11956. }
  11957. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  11958. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  11959. }
  11960. }
  11961. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  11962. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  11963. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  11964. }
  11965. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  11966. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  11967. var m, ml;
  11968. if ( geometryGroup.numMorphTargets ) {
  11969. geometryGroup.__morphTargetsArrays = [];
  11970. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11971. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  11972. }
  11973. }
  11974. if ( geometryGroup.numMorphNormals ) {
  11975. geometryGroup.__morphNormalsArrays = [];
  11976. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11977. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  11978. }
  11979. }
  11980. geometryGroup.__webglFaceCount = ntris * 3;
  11981. geometryGroup.__webglLineCount = nlines * 2;
  11982. // custom attributes
  11983. if ( material.attributes ) {
  11984. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  11985. geometryGroup.__webglCustomAttributesList = [];
  11986. }
  11987. for ( var a in material.attributes ) {
  11988. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  11989. // attribute buffers which are correctly indexed in the setMeshBuffers function
  11990. var originalAttribute = material.attributes[ a ];
  11991. var attribute = {};
  11992. for ( var property in originalAttribute ) {
  11993. attribute[ property ] = originalAttribute[ property ];
  11994. }
  11995. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  11996. attribute.__webglInitialized = true;
  11997. var size = 1; // "f" and "i"
  11998. if( attribute.type === "v2" ) size = 2;
  11999. else if( attribute.type === "v3" ) size = 3;
  12000. else if( attribute.type === "v4" ) size = 4;
  12001. else if( attribute.type === "c" ) size = 3;
  12002. attribute.size = size;
  12003. attribute.array = new Float32Array( nvertices * size );
  12004. attribute.buffer = _gl.createBuffer();
  12005. attribute.buffer.belongsToAttribute = a;
  12006. originalAttribute.needsUpdate = true;
  12007. attribute.__original = originalAttribute;
  12008. }
  12009. geometryGroup.__webglCustomAttributesList.push( attribute );
  12010. }
  12011. }
  12012. geometryGroup.__inittedArrays = true;
  12013. };
  12014. function getBufferMaterial( object, geometryGroup ) {
  12015. return object.material instanceof THREE.MeshFaceMaterial
  12016. ? object.material.materials[ geometryGroup.materialIndex ]
  12017. : object.material;
  12018. };
  12019. function materialNeedsSmoothNormals ( material ) {
  12020. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  12021. };
  12022. function bufferGuessNormalType ( material ) {
  12023. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  12024. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  12025. return false;
  12026. }
  12027. if ( materialNeedsSmoothNormals( material ) ) {
  12028. return THREE.SmoothShading;
  12029. } else {
  12030. return THREE.FlatShading;
  12031. }
  12032. };
  12033. function bufferGuessVertexColorType( material ) {
  12034. if ( material.vertexColors ) {
  12035. return material.vertexColors;
  12036. }
  12037. return false;
  12038. };
  12039. function bufferGuessUVType( material ) {
  12040. // material must use some texture to require uvs
  12041. if ( material.map ||
  12042. material.lightMap ||
  12043. material.bumpMap ||
  12044. material.normalMap ||
  12045. material.specularMap ||
  12046. material instanceof THREE.ShaderMaterial ) {
  12047. return true;
  12048. }
  12049. return false;
  12050. };
  12051. //
  12052. function initDirectBuffers( geometry ) {
  12053. var a, attribute, type;
  12054. for ( a in geometry.attributes ) {
  12055. if ( a === "index" ) {
  12056. type = _gl.ELEMENT_ARRAY_BUFFER;
  12057. } else {
  12058. type = _gl.ARRAY_BUFFER;
  12059. }
  12060. attribute = geometry.attributes[ a ];
  12061. if ( attribute.numItems === undefined ) {
  12062. attribute.numItems = attribute.array.length;
  12063. }
  12064. attribute.buffer = _gl.createBuffer();
  12065. _gl.bindBuffer( type, attribute.buffer );
  12066. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  12067. }
  12068. };
  12069. // Buffer setting
  12070. function setParticleBuffers ( geometry, hint, object ) {
  12071. var v, c, vertex, offset, index, color,
  12072. vertices = geometry.vertices,
  12073. vl = vertices.length,
  12074. colors = geometry.colors,
  12075. cl = colors.length,
  12076. vertexArray = geometry.__vertexArray,
  12077. colorArray = geometry.__colorArray,
  12078. sortArray = geometry.__sortArray,
  12079. dirtyVertices = geometry.verticesNeedUpdate,
  12080. dirtyElements = geometry.elementsNeedUpdate,
  12081. dirtyColors = geometry.colorsNeedUpdate,
  12082. customAttributes = geometry.__webglCustomAttributesList,
  12083. i, il,
  12084. a, ca, cal, value,
  12085. customAttribute;
  12086. if ( object.sortParticles ) {
  12087. _projScreenMatrixPS.copy( _projScreenMatrix );
  12088. _projScreenMatrixPS.multiply( object.matrixWorld );
  12089. for ( v = 0; v < vl; v ++ ) {
  12090. vertex = vertices[ v ];
  12091. _vector3.copy( vertex );
  12092. _vector3.applyProjection( _projScreenMatrixPS );
  12093. sortArray[ v ] = [ _vector3.z, v ];
  12094. }
  12095. sortArray.sort( numericalSort );
  12096. for ( v = 0; v < vl; v ++ ) {
  12097. vertex = vertices[ sortArray[v][1] ];
  12098. offset = v * 3;
  12099. vertexArray[ offset ] = vertex.x;
  12100. vertexArray[ offset + 1 ] = vertex.y;
  12101. vertexArray[ offset + 2 ] = vertex.z;
  12102. }
  12103. for ( c = 0; c < cl; c ++ ) {
  12104. offset = c * 3;
  12105. color = colors[ sortArray[c][1] ];
  12106. colorArray[ offset ] = color.r;
  12107. colorArray[ offset + 1 ] = color.g;
  12108. colorArray[ offset + 2 ] = color.b;
  12109. }
  12110. if ( customAttributes ) {
  12111. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12112. customAttribute = customAttributes[ i ];
  12113. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  12114. offset = 0;
  12115. cal = customAttribute.value.length;
  12116. if ( customAttribute.size === 1 ) {
  12117. for ( ca = 0; ca < cal; ca ++ ) {
  12118. index = sortArray[ ca ][ 1 ];
  12119. customAttribute.array[ ca ] = customAttribute.value[ index ];
  12120. }
  12121. } else if ( customAttribute.size === 2 ) {
  12122. for ( ca = 0; ca < cal; ca ++ ) {
  12123. index = sortArray[ ca ][ 1 ];
  12124. value = customAttribute.value[ index ];
  12125. customAttribute.array[ offset ] = value.x;
  12126. customAttribute.array[ offset + 1 ] = value.y;
  12127. offset += 2;
  12128. }
  12129. } else if ( customAttribute.size === 3 ) {
  12130. if ( customAttribute.type === "c" ) {
  12131. for ( ca = 0; ca < cal; ca ++ ) {
  12132. index = sortArray[ ca ][ 1 ];
  12133. value = customAttribute.value[ index ];
  12134. customAttribute.array[ offset ] = value.r;
  12135. customAttribute.array[ offset + 1 ] = value.g;
  12136. customAttribute.array[ offset + 2 ] = value.b;
  12137. offset += 3;
  12138. }
  12139. } else {
  12140. for ( ca = 0; ca < cal; ca ++ ) {
  12141. index = sortArray[ ca ][ 1 ];
  12142. value = customAttribute.value[ index ];
  12143. customAttribute.array[ offset ] = value.x;
  12144. customAttribute.array[ offset + 1 ] = value.y;
  12145. customAttribute.array[ offset + 2 ] = value.z;
  12146. offset += 3;
  12147. }
  12148. }
  12149. } else if ( customAttribute.size === 4 ) {
  12150. for ( ca = 0; ca < cal; ca ++ ) {
  12151. index = sortArray[ ca ][ 1 ];
  12152. value = customAttribute.value[ index ];
  12153. customAttribute.array[ offset ] = value.x;
  12154. customAttribute.array[ offset + 1 ] = value.y;
  12155. customAttribute.array[ offset + 2 ] = value.z;
  12156. customAttribute.array[ offset + 3 ] = value.w;
  12157. offset += 4;
  12158. }
  12159. }
  12160. }
  12161. }
  12162. } else {
  12163. if ( dirtyVertices ) {
  12164. for ( v = 0; v < vl; v ++ ) {
  12165. vertex = vertices[ v ];
  12166. offset = v * 3;
  12167. vertexArray[ offset ] = vertex.x;
  12168. vertexArray[ offset + 1 ] = vertex.y;
  12169. vertexArray[ offset + 2 ] = vertex.z;
  12170. }
  12171. }
  12172. if ( dirtyColors ) {
  12173. for ( c = 0; c < cl; c ++ ) {
  12174. color = colors[ c ];
  12175. offset = c * 3;
  12176. colorArray[ offset ] = color.r;
  12177. colorArray[ offset + 1 ] = color.g;
  12178. colorArray[ offset + 2 ] = color.b;
  12179. }
  12180. }
  12181. if ( customAttributes ) {
  12182. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12183. customAttribute = customAttributes[ i ];
  12184. if ( customAttribute.needsUpdate &&
  12185. ( customAttribute.boundTo === undefined ||
  12186. customAttribute.boundTo === "vertices") ) {
  12187. cal = customAttribute.value.length;
  12188. offset = 0;
  12189. if ( customAttribute.size === 1 ) {
  12190. for ( ca = 0; ca < cal; ca ++ ) {
  12191. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12192. }
  12193. } else if ( customAttribute.size === 2 ) {
  12194. for ( ca = 0; ca < cal; ca ++ ) {
  12195. value = customAttribute.value[ ca ];
  12196. customAttribute.array[ offset ] = value.x;
  12197. customAttribute.array[ offset + 1 ] = value.y;
  12198. offset += 2;
  12199. }
  12200. } else if ( customAttribute.size === 3 ) {
  12201. if ( customAttribute.type === "c" ) {
  12202. for ( ca = 0; ca < cal; ca ++ ) {
  12203. value = customAttribute.value[ ca ];
  12204. customAttribute.array[ offset ] = value.r;
  12205. customAttribute.array[ offset + 1 ] = value.g;
  12206. customAttribute.array[ offset + 2 ] = value.b;
  12207. offset += 3;
  12208. }
  12209. } else {
  12210. for ( ca = 0; ca < cal; ca ++ ) {
  12211. value = customAttribute.value[ ca ];
  12212. customAttribute.array[ offset ] = value.x;
  12213. customAttribute.array[ offset + 1 ] = value.y;
  12214. customAttribute.array[ offset + 2 ] = value.z;
  12215. offset += 3;
  12216. }
  12217. }
  12218. } else if ( customAttribute.size === 4 ) {
  12219. for ( ca = 0; ca < cal; ca ++ ) {
  12220. value = customAttribute.value[ ca ];
  12221. customAttribute.array[ offset ] = value.x;
  12222. customAttribute.array[ offset + 1 ] = value.y;
  12223. customAttribute.array[ offset + 2 ] = value.z;
  12224. customAttribute.array[ offset + 3 ] = value.w;
  12225. offset += 4;
  12226. }
  12227. }
  12228. }
  12229. }
  12230. }
  12231. }
  12232. if ( dirtyVertices || object.sortParticles ) {
  12233. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12234. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12235. }
  12236. if ( dirtyColors || object.sortParticles ) {
  12237. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12238. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12239. }
  12240. if ( customAttributes ) {
  12241. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12242. customAttribute = customAttributes[ i ];
  12243. if ( customAttribute.needsUpdate || object.sortParticles ) {
  12244. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12245. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12246. }
  12247. }
  12248. }
  12249. };
  12250. function setLineBuffers ( geometry, hint ) {
  12251. var v, c, d, vertex, offset, color,
  12252. vertices = geometry.vertices,
  12253. colors = geometry.colors,
  12254. lineDistances = geometry.lineDistances,
  12255. vl = vertices.length,
  12256. cl = colors.length,
  12257. dl = lineDistances.length,
  12258. vertexArray = geometry.__vertexArray,
  12259. colorArray = geometry.__colorArray,
  12260. lineDistanceArray = geometry.__lineDistanceArray,
  12261. dirtyVertices = geometry.verticesNeedUpdate,
  12262. dirtyColors = geometry.colorsNeedUpdate,
  12263. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  12264. customAttributes = geometry.__webglCustomAttributesList,
  12265. i, il,
  12266. a, ca, cal, value,
  12267. customAttribute;
  12268. if ( dirtyVertices ) {
  12269. for ( v = 0; v < vl; v ++ ) {
  12270. vertex = vertices[ v ];
  12271. offset = v * 3;
  12272. vertexArray[ offset ] = vertex.x;
  12273. vertexArray[ offset + 1 ] = vertex.y;
  12274. vertexArray[ offset + 2 ] = vertex.z;
  12275. }
  12276. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12277. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12278. }
  12279. if ( dirtyColors ) {
  12280. for ( c = 0; c < cl; c ++ ) {
  12281. color = colors[ c ];
  12282. offset = c * 3;
  12283. colorArray[ offset ] = color.r;
  12284. colorArray[ offset + 1 ] = color.g;
  12285. colorArray[ offset + 2 ] = color.b;
  12286. }
  12287. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12288. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12289. }
  12290. if ( dirtyLineDistances ) {
  12291. for ( d = 0; d < dl; d ++ ) {
  12292. lineDistanceArray[ d ] = lineDistances[ d ];
  12293. }
  12294. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  12295. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  12296. }
  12297. if ( customAttributes ) {
  12298. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12299. customAttribute = customAttributes[ i ];
  12300. if ( customAttribute.needsUpdate &&
  12301. ( customAttribute.boundTo === undefined ||
  12302. customAttribute.boundTo === "vertices" ) ) {
  12303. offset = 0;
  12304. cal = customAttribute.value.length;
  12305. if ( customAttribute.size === 1 ) {
  12306. for ( ca = 0; ca < cal; ca ++ ) {
  12307. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12308. }
  12309. } else if ( customAttribute.size === 2 ) {
  12310. for ( ca = 0; ca < cal; ca ++ ) {
  12311. value = customAttribute.value[ ca ];
  12312. customAttribute.array[ offset ] = value.x;
  12313. customAttribute.array[ offset + 1 ] = value.y;
  12314. offset += 2;
  12315. }
  12316. } else if ( customAttribute.size === 3 ) {
  12317. if ( customAttribute.type === "c" ) {
  12318. for ( ca = 0; ca < cal; ca ++ ) {
  12319. value = customAttribute.value[ ca ];
  12320. customAttribute.array[ offset ] = value.r;
  12321. customAttribute.array[ offset + 1 ] = value.g;
  12322. customAttribute.array[ offset + 2 ] = value.b;
  12323. offset += 3;
  12324. }
  12325. } else {
  12326. for ( ca = 0; ca < cal; ca ++ ) {
  12327. value = customAttribute.value[ ca ];
  12328. customAttribute.array[ offset ] = value.x;
  12329. customAttribute.array[ offset + 1 ] = value.y;
  12330. customAttribute.array[ offset + 2 ] = value.z;
  12331. offset += 3;
  12332. }
  12333. }
  12334. } else if ( customAttribute.size === 4 ) {
  12335. for ( ca = 0; ca < cal; ca ++ ) {
  12336. value = customAttribute.value[ ca ];
  12337. customAttribute.array[ offset ] = value.x;
  12338. customAttribute.array[ offset + 1 ] = value.y;
  12339. customAttribute.array[ offset + 2 ] = value.z;
  12340. customAttribute.array[ offset + 3 ] = value.w;
  12341. offset += 4;
  12342. }
  12343. }
  12344. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12345. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12346. }
  12347. }
  12348. }
  12349. };
  12350. function setRibbonBuffers ( geometry, hint ) {
  12351. var v, c, n, vertex, offset, color, normal,
  12352. i, il, ca, cal, customAttribute, value,
  12353. vertices = geometry.vertices,
  12354. colors = geometry.colors,
  12355. normals = geometry.normals,
  12356. vl = vertices.length,
  12357. cl = colors.length,
  12358. nl = normals.length,
  12359. vertexArray = geometry.__vertexArray,
  12360. colorArray = geometry.__colorArray,
  12361. normalArray = geometry.__normalArray,
  12362. dirtyVertices = geometry.verticesNeedUpdate,
  12363. dirtyColors = geometry.colorsNeedUpdate,
  12364. dirtyNormals = geometry.normalsNeedUpdate,
  12365. customAttributes = geometry.__webglCustomAttributesList;
  12366. if ( dirtyVertices ) {
  12367. for ( v = 0; v < vl; v ++ ) {
  12368. vertex = vertices[ v ];
  12369. offset = v * 3;
  12370. vertexArray[ offset ] = vertex.x;
  12371. vertexArray[ offset + 1 ] = vertex.y;
  12372. vertexArray[ offset + 2 ] = vertex.z;
  12373. }
  12374. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12375. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12376. }
  12377. if ( dirtyColors ) {
  12378. for ( c = 0; c < cl; c ++ ) {
  12379. color = colors[ c ];
  12380. offset = c * 3;
  12381. colorArray[ offset ] = color.r;
  12382. colorArray[ offset + 1 ] = color.g;
  12383. colorArray[ offset + 2 ] = color.b;
  12384. }
  12385. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12386. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12387. }
  12388. if ( dirtyNormals ) {
  12389. for ( n = 0; n < nl; n ++ ) {
  12390. normal = normals[ n ];
  12391. offset = n * 3;
  12392. normalArray[ offset ] = normal.x;
  12393. normalArray[ offset + 1 ] = normal.y;
  12394. normalArray[ offset + 2 ] = normal.z;
  12395. }
  12396. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglNormalBuffer );
  12397. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  12398. }
  12399. if ( customAttributes ) {
  12400. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12401. customAttribute = customAttributes[ i ];
  12402. if ( customAttribute.needsUpdate &&
  12403. ( customAttribute.boundTo === undefined ||
  12404. customAttribute.boundTo === "vertices" ) ) {
  12405. offset = 0;
  12406. cal = customAttribute.value.length;
  12407. if ( customAttribute.size === 1 ) {
  12408. for ( ca = 0; ca < cal; ca ++ ) {
  12409. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12410. }
  12411. } else if ( customAttribute.size === 2 ) {
  12412. for ( ca = 0; ca < cal; ca ++ ) {
  12413. value = customAttribute.value[ ca ];
  12414. customAttribute.array[ offset ] = value.x;
  12415. customAttribute.array[ offset + 1 ] = value.y;
  12416. offset += 2;
  12417. }
  12418. } else if ( customAttribute.size === 3 ) {
  12419. if ( customAttribute.type === "c" ) {
  12420. for ( ca = 0; ca < cal; ca ++ ) {
  12421. value = customAttribute.value[ ca ];
  12422. customAttribute.array[ offset ] = value.r;
  12423. customAttribute.array[ offset + 1 ] = value.g;
  12424. customAttribute.array[ offset + 2 ] = value.b;
  12425. offset += 3;
  12426. }
  12427. } else {
  12428. for ( ca = 0; ca < cal; ca ++ ) {
  12429. value = customAttribute.value[ ca ];
  12430. customAttribute.array[ offset ] = value.x;
  12431. customAttribute.array[ offset + 1 ] = value.y;
  12432. customAttribute.array[ offset + 2 ] = value.z;
  12433. offset += 3;
  12434. }
  12435. }
  12436. } else if ( customAttribute.size === 4 ) {
  12437. for ( ca = 0; ca < cal; ca ++ ) {
  12438. value = customAttribute.value[ ca ];
  12439. customAttribute.array[ offset ] = value.x;
  12440. customAttribute.array[ offset + 1 ] = value.y;
  12441. customAttribute.array[ offset + 2 ] = value.z;
  12442. customAttribute.array[ offset + 3 ] = value.w;
  12443. offset += 4;
  12444. }
  12445. }
  12446. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12447. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12448. }
  12449. }
  12450. }
  12451. };
  12452. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  12453. if ( ! geometryGroup.__inittedArrays ) {
  12454. return;
  12455. }
  12456. var normalType = bufferGuessNormalType( material ),
  12457. vertexColorType = bufferGuessVertexColorType( material ),
  12458. uvType = bufferGuessUVType( material ),
  12459. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  12460. var f, fl, fi, face,
  12461. vertexNormals, faceNormal, normal,
  12462. vertexColors, faceColor,
  12463. vertexTangents,
  12464. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  12465. c1, c2, c3, c4,
  12466. sw1, sw2, sw3, sw4,
  12467. si1, si2, si3, si4,
  12468. sa1, sa2, sa3, sa4,
  12469. sb1, sb2, sb3, sb4,
  12470. m, ml, i, il,
  12471. vn, uvi, uv2i,
  12472. vk, vkl, vka,
  12473. nka, chf, faceVertexNormals,
  12474. a,
  12475. vertexIndex = 0,
  12476. offset = 0,
  12477. offset_uv = 0,
  12478. offset_uv2 = 0,
  12479. offset_face = 0,
  12480. offset_normal = 0,
  12481. offset_tangent = 0,
  12482. offset_line = 0,
  12483. offset_color = 0,
  12484. offset_skin = 0,
  12485. offset_morphTarget = 0,
  12486. offset_custom = 0,
  12487. offset_customSrc = 0,
  12488. value,
  12489. vertexArray = geometryGroup.__vertexArray,
  12490. uvArray = geometryGroup.__uvArray,
  12491. uv2Array = geometryGroup.__uv2Array,
  12492. normalArray = geometryGroup.__normalArray,
  12493. tangentArray = geometryGroup.__tangentArray,
  12494. colorArray = geometryGroup.__colorArray,
  12495. skinIndexArray = geometryGroup.__skinIndexArray,
  12496. skinWeightArray = geometryGroup.__skinWeightArray,
  12497. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  12498. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  12499. customAttributes = geometryGroup.__webglCustomAttributesList,
  12500. customAttribute,
  12501. faceArray = geometryGroup.__faceArray,
  12502. lineArray = geometryGroup.__lineArray,
  12503. geometry = object.geometry, // this is shared for all chunks
  12504. dirtyVertices = geometry.verticesNeedUpdate,
  12505. dirtyElements = geometry.elementsNeedUpdate,
  12506. dirtyUvs = geometry.uvsNeedUpdate,
  12507. dirtyNormals = geometry.normalsNeedUpdate,
  12508. dirtyTangents = geometry.tangentsNeedUpdate,
  12509. dirtyColors = geometry.colorsNeedUpdate,
  12510. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  12511. vertices = geometry.vertices,
  12512. chunk_faces3 = geometryGroup.faces3,
  12513. chunk_faces4 = geometryGroup.faces4,
  12514. obj_faces = geometry.faces,
  12515. obj_uvs = geometry.faceVertexUvs[ 0 ],
  12516. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  12517. obj_colors = geometry.colors,
  12518. obj_skinIndices = geometry.skinIndices,
  12519. obj_skinWeights = geometry.skinWeights,
  12520. morphTargets = geometry.morphTargets,
  12521. morphNormals = geometry.morphNormals;
  12522. if ( dirtyVertices ) {
  12523. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12524. face = obj_faces[ chunk_faces3[ f ] ];
  12525. v1 = vertices[ face.a ];
  12526. v2 = vertices[ face.b ];
  12527. v3 = vertices[ face.c ];
  12528. vertexArray[ offset ] = v1.x;
  12529. vertexArray[ offset + 1 ] = v1.y;
  12530. vertexArray[ offset + 2 ] = v1.z;
  12531. vertexArray[ offset + 3 ] = v2.x;
  12532. vertexArray[ offset + 4 ] = v2.y;
  12533. vertexArray[ offset + 5 ] = v2.z;
  12534. vertexArray[ offset + 6 ] = v3.x;
  12535. vertexArray[ offset + 7 ] = v3.y;
  12536. vertexArray[ offset + 8 ] = v3.z;
  12537. offset += 9;
  12538. }
  12539. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12540. face = obj_faces[ chunk_faces4[ f ] ];
  12541. v1 = vertices[ face.a ];
  12542. v2 = vertices[ face.b ];
  12543. v3 = vertices[ face.c ];
  12544. v4 = vertices[ face.d ];
  12545. vertexArray[ offset ] = v1.x;
  12546. vertexArray[ offset + 1 ] = v1.y;
  12547. vertexArray[ offset + 2 ] = v1.z;
  12548. vertexArray[ offset + 3 ] = v2.x;
  12549. vertexArray[ offset + 4 ] = v2.y;
  12550. vertexArray[ offset + 5 ] = v2.z;
  12551. vertexArray[ offset + 6 ] = v3.x;
  12552. vertexArray[ offset + 7 ] = v3.y;
  12553. vertexArray[ offset + 8 ] = v3.z;
  12554. vertexArray[ offset + 9 ] = v4.x;
  12555. vertexArray[ offset + 10 ] = v4.y;
  12556. vertexArray[ offset + 11 ] = v4.z;
  12557. offset += 12;
  12558. }
  12559. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12560. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12561. }
  12562. if ( dirtyMorphTargets ) {
  12563. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  12564. offset_morphTarget = 0;
  12565. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12566. chf = chunk_faces3[ f ];
  12567. face = obj_faces[ chf ];
  12568. // morph positions
  12569. v1 = morphTargets[ vk ].vertices[ face.a ];
  12570. v2 = morphTargets[ vk ].vertices[ face.b ];
  12571. v3 = morphTargets[ vk ].vertices[ face.c ];
  12572. vka = morphTargetsArrays[ vk ];
  12573. vka[ offset_morphTarget ] = v1.x;
  12574. vka[ offset_morphTarget + 1 ] = v1.y;
  12575. vka[ offset_morphTarget + 2 ] = v1.z;
  12576. vka[ offset_morphTarget + 3 ] = v2.x;
  12577. vka[ offset_morphTarget + 4 ] = v2.y;
  12578. vka[ offset_morphTarget + 5 ] = v2.z;
  12579. vka[ offset_morphTarget + 6 ] = v3.x;
  12580. vka[ offset_morphTarget + 7 ] = v3.y;
  12581. vka[ offset_morphTarget + 8 ] = v3.z;
  12582. // morph normals
  12583. if ( material.morphNormals ) {
  12584. if ( needsSmoothNormals ) {
  12585. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  12586. n1 = faceVertexNormals.a;
  12587. n2 = faceVertexNormals.b;
  12588. n3 = faceVertexNormals.c;
  12589. } else {
  12590. n1 = morphNormals[ vk ].faceNormals[ chf ];
  12591. n2 = n1;
  12592. n3 = n1;
  12593. }
  12594. nka = morphNormalsArrays[ vk ];
  12595. nka[ offset_morphTarget ] = n1.x;
  12596. nka[ offset_morphTarget + 1 ] = n1.y;
  12597. nka[ offset_morphTarget + 2 ] = n1.z;
  12598. nka[ offset_morphTarget + 3 ] = n2.x;
  12599. nka[ offset_morphTarget + 4 ] = n2.y;
  12600. nka[ offset_morphTarget + 5 ] = n2.z;
  12601. nka[ offset_morphTarget + 6 ] = n3.x;
  12602. nka[ offset_morphTarget + 7 ] = n3.y;
  12603. nka[ offset_morphTarget + 8 ] = n3.z;
  12604. }
  12605. //
  12606. offset_morphTarget += 9;
  12607. }
  12608. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12609. chf = chunk_faces4[ f ];
  12610. face = obj_faces[ chf ];
  12611. // morph positions
  12612. v1 = morphTargets[ vk ].vertices[ face.a ];
  12613. v2 = morphTargets[ vk ].vertices[ face.b ];
  12614. v3 = morphTargets[ vk ].vertices[ face.c ];
  12615. v4 = morphTargets[ vk ].vertices[ face.d ];
  12616. vka = morphTargetsArrays[ vk ];
  12617. vka[ offset_morphTarget ] = v1.x;
  12618. vka[ offset_morphTarget + 1 ] = v1.y;
  12619. vka[ offset_morphTarget + 2 ] = v1.z;
  12620. vka[ offset_morphTarget + 3 ] = v2.x;
  12621. vka[ offset_morphTarget + 4 ] = v2.y;
  12622. vka[ offset_morphTarget + 5 ] = v2.z;
  12623. vka[ offset_morphTarget + 6 ] = v3.x;
  12624. vka[ offset_morphTarget + 7 ] = v3.y;
  12625. vka[ offset_morphTarget + 8 ] = v3.z;
  12626. vka[ offset_morphTarget + 9 ] = v4.x;
  12627. vka[ offset_morphTarget + 10 ] = v4.y;
  12628. vka[ offset_morphTarget + 11 ] = v4.z;
  12629. // morph normals
  12630. if ( material.morphNormals ) {
  12631. if ( needsSmoothNormals ) {
  12632. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  12633. n1 = faceVertexNormals.a;
  12634. n2 = faceVertexNormals.b;
  12635. n3 = faceVertexNormals.c;
  12636. n4 = faceVertexNormals.d;
  12637. } else {
  12638. n1 = morphNormals[ vk ].faceNormals[ chf ];
  12639. n2 = n1;
  12640. n3 = n1;
  12641. n4 = n1;
  12642. }
  12643. nka = morphNormalsArrays[ vk ];
  12644. nka[ offset_morphTarget ] = n1.x;
  12645. nka[ offset_morphTarget + 1 ] = n1.y;
  12646. nka[ offset_morphTarget + 2 ] = n1.z;
  12647. nka[ offset_morphTarget + 3 ] = n2.x;
  12648. nka[ offset_morphTarget + 4 ] = n2.y;
  12649. nka[ offset_morphTarget + 5 ] = n2.z;
  12650. nka[ offset_morphTarget + 6 ] = n3.x;
  12651. nka[ offset_morphTarget + 7 ] = n3.y;
  12652. nka[ offset_morphTarget + 8 ] = n3.z;
  12653. nka[ offset_morphTarget + 9 ] = n4.x;
  12654. nka[ offset_morphTarget + 10 ] = n4.y;
  12655. nka[ offset_morphTarget + 11 ] = n4.z;
  12656. }
  12657. //
  12658. offset_morphTarget += 12;
  12659. }
  12660. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  12661. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  12662. if ( material.morphNormals ) {
  12663. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  12664. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  12665. }
  12666. }
  12667. }
  12668. if ( obj_skinWeights.length ) {
  12669. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12670. face = obj_faces[ chunk_faces3[ f ] ];
  12671. // weights
  12672. sw1 = obj_skinWeights[ face.a ];
  12673. sw2 = obj_skinWeights[ face.b ];
  12674. sw3 = obj_skinWeights[ face.c ];
  12675. skinWeightArray[ offset_skin ] = sw1.x;
  12676. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  12677. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  12678. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  12679. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  12680. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  12681. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  12682. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  12683. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  12684. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  12685. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  12686. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  12687. // indices
  12688. si1 = obj_skinIndices[ face.a ];
  12689. si2 = obj_skinIndices[ face.b ];
  12690. si3 = obj_skinIndices[ face.c ];
  12691. skinIndexArray[ offset_skin ] = si1.x;
  12692. skinIndexArray[ offset_skin + 1 ] = si1.y;
  12693. skinIndexArray[ offset_skin + 2 ] = si1.z;
  12694. skinIndexArray[ offset_skin + 3 ] = si1.w;
  12695. skinIndexArray[ offset_skin + 4 ] = si2.x;
  12696. skinIndexArray[ offset_skin + 5 ] = si2.y;
  12697. skinIndexArray[ offset_skin + 6 ] = si2.z;
  12698. skinIndexArray[ offset_skin + 7 ] = si2.w;
  12699. skinIndexArray[ offset_skin + 8 ] = si3.x;
  12700. skinIndexArray[ offset_skin + 9 ] = si3.y;
  12701. skinIndexArray[ offset_skin + 10 ] = si3.z;
  12702. skinIndexArray[ offset_skin + 11 ] = si3.w;
  12703. offset_skin += 12;
  12704. }
  12705. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12706. face = obj_faces[ chunk_faces4[ f ] ];
  12707. // weights
  12708. sw1 = obj_skinWeights[ face.a ];
  12709. sw2 = obj_skinWeights[ face.b ];
  12710. sw3 = obj_skinWeights[ face.c ];
  12711. sw4 = obj_skinWeights[ face.d ];
  12712. skinWeightArray[ offset_skin ] = sw1.x;
  12713. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  12714. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  12715. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  12716. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  12717. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  12718. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  12719. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  12720. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  12721. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  12722. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  12723. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  12724. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  12725. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  12726. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  12727. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  12728. // indices
  12729. si1 = obj_skinIndices[ face.a ];
  12730. si2 = obj_skinIndices[ face.b ];
  12731. si3 = obj_skinIndices[ face.c ];
  12732. si4 = obj_skinIndices[ face.d ];
  12733. skinIndexArray[ offset_skin ] = si1.x;
  12734. skinIndexArray[ offset_skin + 1 ] = si1.y;
  12735. skinIndexArray[ offset_skin + 2 ] = si1.z;
  12736. skinIndexArray[ offset_skin + 3 ] = si1.w;
  12737. skinIndexArray[ offset_skin + 4 ] = si2.x;
  12738. skinIndexArray[ offset_skin + 5 ] = si2.y;
  12739. skinIndexArray[ offset_skin + 6 ] = si2.z;
  12740. skinIndexArray[ offset_skin + 7 ] = si2.w;
  12741. skinIndexArray[ offset_skin + 8 ] = si3.x;
  12742. skinIndexArray[ offset_skin + 9 ] = si3.y;
  12743. skinIndexArray[ offset_skin + 10 ] = si3.z;
  12744. skinIndexArray[ offset_skin + 11 ] = si3.w;
  12745. skinIndexArray[ offset_skin + 12 ] = si4.x;
  12746. skinIndexArray[ offset_skin + 13 ] = si4.y;
  12747. skinIndexArray[ offset_skin + 14 ] = si4.z;
  12748. skinIndexArray[ offset_skin + 15 ] = si4.w;
  12749. offset_skin += 16;
  12750. }
  12751. if ( offset_skin > 0 ) {
  12752. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  12753. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  12754. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  12755. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  12756. }
  12757. }
  12758. if ( dirtyColors && vertexColorType ) {
  12759. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12760. face = obj_faces[ chunk_faces3[ f ] ];
  12761. vertexColors = face.vertexColors;
  12762. faceColor = face.color;
  12763. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  12764. c1 = vertexColors[ 0 ];
  12765. c2 = vertexColors[ 1 ];
  12766. c3 = vertexColors[ 2 ];
  12767. } else {
  12768. c1 = faceColor;
  12769. c2 = faceColor;
  12770. c3 = faceColor;
  12771. }
  12772. colorArray[ offset_color ] = c1.r;
  12773. colorArray[ offset_color + 1 ] = c1.g;
  12774. colorArray[ offset_color + 2 ] = c1.b;
  12775. colorArray[ offset_color + 3 ] = c2.r;
  12776. colorArray[ offset_color + 4 ] = c2.g;
  12777. colorArray[ offset_color + 5 ] = c2.b;
  12778. colorArray[ offset_color + 6 ] = c3.r;
  12779. colorArray[ offset_color + 7 ] = c3.g;
  12780. colorArray[ offset_color + 8 ] = c3.b;
  12781. offset_color += 9;
  12782. }
  12783. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12784. face = obj_faces[ chunk_faces4[ f ] ];
  12785. vertexColors = face.vertexColors;
  12786. faceColor = face.color;
  12787. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  12788. c1 = vertexColors[ 0 ];
  12789. c2 = vertexColors[ 1 ];
  12790. c3 = vertexColors[ 2 ];
  12791. c4 = vertexColors[ 3 ];
  12792. } else {
  12793. c1 = faceColor;
  12794. c2 = faceColor;
  12795. c3 = faceColor;
  12796. c4 = faceColor;
  12797. }
  12798. colorArray[ offset_color ] = c1.r;
  12799. colorArray[ offset_color + 1 ] = c1.g;
  12800. colorArray[ offset_color + 2 ] = c1.b;
  12801. colorArray[ offset_color + 3 ] = c2.r;
  12802. colorArray[ offset_color + 4 ] = c2.g;
  12803. colorArray[ offset_color + 5 ] = c2.b;
  12804. colorArray[ offset_color + 6 ] = c3.r;
  12805. colorArray[ offset_color + 7 ] = c3.g;
  12806. colorArray[ offset_color + 8 ] = c3.b;
  12807. colorArray[ offset_color + 9 ] = c4.r;
  12808. colorArray[ offset_color + 10 ] = c4.g;
  12809. colorArray[ offset_color + 11 ] = c4.b;
  12810. offset_color += 12;
  12811. }
  12812. if ( offset_color > 0 ) {
  12813. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12814. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12815. }
  12816. }
  12817. if ( dirtyTangents && geometry.hasTangents ) {
  12818. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12819. face = obj_faces[ chunk_faces3[ f ] ];
  12820. vertexTangents = face.vertexTangents;
  12821. t1 = vertexTangents[ 0 ];
  12822. t2 = vertexTangents[ 1 ];
  12823. t3 = vertexTangents[ 2 ];
  12824. tangentArray[ offset_tangent ] = t1.x;
  12825. tangentArray[ offset_tangent + 1 ] = t1.y;
  12826. tangentArray[ offset_tangent + 2 ] = t1.z;
  12827. tangentArray[ offset_tangent + 3 ] = t1.w;
  12828. tangentArray[ offset_tangent + 4 ] = t2.x;
  12829. tangentArray[ offset_tangent + 5 ] = t2.y;
  12830. tangentArray[ offset_tangent + 6 ] = t2.z;
  12831. tangentArray[ offset_tangent + 7 ] = t2.w;
  12832. tangentArray[ offset_tangent + 8 ] = t3.x;
  12833. tangentArray[ offset_tangent + 9 ] = t3.y;
  12834. tangentArray[ offset_tangent + 10 ] = t3.z;
  12835. tangentArray[ offset_tangent + 11 ] = t3.w;
  12836. offset_tangent += 12;
  12837. }
  12838. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12839. face = obj_faces[ chunk_faces4[ f ] ];
  12840. vertexTangents = face.vertexTangents;
  12841. t1 = vertexTangents[ 0 ];
  12842. t2 = vertexTangents[ 1 ];
  12843. t3 = vertexTangents[ 2 ];
  12844. t4 = vertexTangents[ 3 ];
  12845. tangentArray[ offset_tangent ] = t1.x;
  12846. tangentArray[ offset_tangent + 1 ] = t1.y;
  12847. tangentArray[ offset_tangent + 2 ] = t1.z;
  12848. tangentArray[ offset_tangent + 3 ] = t1.w;
  12849. tangentArray[ offset_tangent + 4 ] = t2.x;
  12850. tangentArray[ offset_tangent + 5 ] = t2.y;
  12851. tangentArray[ offset_tangent + 6 ] = t2.z;
  12852. tangentArray[ offset_tangent + 7 ] = t2.w;
  12853. tangentArray[ offset_tangent + 8 ] = t3.x;
  12854. tangentArray[ offset_tangent + 9 ] = t3.y;
  12855. tangentArray[ offset_tangent + 10 ] = t3.z;
  12856. tangentArray[ offset_tangent + 11 ] = t3.w;
  12857. tangentArray[ offset_tangent + 12 ] = t4.x;
  12858. tangentArray[ offset_tangent + 13 ] = t4.y;
  12859. tangentArray[ offset_tangent + 14 ] = t4.z;
  12860. tangentArray[ offset_tangent + 15 ] = t4.w;
  12861. offset_tangent += 16;
  12862. }
  12863. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12864. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  12865. }
  12866. if ( dirtyNormals && normalType ) {
  12867. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12868. face = obj_faces[ chunk_faces3[ f ] ];
  12869. vertexNormals = face.vertexNormals;
  12870. faceNormal = face.normal;
  12871. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  12872. for ( i = 0; i < 3; i ++ ) {
  12873. vn = vertexNormals[ i ];
  12874. normalArray[ offset_normal ] = vn.x;
  12875. normalArray[ offset_normal + 1 ] = vn.y;
  12876. normalArray[ offset_normal + 2 ] = vn.z;
  12877. offset_normal += 3;
  12878. }
  12879. } else {
  12880. for ( i = 0; i < 3; i ++ ) {
  12881. normalArray[ offset_normal ] = faceNormal.x;
  12882. normalArray[ offset_normal + 1 ] = faceNormal.y;
  12883. normalArray[ offset_normal + 2 ] = faceNormal.z;
  12884. offset_normal += 3;
  12885. }
  12886. }
  12887. }
  12888. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12889. face = obj_faces[ chunk_faces4[ f ] ];
  12890. vertexNormals = face.vertexNormals;
  12891. faceNormal = face.normal;
  12892. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  12893. for ( i = 0; i < 4; i ++ ) {
  12894. vn = vertexNormals[ i ];
  12895. normalArray[ offset_normal ] = vn.x;
  12896. normalArray[ offset_normal + 1 ] = vn.y;
  12897. normalArray[ offset_normal + 2 ] = vn.z;
  12898. offset_normal += 3;
  12899. }
  12900. } else {
  12901. for ( i = 0; i < 4; i ++ ) {
  12902. normalArray[ offset_normal ] = faceNormal.x;
  12903. normalArray[ offset_normal + 1 ] = faceNormal.y;
  12904. normalArray[ offset_normal + 2 ] = faceNormal.z;
  12905. offset_normal += 3;
  12906. }
  12907. }
  12908. }
  12909. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12910. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  12911. }
  12912. if ( dirtyUvs && obj_uvs && uvType ) {
  12913. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12914. fi = chunk_faces3[ f ];
  12915. uv = obj_uvs[ fi ];
  12916. if ( uv === undefined ) continue;
  12917. for ( i = 0; i < 3; i ++ ) {
  12918. uvi = uv[ i ];
  12919. uvArray[ offset_uv ] = uvi.x;
  12920. uvArray[ offset_uv + 1 ] = uvi.y;
  12921. offset_uv += 2;
  12922. }
  12923. }
  12924. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12925. fi = chunk_faces4[ f ];
  12926. uv = obj_uvs[ fi ];
  12927. if ( uv === undefined ) continue;
  12928. for ( i = 0; i < 4; i ++ ) {
  12929. uvi = uv[ i ];
  12930. uvArray[ offset_uv ] = uvi.x;
  12931. uvArray[ offset_uv + 1 ] = uvi.y;
  12932. offset_uv += 2;
  12933. }
  12934. }
  12935. if ( offset_uv > 0 ) {
  12936. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12937. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  12938. }
  12939. }
  12940. if ( dirtyUvs && obj_uvs2 && uvType ) {
  12941. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12942. fi = chunk_faces3[ f ];
  12943. uv2 = obj_uvs2[ fi ];
  12944. if ( uv2 === undefined ) continue;
  12945. for ( i = 0; i < 3; i ++ ) {
  12946. uv2i = uv2[ i ];
  12947. uv2Array[ offset_uv2 ] = uv2i.x;
  12948. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  12949. offset_uv2 += 2;
  12950. }
  12951. }
  12952. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12953. fi = chunk_faces4[ f ];
  12954. uv2 = obj_uvs2[ fi ];
  12955. if ( uv2 === undefined ) continue;
  12956. for ( i = 0; i < 4; i ++ ) {
  12957. uv2i = uv2[ i ];
  12958. uv2Array[ offset_uv2 ] = uv2i.x;
  12959. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  12960. offset_uv2 += 2;
  12961. }
  12962. }
  12963. if ( offset_uv2 > 0 ) {
  12964. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12965. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  12966. }
  12967. }
  12968. if ( dirtyElements ) {
  12969. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12970. faceArray[ offset_face ] = vertexIndex;
  12971. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12972. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  12973. offset_face += 3;
  12974. lineArray[ offset_line ] = vertexIndex;
  12975. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  12976. lineArray[ offset_line + 2 ] = vertexIndex;
  12977. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  12978. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  12979. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  12980. offset_line += 6;
  12981. vertexIndex += 3;
  12982. }
  12983. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12984. faceArray[ offset_face ] = vertexIndex;
  12985. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12986. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  12987. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  12988. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  12989. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  12990. offset_face += 6;
  12991. lineArray[ offset_line ] = vertexIndex;
  12992. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  12993. lineArray[ offset_line + 2 ] = vertexIndex;
  12994. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  12995. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  12996. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  12997. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  12998. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  12999. offset_line += 8;
  13000. vertexIndex += 4;
  13001. }
  13002. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13003. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  13004. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13005. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  13006. }
  13007. if ( customAttributes ) {
  13008. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  13009. customAttribute = customAttributes[ i ];
  13010. if ( ! customAttribute.__original.needsUpdate ) continue;
  13011. offset_custom = 0;
  13012. offset_customSrc = 0;
  13013. if ( customAttribute.size === 1 ) {
  13014. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13015. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13016. face = obj_faces[ chunk_faces3[ f ] ];
  13017. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  13018. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  13019. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  13020. offset_custom += 3;
  13021. }
  13022. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13023. face = obj_faces[ chunk_faces4[ f ] ];
  13024. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  13025. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  13026. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  13027. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  13028. offset_custom += 4;
  13029. }
  13030. } else if ( customAttribute.boundTo === "faces" ) {
  13031. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13032. value = customAttribute.value[ chunk_faces3[ f ] ];
  13033. customAttribute.array[ offset_custom ] = value;
  13034. customAttribute.array[ offset_custom + 1 ] = value;
  13035. customAttribute.array[ offset_custom + 2 ] = value;
  13036. offset_custom += 3;
  13037. }
  13038. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13039. value = customAttribute.value[ chunk_faces4[ f ] ];
  13040. customAttribute.array[ offset_custom ] = value;
  13041. customAttribute.array[ offset_custom + 1 ] = value;
  13042. customAttribute.array[ offset_custom + 2 ] = value;
  13043. customAttribute.array[ offset_custom + 3 ] = value;
  13044. offset_custom += 4;
  13045. }
  13046. }
  13047. } else if ( customAttribute.size === 2 ) {
  13048. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13049. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13050. face = obj_faces[ chunk_faces3[ f ] ];
  13051. v1 = customAttribute.value[ face.a ];
  13052. v2 = customAttribute.value[ face.b ];
  13053. v3 = customAttribute.value[ face.c ];
  13054. customAttribute.array[ offset_custom ] = v1.x;
  13055. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13056. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13057. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13058. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13059. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13060. offset_custom += 6;
  13061. }
  13062. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13063. face = obj_faces[ chunk_faces4[ f ] ];
  13064. v1 = customAttribute.value[ face.a ];
  13065. v2 = customAttribute.value[ face.b ];
  13066. v3 = customAttribute.value[ face.c ];
  13067. v4 = customAttribute.value[ face.d ];
  13068. customAttribute.array[ offset_custom ] = v1.x;
  13069. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13070. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13071. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13072. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13073. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13074. customAttribute.array[ offset_custom + 6 ] = v4.x;
  13075. customAttribute.array[ offset_custom + 7 ] = v4.y;
  13076. offset_custom += 8;
  13077. }
  13078. } else if ( customAttribute.boundTo === "faces" ) {
  13079. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13080. value = customAttribute.value[ chunk_faces3[ f ] ];
  13081. v1 = value;
  13082. v2 = value;
  13083. v3 = value;
  13084. customAttribute.array[ offset_custom ] = v1.x;
  13085. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13086. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13087. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13088. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13089. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13090. offset_custom += 6;
  13091. }
  13092. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13093. value = customAttribute.value[ chunk_faces4[ f ] ];
  13094. v1 = value;
  13095. v2 = value;
  13096. v3 = value;
  13097. v4 = value;
  13098. customAttribute.array[ offset_custom ] = v1.x;
  13099. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13100. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13101. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13102. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13103. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13104. customAttribute.array[ offset_custom + 6 ] = v4.x;
  13105. customAttribute.array[ offset_custom + 7 ] = v4.y;
  13106. offset_custom += 8;
  13107. }
  13108. }
  13109. } else if ( customAttribute.size === 3 ) {
  13110. var pp;
  13111. if ( customAttribute.type === "c" ) {
  13112. pp = [ "r", "g", "b" ];
  13113. } else {
  13114. pp = [ "x", "y", "z" ];
  13115. }
  13116. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13117. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13118. face = obj_faces[ chunk_faces3[ f ] ];
  13119. v1 = customAttribute.value[ face.a ];
  13120. v2 = customAttribute.value[ face.b ];
  13121. v3 = customAttribute.value[ face.c ];
  13122. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13123. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13124. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13125. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13126. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13127. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13128. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13129. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13130. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13131. offset_custom += 9;
  13132. }
  13133. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13134. face = obj_faces[ chunk_faces4[ f ] ];
  13135. v1 = customAttribute.value[ face.a ];
  13136. v2 = customAttribute.value[ face.b ];
  13137. v3 = customAttribute.value[ face.c ];
  13138. v4 = customAttribute.value[ face.d ];
  13139. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13140. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13141. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13142. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13143. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13144. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13145. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13146. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13147. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13148. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  13149. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  13150. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  13151. offset_custom += 12;
  13152. }
  13153. } else if ( customAttribute.boundTo === "faces" ) {
  13154. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13155. value = customAttribute.value[ chunk_faces3[ f ] ];
  13156. v1 = value;
  13157. v2 = value;
  13158. v3 = value;
  13159. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13160. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13161. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13162. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13163. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13164. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13165. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13166. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13167. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13168. offset_custom += 9;
  13169. }
  13170. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13171. value = customAttribute.value[ chunk_faces4[ f ] ];
  13172. v1 = value;
  13173. v2 = value;
  13174. v3 = value;
  13175. v4 = value;
  13176. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13177. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13178. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13179. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13180. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13181. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13182. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13183. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13184. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13185. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  13186. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  13187. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  13188. offset_custom += 12;
  13189. }
  13190. } else if ( customAttribute.boundTo === "faceVertices" ) {
  13191. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13192. value = customAttribute.value[ chunk_faces3[ f ] ];
  13193. v1 = value[ 0 ];
  13194. v2 = value[ 1 ];
  13195. v3 = value[ 2 ];
  13196. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13197. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13198. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13199. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13200. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13201. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13202. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13203. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13204. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13205. offset_custom += 9;
  13206. }
  13207. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13208. value = customAttribute.value[ chunk_faces4[ f ] ];
  13209. v1 = value[ 0 ];
  13210. v2 = value[ 1 ];
  13211. v3 = value[ 2 ];
  13212. v4 = value[ 3 ];
  13213. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13214. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13215. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13216. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13217. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13218. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13219. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13220. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13221. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13222. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  13223. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  13224. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  13225. offset_custom += 12;
  13226. }
  13227. }
  13228. } else if ( customAttribute.size === 4 ) {
  13229. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13230. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13231. face = obj_faces[ chunk_faces3[ f ] ];
  13232. v1 = customAttribute.value[ face.a ];
  13233. v2 = customAttribute.value[ face.b ];
  13234. v3 = customAttribute.value[ face.c ];
  13235. customAttribute.array[ offset_custom ] = v1.x;
  13236. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13237. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13238. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13239. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13240. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13241. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13242. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13243. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13244. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13245. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13246. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13247. offset_custom += 12;
  13248. }
  13249. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13250. face = obj_faces[ chunk_faces4[ f ] ];
  13251. v1 = customAttribute.value[ face.a ];
  13252. v2 = customAttribute.value[ face.b ];
  13253. v3 = customAttribute.value[ face.c ];
  13254. v4 = customAttribute.value[ face.d ];
  13255. customAttribute.array[ offset_custom ] = v1.x;
  13256. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13257. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13258. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13259. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13260. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13261. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13262. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13263. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13264. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13265. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13266. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13267. customAttribute.array[ offset_custom + 12 ] = v4.x;
  13268. customAttribute.array[ offset_custom + 13 ] = v4.y;
  13269. customAttribute.array[ offset_custom + 14 ] = v4.z;
  13270. customAttribute.array[ offset_custom + 15 ] = v4.w;
  13271. offset_custom += 16;
  13272. }
  13273. } else if ( customAttribute.boundTo === "faces" ) {
  13274. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13275. value = customAttribute.value[ chunk_faces3[ f ] ];
  13276. v1 = value;
  13277. v2 = value;
  13278. v3 = value;
  13279. customAttribute.array[ offset_custom ] = v1.x;
  13280. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13281. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13282. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13283. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13284. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13285. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13286. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13287. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13288. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13289. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13290. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13291. offset_custom += 12;
  13292. }
  13293. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13294. value = customAttribute.value[ chunk_faces4[ f ] ];
  13295. v1 = value;
  13296. v2 = value;
  13297. v3 = value;
  13298. v4 = value;
  13299. customAttribute.array[ offset_custom ] = v1.x;
  13300. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13301. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13302. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13303. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13304. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13305. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13306. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13307. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13308. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13309. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13310. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13311. customAttribute.array[ offset_custom + 12 ] = v4.x;
  13312. customAttribute.array[ offset_custom + 13 ] = v4.y;
  13313. customAttribute.array[ offset_custom + 14 ] = v4.z;
  13314. customAttribute.array[ offset_custom + 15 ] = v4.w;
  13315. offset_custom += 16;
  13316. }
  13317. } else if ( customAttribute.boundTo === "faceVertices" ) {
  13318. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13319. value = customAttribute.value[ chunk_faces3[ f ] ];
  13320. v1 = value[ 0 ];
  13321. v2 = value[ 1 ];
  13322. v3 = value[ 2 ];
  13323. customAttribute.array[ offset_custom ] = v1.x;
  13324. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13325. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13326. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13327. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13328. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13329. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13330. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13331. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13332. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13333. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13334. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13335. offset_custom += 12;
  13336. }
  13337. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13338. value = customAttribute.value[ chunk_faces4[ f ] ];
  13339. v1 = value[ 0 ];
  13340. v2 = value[ 1 ];
  13341. v3 = value[ 2 ];
  13342. v4 = value[ 3 ];
  13343. customAttribute.array[ offset_custom ] = v1.x;
  13344. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13345. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13346. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13347. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13348. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13349. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13350. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13351. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13352. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13353. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13354. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13355. customAttribute.array[ offset_custom + 12 ] = v4.x;
  13356. customAttribute.array[ offset_custom + 13 ] = v4.y;
  13357. customAttribute.array[ offset_custom + 14 ] = v4.z;
  13358. customAttribute.array[ offset_custom + 15 ] = v4.w;
  13359. offset_custom += 16;
  13360. }
  13361. }
  13362. }
  13363. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  13364. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  13365. }
  13366. }
  13367. if ( dispose ) {
  13368. delete geometryGroup.__inittedArrays;
  13369. delete geometryGroup.__colorArray;
  13370. delete geometryGroup.__normalArray;
  13371. delete geometryGroup.__tangentArray;
  13372. delete geometryGroup.__uvArray;
  13373. delete geometryGroup.__uv2Array;
  13374. delete geometryGroup.__faceArray;
  13375. delete geometryGroup.__vertexArray;
  13376. delete geometryGroup.__lineArray;
  13377. delete geometryGroup.__skinIndexArray;
  13378. delete geometryGroup.__skinWeightArray;
  13379. }
  13380. };
  13381. function setDirectBuffers ( geometry, hint, dispose ) {
  13382. var attributes = geometry.attributes;
  13383. var attributeName, attributeItem;
  13384. for ( attributeName in attributes ) {
  13385. attributeItem = attributes[ attributeName ];
  13386. if ( attributeItem.needsUpdate ) {
  13387. if ( attributeName === 'index' ) {
  13388. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer );
  13389. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint );
  13390. } else {
  13391. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13392. _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint );
  13393. }
  13394. attributeItem.needsUpdate = false;
  13395. }
  13396. if ( dispose && ! attributeItem.dynamic ) {
  13397. attributeItem.array = null;
  13398. }
  13399. }
  13400. };
  13401. // Buffer rendering
  13402. this.renderBufferImmediate = function ( object, program, material ) {
  13403. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  13404. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  13405. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  13406. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  13407. if ( object.hasPositions ) {
  13408. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  13409. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  13410. _gl.enableVertexAttribArray( program.attributes.position );
  13411. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13412. }
  13413. if ( object.hasNormals ) {
  13414. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  13415. if ( material.shading === THREE.FlatShading ) {
  13416. var nx, ny, nz,
  13417. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  13418. normalArray,
  13419. i, il = object.count * 3;
  13420. for( i = 0; i < il; i += 9 ) {
  13421. normalArray = object.normalArray;
  13422. nax = normalArray[ i ];
  13423. nay = normalArray[ i + 1 ];
  13424. naz = normalArray[ i + 2 ];
  13425. nbx = normalArray[ i + 3 ];
  13426. nby = normalArray[ i + 4 ];
  13427. nbz = normalArray[ i + 5 ];
  13428. ncx = normalArray[ i + 6 ];
  13429. ncy = normalArray[ i + 7 ];
  13430. ncz = normalArray[ i + 8 ];
  13431. nx = ( nax + nbx + ncx ) / 3;
  13432. ny = ( nay + nby + ncy ) / 3;
  13433. nz = ( naz + nbz + ncz ) / 3;
  13434. normalArray[ i ] = nx;
  13435. normalArray[ i + 1 ] = ny;
  13436. normalArray[ i + 2 ] = nz;
  13437. normalArray[ i + 3 ] = nx;
  13438. normalArray[ i + 4 ] = ny;
  13439. normalArray[ i + 5 ] = nz;
  13440. normalArray[ i + 6 ] = nx;
  13441. normalArray[ i + 7 ] = ny;
  13442. normalArray[ i + 8 ] = nz;
  13443. }
  13444. }
  13445. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  13446. _gl.enableVertexAttribArray( program.attributes.normal );
  13447. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13448. }
  13449. if ( object.hasUvs && material.map ) {
  13450. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  13451. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  13452. _gl.enableVertexAttribArray( program.attributes.uv );
  13453. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13454. }
  13455. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  13456. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  13457. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  13458. _gl.enableVertexAttribArray( program.attributes.color );
  13459. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13460. }
  13461. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  13462. object.count = 0;
  13463. };
  13464. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  13465. if ( material.visible === false ) return;
  13466. var linewidth, a, attribute;
  13467. var attributeItem, attributeName, attributePointer, attributeSize;
  13468. var program = setProgram( camera, lights, fog, material, object );
  13469. var programAttributes = program.attributes;
  13470. var geometryAttributes = geometry.attributes;
  13471. var updateBuffers = false,
  13472. wireframeBit = material.wireframe ? 1 : 0,
  13473. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13474. if ( geometryHash !== _currentGeometryGroupHash ) {
  13475. _currentGeometryGroupHash = geometryHash;
  13476. updateBuffers = true;
  13477. }
  13478. if ( updateBuffers ) {
  13479. disableAttributes();
  13480. }
  13481. // render mesh
  13482. if ( object instanceof THREE.Mesh ) {
  13483. var index = geometryAttributes[ "index" ];
  13484. // indexed triangles
  13485. if ( index ) {
  13486. var offsets = geometry.offsets;
  13487. // if there is more than 1 chunk
  13488. // must set attribute pointers to use new offsets for each chunk
  13489. // even if geometry and materials didn't change
  13490. if ( offsets.length > 1 ) updateBuffers = true;
  13491. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13492. var startIndex = offsets[ i ].index;
  13493. if ( updateBuffers ) {
  13494. for ( attributeName in geometryAttributes ) {
  13495. if ( attributeName === 'index' ) continue;
  13496. attributePointer = programAttributes[ attributeName ];
  13497. attributeItem = geometryAttributes[ attributeName ];
  13498. attributeSize = attributeItem.itemSize;
  13499. if ( attributePointer >= 0 ) {
  13500. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13501. enableAttribute( attributePointer );
  13502. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  13503. }
  13504. }
  13505. // indices
  13506. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13507. }
  13508. // render indexed triangles
  13509. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  13510. _this.info.render.calls ++;
  13511. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13512. _this.info.render.faces += offsets[ i ].count / 3;
  13513. }
  13514. // non-indexed triangles
  13515. } else {
  13516. if ( updateBuffers ) {
  13517. for ( attributeName in geometryAttributes ) {
  13518. if ( attributeName === 'index') continue;
  13519. attributePointer = programAttributes[ attributeName ];
  13520. attributeItem = geometryAttributes[ attributeName ];
  13521. attributeSize = attributeItem.itemSize;
  13522. if ( attributePointer >= 0 ) {
  13523. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13524. enableAttribute( attributePointer );
  13525. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13526. }
  13527. }
  13528. }
  13529. var position = geometry.attributes[ "position" ];
  13530. // render non-indexed triangles
  13531. _gl.drawArrays( _gl.TRIANGLES, 0, position.numItems / 3 );
  13532. _this.info.render.calls ++;
  13533. _this.info.render.vertices += position.numItems / 3;
  13534. _this.info.render.faces += position.numItems / 3 / 3;
  13535. }
  13536. // render particles
  13537. } else if ( object instanceof THREE.ParticleSystem ) {
  13538. if ( updateBuffers ) {
  13539. for ( attributeName in geometryAttributes ) {
  13540. attributePointer = programAttributes[ attributeName ];
  13541. attributeItem = geometryAttributes[ attributeName ];
  13542. attributeSize = attributeItem.itemSize;
  13543. if ( attributePointer >= 0 ) {
  13544. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13545. enableAttribute( attributePointer );
  13546. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13547. }
  13548. }
  13549. var position = geometryAttributes[ "position" ];
  13550. // render particles
  13551. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  13552. _this.info.render.calls ++;
  13553. _this.info.render.points += position.numItems / 3;
  13554. }
  13555. } else if ( object instanceof THREE.Line ) {
  13556. if ( updateBuffers ) {
  13557. for ( attributeName in geometryAttributes ) {
  13558. attributePointer = programAttributes[ attributeName ];
  13559. attributeItem = geometryAttributes[ attributeName ];
  13560. attributeSize = attributeItem.itemSize;
  13561. if ( attributePointer >= 0 ) {
  13562. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13563. enableAttribute( attributePointer );
  13564. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13565. }
  13566. }
  13567. // render lines
  13568. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13569. setLineWidth( material.linewidth );
  13570. var position = geometryAttributes[ "position" ];
  13571. _gl.drawArrays( primitives, 0, position.numItems / 3 );
  13572. _this.info.render.calls ++;
  13573. _this.info.render.points += position.numItems;
  13574. }
  13575. }
  13576. };
  13577. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  13578. if ( material.visible === false ) return;
  13579. var linewidth, a, attribute, i, il;
  13580. var program = setProgram( camera, lights, fog, material, object );
  13581. var attributes = program.attributes;
  13582. var updateBuffers = false,
  13583. wireframeBit = material.wireframe ? 1 : 0,
  13584. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13585. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  13586. _currentGeometryGroupHash = geometryGroupHash;
  13587. updateBuffers = true;
  13588. }
  13589. if ( updateBuffers ) {
  13590. disableAttributes();
  13591. }
  13592. // vertices
  13593. if ( !material.morphTargets && attributes.position >= 0 ) {
  13594. if ( updateBuffers ) {
  13595. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13596. enableAttribute( attributes.position );
  13597. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13598. }
  13599. } else {
  13600. if ( object.morphTargetBase ) {
  13601. setupMorphTargets( material, geometryGroup, object );
  13602. }
  13603. }
  13604. if ( updateBuffers ) {
  13605. // custom attributes
  13606. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  13607. if ( geometryGroup.__webglCustomAttributesList ) {
  13608. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  13609. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  13610. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  13611. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  13612. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  13613. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  13614. }
  13615. }
  13616. }
  13617. // colors
  13618. if ( attributes.color >= 0 ) {
  13619. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13620. enableAttribute( attributes.color );
  13621. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13622. }
  13623. // normals
  13624. if ( attributes.normal >= 0 ) {
  13625. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13626. enableAttribute( attributes.normal );
  13627. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13628. }
  13629. // tangents
  13630. if ( attributes.tangent >= 0 ) {
  13631. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13632. enableAttribute( attributes.tangent );
  13633. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  13634. }
  13635. // uvs
  13636. if ( attributes.uv >= 0 ) {
  13637. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13638. enableAttribute( attributes.uv );
  13639. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13640. }
  13641. if ( attributes.uv2 >= 0 ) {
  13642. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13643. enableAttribute( attributes.uv2 );
  13644. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  13645. }
  13646. if ( material.skinning &&
  13647. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  13648. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13649. enableAttribute( attributes.skinIndex );
  13650. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  13651. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13652. enableAttribute( attributes.skinWeight );
  13653. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  13654. }
  13655. // line distances
  13656. if ( attributes.lineDistance >= 0 ) {
  13657. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  13658. enableAttribute( attributes.lineDistance );
  13659. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  13660. }
  13661. }
  13662. // render mesh
  13663. if ( object instanceof THREE.Mesh ) {
  13664. // wireframe
  13665. if ( material.wireframe ) {
  13666. setLineWidth( material.wireframeLinewidth );
  13667. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13668. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  13669. // triangles
  13670. } else {
  13671. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13672. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  13673. }
  13674. _this.info.render.calls ++;
  13675. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  13676. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  13677. // render lines
  13678. } else if ( object instanceof THREE.Line ) {
  13679. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13680. setLineWidth( material.linewidth );
  13681. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  13682. _this.info.render.calls ++;
  13683. // render particles
  13684. } else if ( object instanceof THREE.ParticleSystem ) {
  13685. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  13686. _this.info.render.calls ++;
  13687. _this.info.render.points += geometryGroup.__webglParticleCount;
  13688. // render ribbon
  13689. } else if ( object instanceof THREE.Ribbon ) {
  13690. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  13691. _this.info.render.calls ++;
  13692. }
  13693. };
  13694. function enableAttribute( attribute ) {
  13695. if ( ! _enabledAttributes[ attribute ] ) {
  13696. _gl.enableVertexAttribArray( attribute );
  13697. _enabledAttributes[ attribute ] = true;
  13698. }
  13699. };
  13700. function disableAttributes() {
  13701. for ( var attribute in _enabledAttributes ) {
  13702. if ( _enabledAttributes[ attribute ] ) {
  13703. _gl.disableVertexAttribArray( attribute );
  13704. _enabledAttributes[ attribute ] = false;
  13705. }
  13706. }
  13707. };
  13708. function setupMorphTargets ( material, geometryGroup, object ) {
  13709. // set base
  13710. var attributes = material.program.attributes;
  13711. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  13712. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  13713. enableAttribute( attributes.position );
  13714. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13715. } else if ( attributes.position >= 0 ) {
  13716. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13717. enableAttribute( attributes.position );
  13718. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13719. }
  13720. if ( object.morphTargetForcedOrder.length ) {
  13721. // set forced order
  13722. var m = 0;
  13723. var order = object.morphTargetForcedOrder;
  13724. var influences = object.morphTargetInfluences;
  13725. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  13726. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13727. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  13728. enableAttribute( attributes[ "morphTarget" + m ] );
  13729. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13730. }
  13731. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13732. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  13733. enableAttribute( attributes[ "morphNormal" + m ] );
  13734. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13735. }
  13736. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  13737. m ++;
  13738. }
  13739. } else {
  13740. // find the most influencing
  13741. var influence, activeInfluenceIndices = [];
  13742. var influences = object.morphTargetInfluences;
  13743. var i, il = influences.length;
  13744. for ( i = 0; i < il; i ++ ) {
  13745. influence = influences[ i ];
  13746. if ( influence > 0 ) {
  13747. activeInfluenceIndices.push( [ influence, i ] );
  13748. }
  13749. }
  13750. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  13751. activeInfluenceIndices.sort( numericalSort );
  13752. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  13753. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  13754. activeInfluenceIndices.sort( numericalSort );
  13755. } else if ( activeInfluenceIndices.length === 0 ) {
  13756. activeInfluenceIndices.push( [ 0, 0 ] );
  13757. };
  13758. var influenceIndex, m = 0;
  13759. while ( m < material.numSupportedMorphTargets ) {
  13760. if ( activeInfluenceIndices[ m ] ) {
  13761. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  13762. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13763. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  13764. enableAttribute( attributes[ "morphTarget" + m ] );
  13765. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13766. }
  13767. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13768. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  13769. enableAttribute( attributes[ "morphNormal" + m ] );
  13770. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13771. }
  13772. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  13773. } else {
  13774. /*
  13775. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13776. if ( material.morphNormals ) {
  13777. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13778. }
  13779. */
  13780. object.__webglMorphTargetInfluences[ m ] = 0;
  13781. }
  13782. m ++;
  13783. }
  13784. }
  13785. // load updated influences uniform
  13786. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  13787. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  13788. }
  13789. };
  13790. // Sorting
  13791. function painterSortStable ( a, b ) {
  13792. if ( a.z !== b.z ) {
  13793. return b.z - a.z;
  13794. } else {
  13795. return a.id - b.id;
  13796. }
  13797. };
  13798. function numericalSort ( a, b ) {
  13799. return b[ 0 ] - a[ 0 ];
  13800. };
  13801. // Rendering
  13802. this.render = function ( scene, camera, renderTarget, forceClear ) {
  13803. if ( camera instanceof THREE.Camera === false ) {
  13804. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  13805. return;
  13806. }
  13807. var i, il,
  13808. webglObject, object,
  13809. renderList,
  13810. lights = scene.__lights,
  13811. fog = scene.fog;
  13812. // reset caching for this frame
  13813. _currentMaterialId = -1;
  13814. _lightsNeedUpdate = true;
  13815. // update scene graph
  13816. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  13817. // update camera matrices and frustum
  13818. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  13819. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  13820. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  13821. _frustum.setFromMatrix( _projScreenMatrix );
  13822. // update WebGL objects
  13823. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  13824. // custom render plugins (pre pass)
  13825. renderPlugins( this.renderPluginsPre, scene, camera );
  13826. //
  13827. _this.info.render.calls = 0;
  13828. _this.info.render.vertices = 0;
  13829. _this.info.render.faces = 0;
  13830. _this.info.render.points = 0;
  13831. this.setRenderTarget( renderTarget );
  13832. if ( this.autoClear || forceClear ) {
  13833. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  13834. }
  13835. // set matrices for regular objects (frustum culled)
  13836. renderList = scene.__webglObjects;
  13837. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13838. webglObject = renderList[ i ];
  13839. object = webglObject.object;
  13840. webglObject.id = i;
  13841. webglObject.render = false;
  13842. if ( object.visible ) {
  13843. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  13844. setupMatrices( object, camera );
  13845. unrollBufferMaterial( webglObject );
  13846. webglObject.render = true;
  13847. if ( this.sortObjects === true ) {
  13848. if ( object.renderDepth !== null ) {
  13849. webglObject.z = object.renderDepth;
  13850. } else {
  13851. _vector3.getPositionFromMatrix( object.matrixWorld );
  13852. _vector3.applyProjection( _projScreenMatrix );
  13853. webglObject.z = _vector3.z;
  13854. }
  13855. }
  13856. }
  13857. }
  13858. }
  13859. if ( this.sortObjects ) {
  13860. renderList.sort( painterSortStable );
  13861. }
  13862. // set matrices for immediate objects
  13863. renderList = scene.__webglObjectsImmediate;
  13864. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13865. webglObject = renderList[ i ];
  13866. object = webglObject.object;
  13867. if ( object.visible ) {
  13868. setupMatrices( object, camera );
  13869. unrollImmediateBufferMaterial( webglObject );
  13870. }
  13871. }
  13872. if ( scene.overrideMaterial ) {
  13873. var material = scene.overrideMaterial;
  13874. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13875. this.setDepthTest( material.depthTest );
  13876. this.setDepthWrite( material.depthWrite );
  13877. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13878. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  13879. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  13880. } else {
  13881. var material = null;
  13882. // opaque pass (front-to-back order)
  13883. this.setBlending( THREE.NoBlending );
  13884. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  13885. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  13886. // transparent pass (back-to-front order)
  13887. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  13888. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  13889. }
  13890. // custom render plugins (post pass)
  13891. renderPlugins( this.renderPluginsPost, scene, camera );
  13892. // Generate mipmap if we're using any kind of mipmap filtering
  13893. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  13894. updateRenderTargetMipmap( renderTarget );
  13895. }
  13896. // Ensure depth buffer writing is enabled so it can be cleared on next render
  13897. this.setDepthTest( true );
  13898. this.setDepthWrite( true );
  13899. // _gl.finish();
  13900. };
  13901. function renderPlugins( plugins, scene, camera ) {
  13902. if ( ! plugins.length ) return;
  13903. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  13904. // reset state for plugin (to start from clean slate)
  13905. _currentProgram = null;
  13906. _currentCamera = null;
  13907. _oldBlending = -1;
  13908. _oldDepthTest = -1;
  13909. _oldDepthWrite = -1;
  13910. _oldDoubleSided = -1;
  13911. _oldFlipSided = -1;
  13912. _currentGeometryGroupHash = -1;
  13913. _currentMaterialId = -1;
  13914. _lightsNeedUpdate = true;
  13915. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  13916. // reset state after plugin (anything could have changed)
  13917. _currentProgram = null;
  13918. _currentCamera = null;
  13919. _oldBlending = -1;
  13920. _oldDepthTest = -1;
  13921. _oldDepthWrite = -1;
  13922. _oldDoubleSided = -1;
  13923. _oldFlipSided = -1;
  13924. _currentGeometryGroupHash = -1;
  13925. _currentMaterialId = -1;
  13926. _lightsNeedUpdate = true;
  13927. }
  13928. };
  13929. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13930. var webglObject, object, buffer, material, start, end, delta;
  13931. if ( reverse ) {
  13932. start = renderList.length - 1;
  13933. end = -1;
  13934. delta = -1;
  13935. } else {
  13936. start = 0;
  13937. end = renderList.length;
  13938. delta = 1;
  13939. }
  13940. for ( var i = start; i !== end; i += delta ) {
  13941. webglObject = renderList[ i ];
  13942. if ( webglObject.render ) {
  13943. object = webglObject.object;
  13944. buffer = webglObject.buffer;
  13945. if ( overrideMaterial ) {
  13946. material = overrideMaterial;
  13947. } else {
  13948. material = webglObject[ materialType ];
  13949. if ( ! material ) continue;
  13950. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13951. _this.setDepthTest( material.depthTest );
  13952. _this.setDepthWrite( material.depthWrite );
  13953. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13954. }
  13955. _this.setMaterialFaces( material );
  13956. if ( buffer instanceof THREE.BufferGeometry ) {
  13957. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  13958. } else {
  13959. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  13960. }
  13961. }
  13962. }
  13963. };
  13964. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13965. var webglObject, object, material, program;
  13966. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  13967. webglObject = renderList[ i ];
  13968. object = webglObject.object;
  13969. if ( object.visible ) {
  13970. if ( overrideMaterial ) {
  13971. material = overrideMaterial;
  13972. } else {
  13973. material = webglObject[ materialType ];
  13974. if ( ! material ) continue;
  13975. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13976. _this.setDepthTest( material.depthTest );
  13977. _this.setDepthWrite( material.depthWrite );
  13978. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13979. }
  13980. _this.renderImmediateObject( camera, lights, fog, material, object );
  13981. }
  13982. }
  13983. };
  13984. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  13985. var program = setProgram( camera, lights, fog, material, object );
  13986. _currentGeometryGroupHash = -1;
  13987. _this.setMaterialFaces( material );
  13988. if ( object.immediateRenderCallback ) {
  13989. object.immediateRenderCallback( program, _gl, _frustum );
  13990. } else {
  13991. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  13992. }
  13993. };
  13994. function unrollImmediateBufferMaterial ( globject ) {
  13995. var object = globject.object,
  13996. material = object.material;
  13997. if ( material.transparent ) {
  13998. globject.transparent = material;
  13999. globject.opaque = null;
  14000. } else {
  14001. globject.opaque = material;
  14002. globject.transparent = null;
  14003. }
  14004. };
  14005. function unrollBufferMaterial ( globject ) {
  14006. var object = globject.object,
  14007. buffer = globject.buffer,
  14008. material, materialIndex, meshMaterial;
  14009. meshMaterial = object.material;
  14010. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  14011. materialIndex = buffer.materialIndex;
  14012. material = meshMaterial.materials[ materialIndex ];
  14013. if ( material.transparent ) {
  14014. globject.transparent = material;
  14015. globject.opaque = null;
  14016. } else {
  14017. globject.opaque = material;
  14018. globject.transparent = null;
  14019. }
  14020. } else {
  14021. material = meshMaterial;
  14022. if ( material ) {
  14023. if ( material.transparent ) {
  14024. globject.transparent = material;
  14025. globject.opaque = null;
  14026. } else {
  14027. globject.opaque = material;
  14028. globject.transparent = null;
  14029. }
  14030. }
  14031. }
  14032. };
  14033. // Geometry splitting
  14034. function sortFacesByMaterial ( geometry, material ) {
  14035. var f, fl, face, materialIndex, vertices,
  14036. groupHash, hash_map = {};
  14037. var numMorphTargets = geometry.morphTargets.length;
  14038. var numMorphNormals = geometry.morphNormals.length;
  14039. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  14040. geometry.geometryGroups = {};
  14041. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  14042. face = geometry.faces[ f ];
  14043. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  14044. if ( hash_map[ materialIndex ] === undefined ) {
  14045. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  14046. }
  14047. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  14048. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  14049. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  14050. }
  14051. vertices = face instanceof THREE.Face3 ? 3 : 4;
  14052. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  14053. hash_map[ materialIndex ].counter += 1;
  14054. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  14055. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  14056. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  14057. }
  14058. }
  14059. if ( face instanceof THREE.Face3 ) {
  14060. geometry.geometryGroups[ groupHash ].faces3.push( f );
  14061. } else {
  14062. geometry.geometryGroups[ groupHash ].faces4.push( f );
  14063. }
  14064. geometry.geometryGroups[ groupHash ].vertices += vertices;
  14065. }
  14066. geometry.geometryGroupsList = [];
  14067. for ( var g in geometry.geometryGroups ) {
  14068. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  14069. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  14070. }
  14071. };
  14072. // Objects refresh
  14073. this.initWebGLObjects = function ( scene ) {
  14074. if ( !scene.__webglObjects ) {
  14075. scene.__webglObjects = [];
  14076. scene.__webglObjectsImmediate = [];
  14077. scene.__webglSprites = [];
  14078. scene.__webglFlares = [];
  14079. }
  14080. while ( scene.__objectsAdded.length ) {
  14081. addObject( scene.__objectsAdded[ 0 ], scene );
  14082. scene.__objectsAdded.splice( 0, 1 );
  14083. }
  14084. while ( scene.__objectsRemoved.length ) {
  14085. removeObject( scene.__objectsRemoved[ 0 ], scene );
  14086. scene.__objectsRemoved.splice( 0, 1 );
  14087. }
  14088. // update must be called after objects adding / removal
  14089. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  14090. var object = scene.__webglObjects[ o ].object;
  14091. // TODO: Remove this hack (WebGLRenderer refactoring)
  14092. if ( object.__webglInit === undefined ) {
  14093. if ( object.__webglActive !== undefined ) {
  14094. removeObject( object, scene );
  14095. }
  14096. addObject( object, scene );
  14097. }
  14098. updateObject( object );
  14099. }
  14100. };
  14101. // Objects adding
  14102. function addObject( object, scene ) {
  14103. var g, geometry, material, geometryGroup;
  14104. if ( object.__webglInit === undefined ) {
  14105. object.__webglInit = true;
  14106. object._modelViewMatrix = new THREE.Matrix4();
  14107. object._normalMatrix = new THREE.Matrix3();
  14108. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  14109. object.geometry.__webglInit = true;
  14110. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  14111. }
  14112. geometry = object.geometry;
  14113. if ( geometry === undefined ) {
  14114. // fail silently for now
  14115. } else if ( geometry instanceof THREE.BufferGeometry ) {
  14116. initDirectBuffers( geometry );
  14117. } else if ( object instanceof THREE.Mesh ) {
  14118. material = object.material;
  14119. if ( geometry.geometryGroups === undefined ) {
  14120. sortFacesByMaterial( geometry, material );
  14121. }
  14122. // create separate VBOs per geometry chunk
  14123. for ( g in geometry.geometryGroups ) {
  14124. geometryGroup = geometry.geometryGroups[ g ];
  14125. // initialise VBO on the first access
  14126. if ( ! geometryGroup.__webglVertexBuffer ) {
  14127. createMeshBuffers( geometryGroup );
  14128. initMeshBuffers( geometryGroup, object );
  14129. geometry.verticesNeedUpdate = true;
  14130. geometry.morphTargetsNeedUpdate = true;
  14131. geometry.elementsNeedUpdate = true;
  14132. geometry.uvsNeedUpdate = true;
  14133. geometry.normalsNeedUpdate = true;
  14134. geometry.tangentsNeedUpdate = true;
  14135. geometry.colorsNeedUpdate = true;
  14136. }
  14137. }
  14138. } else if ( object instanceof THREE.Ribbon ) {
  14139. if ( ! geometry.__webglVertexBuffer ) {
  14140. createRibbonBuffers( geometry );
  14141. initRibbonBuffers( geometry, object );
  14142. geometry.verticesNeedUpdate = true;
  14143. geometry.colorsNeedUpdate = true;
  14144. geometry.normalsNeedUpdate = true;
  14145. }
  14146. } else if ( object instanceof THREE.Line ) {
  14147. if ( ! geometry.__webglVertexBuffer ) {
  14148. createLineBuffers( geometry );
  14149. initLineBuffers( geometry, object );
  14150. geometry.verticesNeedUpdate = true;
  14151. geometry.colorsNeedUpdate = true;
  14152. geometry.lineDistancesNeedUpdate = true;
  14153. }
  14154. } else if ( object instanceof THREE.ParticleSystem ) {
  14155. if ( ! geometry.__webglVertexBuffer ) {
  14156. createParticleBuffers( geometry );
  14157. initParticleBuffers( geometry, object );
  14158. geometry.verticesNeedUpdate = true;
  14159. geometry.colorsNeedUpdate = true;
  14160. }
  14161. }
  14162. }
  14163. if ( object.__webglActive === undefined ) {
  14164. if ( object instanceof THREE.Mesh ) {
  14165. geometry = object.geometry;
  14166. if ( geometry instanceof THREE.BufferGeometry ) {
  14167. addBuffer( scene.__webglObjects, geometry, object );
  14168. } else if ( geometry instanceof THREE.Geometry ) {
  14169. for ( g in geometry.geometryGroups ) {
  14170. geometryGroup = geometry.geometryGroups[ g ];
  14171. addBuffer( scene.__webglObjects, geometryGroup, object );
  14172. }
  14173. }
  14174. } else if ( object instanceof THREE.Ribbon ||
  14175. object instanceof THREE.Line ||
  14176. object instanceof THREE.ParticleSystem ) {
  14177. geometry = object.geometry;
  14178. addBuffer( scene.__webglObjects, geometry, object );
  14179. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14180. addBufferImmediate( scene.__webglObjectsImmediate, object );
  14181. } else if ( object instanceof THREE.Sprite ) {
  14182. scene.__webglSprites.push( object );
  14183. } else if ( object instanceof THREE.LensFlare ) {
  14184. scene.__webglFlares.push( object );
  14185. }
  14186. object.__webglActive = true;
  14187. }
  14188. };
  14189. function addBuffer( objlist, buffer, object ) {
  14190. objlist.push(
  14191. {
  14192. id: null,
  14193. buffer: buffer,
  14194. object: object,
  14195. opaque: null,
  14196. transparent: null,
  14197. z: 0
  14198. }
  14199. );
  14200. };
  14201. function addBufferImmediate( objlist, object ) {
  14202. objlist.push(
  14203. {
  14204. id: null,
  14205. object: object,
  14206. opaque: null,
  14207. transparent: null,
  14208. z: 0
  14209. }
  14210. );
  14211. };
  14212. // Objects updates
  14213. function updateObject( object ) {
  14214. var geometry = object.geometry,
  14215. geometryGroup, customAttributesDirty, material;
  14216. if ( geometry instanceof THREE.BufferGeometry ) {
  14217. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  14218. } else if ( object instanceof THREE.Mesh ) {
  14219. // check all geometry groups
  14220. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  14221. geometryGroup = geometry.geometryGroupsList[ i ];
  14222. material = getBufferMaterial( object, geometryGroup );
  14223. if ( geometry.buffersNeedUpdate ) {
  14224. initMeshBuffers( geometryGroup, object );
  14225. }
  14226. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14227. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  14228. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  14229. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  14230. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  14231. }
  14232. }
  14233. geometry.verticesNeedUpdate = false;
  14234. geometry.morphTargetsNeedUpdate = false;
  14235. geometry.elementsNeedUpdate = false;
  14236. geometry.uvsNeedUpdate = false;
  14237. geometry.normalsNeedUpdate = false;
  14238. geometry.colorsNeedUpdate = false;
  14239. geometry.tangentsNeedUpdate = false;
  14240. geometry.buffersNeedUpdate = false;
  14241. material.attributes && clearCustomAttributes( material );
  14242. } else if ( object instanceof THREE.Ribbon ) {
  14243. material = getBufferMaterial( object, geometry );
  14244. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14245. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.normalsNeedUpdate || customAttributesDirty ) {
  14246. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  14247. }
  14248. geometry.verticesNeedUpdate = false;
  14249. geometry.colorsNeedUpdate = false;
  14250. geometry.normalsNeedUpdate = false;
  14251. material.attributes && clearCustomAttributes( material );
  14252. } else if ( object instanceof THREE.Line ) {
  14253. material = getBufferMaterial( object, geometry );
  14254. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14255. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  14256. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  14257. }
  14258. geometry.verticesNeedUpdate = false;
  14259. geometry.colorsNeedUpdate = false;
  14260. geometry.lineDistancesNeedUpdate = false;
  14261. material.attributes && clearCustomAttributes( material );
  14262. } else if ( object instanceof THREE.ParticleSystem ) {
  14263. material = getBufferMaterial( object, geometry );
  14264. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14265. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  14266. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  14267. }
  14268. geometry.verticesNeedUpdate = false;
  14269. geometry.colorsNeedUpdate = false;
  14270. material.attributes && clearCustomAttributes( material );
  14271. }
  14272. };
  14273. // Objects updates - custom attributes check
  14274. function areCustomAttributesDirty( material ) {
  14275. for ( var a in material.attributes ) {
  14276. if ( material.attributes[ a ].needsUpdate ) return true;
  14277. }
  14278. return false;
  14279. };
  14280. function clearCustomAttributes( material ) {
  14281. for ( var a in material.attributes ) {
  14282. material.attributes[ a ].needsUpdate = false;
  14283. }
  14284. };
  14285. // Objects removal
  14286. function removeObject( object, scene ) {
  14287. if ( object instanceof THREE.Mesh ||
  14288. object instanceof THREE.ParticleSystem ||
  14289. object instanceof THREE.Ribbon ||
  14290. object instanceof THREE.Line ) {
  14291. removeInstances( scene.__webglObjects, object );
  14292. } else if ( object instanceof THREE.Sprite ) {
  14293. removeInstancesDirect( scene.__webglSprites, object );
  14294. } else if ( object instanceof THREE.LensFlare ) {
  14295. removeInstancesDirect( scene.__webglFlares, object );
  14296. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14297. removeInstances( scene.__webglObjectsImmediate, object );
  14298. }
  14299. delete object.__webglActive;
  14300. };
  14301. function removeInstances( objlist, object ) {
  14302. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  14303. if ( objlist[ o ].object === object ) {
  14304. objlist.splice( o, 1 );
  14305. }
  14306. }
  14307. };
  14308. function removeInstancesDirect( objlist, object ) {
  14309. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  14310. if ( objlist[ o ] === object ) {
  14311. objlist.splice( o, 1 );
  14312. }
  14313. }
  14314. };
  14315. // Materials
  14316. this.initMaterial = function ( material, lights, fog, object ) {
  14317. material.addEventListener( 'dispose', onMaterialDispose );
  14318. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  14319. if ( material instanceof THREE.MeshDepthMaterial ) {
  14320. shaderID = 'depth';
  14321. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14322. shaderID = 'normal';
  14323. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  14324. shaderID = 'basic';
  14325. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14326. shaderID = 'lambert';
  14327. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14328. shaderID = 'phong';
  14329. } else if ( material instanceof THREE.LineBasicMaterial ) {
  14330. shaderID = 'basic';
  14331. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14332. shaderID = 'dashed';
  14333. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  14334. shaderID = 'particle_basic';
  14335. }
  14336. if ( shaderID ) {
  14337. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  14338. }
  14339. // heuristics to create shader parameters according to lights in the scene
  14340. // (not to blow over maxLights budget)
  14341. maxLightCount = allocateLights( lights );
  14342. maxShadows = allocateShadows( lights );
  14343. maxBones = allocateBones( object );
  14344. parameters = {
  14345. map: !!material.map,
  14346. envMap: !!material.envMap,
  14347. lightMap: !!material.lightMap,
  14348. bumpMap: !!material.bumpMap,
  14349. normalMap: !!material.normalMap,
  14350. specularMap: !!material.specularMap,
  14351. vertexColors: material.vertexColors,
  14352. fog: fog,
  14353. useFog: material.fog,
  14354. fogExp: fog instanceof THREE.FogExp2,
  14355. sizeAttenuation: material.sizeAttenuation,
  14356. skinning: material.skinning,
  14357. maxBones: maxBones,
  14358. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  14359. boneTextureWidth: object && object.boneTextureWidth,
  14360. boneTextureHeight: object && object.boneTextureHeight,
  14361. morphTargets: material.morphTargets,
  14362. morphNormals: material.morphNormals,
  14363. maxMorphTargets: this.maxMorphTargets,
  14364. maxMorphNormals: this.maxMorphNormals,
  14365. maxDirLights: maxLightCount.directional,
  14366. maxPointLights: maxLightCount.point,
  14367. maxSpotLights: maxLightCount.spot,
  14368. maxHemiLights: maxLightCount.hemi,
  14369. maxShadows: maxShadows,
  14370. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  14371. shadowMapType: this.shadowMapType,
  14372. shadowMapDebug: this.shadowMapDebug,
  14373. shadowMapCascade: this.shadowMapCascade,
  14374. alphaTest: material.alphaTest,
  14375. metal: material.metal,
  14376. perPixel: material.perPixel,
  14377. wrapAround: material.wrapAround,
  14378. doubleSided: material.side === THREE.DoubleSide,
  14379. flipSided: material.side === THREE.BackSide
  14380. };
  14381. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters );
  14382. var attributes = material.program.attributes;
  14383. if ( material.morphTargets ) {
  14384. material.numSupportedMorphTargets = 0;
  14385. var id, base = "morphTarget";
  14386. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  14387. id = base + i;
  14388. if ( attributes[ id ] >= 0 ) {
  14389. material.numSupportedMorphTargets ++;
  14390. }
  14391. }
  14392. }
  14393. if ( material.morphNormals ) {
  14394. material.numSupportedMorphNormals = 0;
  14395. var id, base = "morphNormal";
  14396. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  14397. id = base + i;
  14398. if ( attributes[ id ] >= 0 ) {
  14399. material.numSupportedMorphNormals ++;
  14400. }
  14401. }
  14402. }
  14403. material.uniformsList = [];
  14404. for ( u in material.uniforms ) {
  14405. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  14406. }
  14407. };
  14408. function setMaterialShaders( material, shaders ) {
  14409. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  14410. material.vertexShader = shaders.vertexShader;
  14411. material.fragmentShader = shaders.fragmentShader;
  14412. };
  14413. function setProgram( camera, lights, fog, material, object ) {
  14414. _usedTextureUnits = 0;
  14415. if ( material.needsUpdate ) {
  14416. if ( material.program ) deallocateMaterial( material );
  14417. _this.initMaterial( material, lights, fog, object );
  14418. material.needsUpdate = false;
  14419. }
  14420. if ( material.morphTargets ) {
  14421. if ( ! object.__webglMorphTargetInfluences ) {
  14422. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  14423. }
  14424. }
  14425. var refreshMaterial = false;
  14426. var program = material.program,
  14427. p_uniforms = program.uniforms,
  14428. m_uniforms = material.uniforms;
  14429. if ( program !== _currentProgram ) {
  14430. _gl.useProgram( program );
  14431. _currentProgram = program;
  14432. refreshMaterial = true;
  14433. }
  14434. if ( material.id !== _currentMaterialId ) {
  14435. _currentMaterialId = material.id;
  14436. refreshMaterial = true;
  14437. }
  14438. if ( refreshMaterial || camera !== _currentCamera ) {
  14439. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  14440. if ( camera !== _currentCamera ) _currentCamera = camera;
  14441. }
  14442. // skinning uniforms must be set even if material didn't change
  14443. // auto-setting of texture unit for bone texture must go before other textures
  14444. // not sure why, but otherwise weird things happen
  14445. if ( material.skinning ) {
  14446. if ( _supportsBoneTextures && object.useVertexTexture ) {
  14447. if ( p_uniforms.boneTexture !== null ) {
  14448. var textureUnit = getTextureUnit();
  14449. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  14450. _this.setTexture( object.boneTexture, textureUnit );
  14451. }
  14452. } else {
  14453. if ( p_uniforms.boneGlobalMatrices !== null ) {
  14454. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  14455. }
  14456. }
  14457. }
  14458. if ( refreshMaterial ) {
  14459. // refresh uniforms common to several materials
  14460. if ( fog && material.fog ) {
  14461. refreshUniformsFog( m_uniforms, fog );
  14462. }
  14463. if ( material instanceof THREE.MeshPhongMaterial ||
  14464. material instanceof THREE.MeshLambertMaterial ||
  14465. material.lights ) {
  14466. if ( _lightsNeedUpdate ) {
  14467. setupLights( program, lights );
  14468. _lightsNeedUpdate = false;
  14469. }
  14470. refreshUniformsLights( m_uniforms, _lights );
  14471. }
  14472. if ( material instanceof THREE.MeshBasicMaterial ||
  14473. material instanceof THREE.MeshLambertMaterial ||
  14474. material instanceof THREE.MeshPhongMaterial ) {
  14475. refreshUniformsCommon( m_uniforms, material );
  14476. }
  14477. // refresh single material specific uniforms
  14478. if ( material instanceof THREE.LineBasicMaterial ) {
  14479. refreshUniformsLine( m_uniforms, material );
  14480. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14481. refreshUniformsLine( m_uniforms, material );
  14482. refreshUniformsDash( m_uniforms, material );
  14483. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  14484. refreshUniformsParticle( m_uniforms, material );
  14485. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14486. refreshUniformsPhong( m_uniforms, material );
  14487. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14488. refreshUniformsLambert( m_uniforms, material );
  14489. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  14490. m_uniforms.mNear.value = camera.near;
  14491. m_uniforms.mFar.value = camera.far;
  14492. m_uniforms.opacity.value = material.opacity;
  14493. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14494. m_uniforms.opacity.value = material.opacity;
  14495. }
  14496. if ( object.receiveShadow && ! material._shadowPass ) {
  14497. refreshUniformsShadow( m_uniforms, lights );
  14498. }
  14499. // load common uniforms
  14500. loadUniformsGeneric( program, material.uniformsList );
  14501. // load material specific uniforms
  14502. // (shader material also gets them for the sake of genericity)
  14503. if ( material instanceof THREE.ShaderMaterial ||
  14504. material instanceof THREE.MeshPhongMaterial ||
  14505. material.envMap ) {
  14506. if ( p_uniforms.cameraPosition !== null ) {
  14507. _vector3.getPositionFromMatrix( camera.matrixWorld );
  14508. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  14509. }
  14510. }
  14511. if ( material instanceof THREE.MeshPhongMaterial ||
  14512. material instanceof THREE.MeshLambertMaterial ||
  14513. material instanceof THREE.ShaderMaterial ||
  14514. material.skinning ) {
  14515. if ( p_uniforms.viewMatrix !== null ) {
  14516. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  14517. }
  14518. }
  14519. }
  14520. loadUniformsMatrices( p_uniforms, object );
  14521. if ( p_uniforms.modelMatrix !== null ) {
  14522. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  14523. }
  14524. return program;
  14525. };
  14526. // Uniforms (refresh uniforms objects)
  14527. function refreshUniformsCommon ( uniforms, material ) {
  14528. uniforms.opacity.value = material.opacity;
  14529. if ( _this.gammaInput ) {
  14530. uniforms.diffuse.value.copyGammaToLinear( material.color );
  14531. } else {
  14532. uniforms.diffuse.value = material.color;
  14533. }
  14534. uniforms.map.value = material.map;
  14535. uniforms.lightMap.value = material.lightMap;
  14536. uniforms.specularMap.value = material.specularMap;
  14537. if ( material.bumpMap ) {
  14538. uniforms.bumpMap.value = material.bumpMap;
  14539. uniforms.bumpScale.value = material.bumpScale;
  14540. }
  14541. if ( material.normalMap ) {
  14542. uniforms.normalMap.value = material.normalMap;
  14543. uniforms.normalScale.value.copy( material.normalScale );
  14544. }
  14545. // uv repeat and offset setting priorities
  14546. // 1. color map
  14547. // 2. specular map
  14548. // 3. normal map
  14549. // 4. bump map
  14550. var uvScaleMap;
  14551. if ( material.map ) {
  14552. uvScaleMap = material.map;
  14553. } else if ( material.specularMap ) {
  14554. uvScaleMap = material.specularMap;
  14555. } else if ( material.normalMap ) {
  14556. uvScaleMap = material.normalMap;
  14557. } else if ( material.bumpMap ) {
  14558. uvScaleMap = material.bumpMap;
  14559. }
  14560. if ( uvScaleMap !== undefined ) {
  14561. var offset = uvScaleMap.offset;
  14562. var repeat = uvScaleMap.repeat;
  14563. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  14564. }
  14565. uniforms.envMap.value = material.envMap;
  14566. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  14567. if ( _this.gammaInput ) {
  14568. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  14569. uniforms.reflectivity.value = material.reflectivity;
  14570. } else {
  14571. uniforms.reflectivity.value = material.reflectivity;
  14572. }
  14573. uniforms.refractionRatio.value = material.refractionRatio;
  14574. uniforms.combine.value = material.combine;
  14575. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  14576. };
  14577. function refreshUniformsLine ( uniforms, material ) {
  14578. uniforms.diffuse.value = material.color;
  14579. uniforms.opacity.value = material.opacity;
  14580. };
  14581. function refreshUniformsDash ( uniforms, material ) {
  14582. uniforms.dashSize.value = material.dashSize;
  14583. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14584. uniforms.scale.value = material.scale;
  14585. };
  14586. function refreshUniformsParticle ( uniforms, material ) {
  14587. uniforms.psColor.value = material.color;
  14588. uniforms.opacity.value = material.opacity;
  14589. uniforms.size.value = material.size;
  14590. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  14591. uniforms.map.value = material.map;
  14592. };
  14593. function refreshUniformsFog ( uniforms, fog ) {
  14594. uniforms.fogColor.value = fog.color;
  14595. if ( fog instanceof THREE.Fog ) {
  14596. uniforms.fogNear.value = fog.near;
  14597. uniforms.fogFar.value = fog.far;
  14598. } else if ( fog instanceof THREE.FogExp2 ) {
  14599. uniforms.fogDensity.value = fog.density;
  14600. }
  14601. };
  14602. function refreshUniformsPhong ( uniforms, material ) {
  14603. uniforms.shininess.value = material.shininess;
  14604. if ( _this.gammaInput ) {
  14605. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14606. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14607. uniforms.specular.value.copyGammaToLinear( material.specular );
  14608. } else {
  14609. uniforms.ambient.value = material.ambient;
  14610. uniforms.emissive.value = material.emissive;
  14611. uniforms.specular.value = material.specular;
  14612. }
  14613. if ( material.wrapAround ) {
  14614. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14615. }
  14616. };
  14617. function refreshUniformsLambert ( uniforms, material ) {
  14618. if ( _this.gammaInput ) {
  14619. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14620. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14621. } else {
  14622. uniforms.ambient.value = material.ambient;
  14623. uniforms.emissive.value = material.emissive;
  14624. }
  14625. if ( material.wrapAround ) {
  14626. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14627. }
  14628. };
  14629. function refreshUniformsLights ( uniforms, lights ) {
  14630. uniforms.ambientLightColor.value = lights.ambient;
  14631. uniforms.directionalLightColor.value = lights.directional.colors;
  14632. uniforms.directionalLightDirection.value = lights.directional.positions;
  14633. uniforms.pointLightColor.value = lights.point.colors;
  14634. uniforms.pointLightPosition.value = lights.point.positions;
  14635. uniforms.pointLightDistance.value = lights.point.distances;
  14636. uniforms.spotLightColor.value = lights.spot.colors;
  14637. uniforms.spotLightPosition.value = lights.spot.positions;
  14638. uniforms.spotLightDistance.value = lights.spot.distances;
  14639. uniforms.spotLightDirection.value = lights.spot.directions;
  14640. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  14641. uniforms.spotLightExponent.value = lights.spot.exponents;
  14642. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  14643. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  14644. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  14645. };
  14646. function refreshUniformsShadow ( uniforms, lights ) {
  14647. if ( uniforms.shadowMatrix ) {
  14648. var j = 0;
  14649. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  14650. var light = lights[ i ];
  14651. if ( ! light.castShadow ) continue;
  14652. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  14653. uniforms.shadowMap.value[ j ] = light.shadowMap;
  14654. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  14655. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  14656. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  14657. uniforms.shadowBias.value[ j ] = light.shadowBias;
  14658. j ++;
  14659. }
  14660. }
  14661. }
  14662. };
  14663. // Uniforms (load to GPU)
  14664. function loadUniformsMatrices ( uniforms, object ) {
  14665. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  14666. if ( uniforms.normalMatrix ) {
  14667. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  14668. }
  14669. };
  14670. function getTextureUnit() {
  14671. var textureUnit = _usedTextureUnits;
  14672. if ( textureUnit >= _maxTextures ) {
  14673. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  14674. }
  14675. _usedTextureUnits += 1;
  14676. return textureUnit;
  14677. };
  14678. function loadUniformsGeneric ( program, uniforms ) {
  14679. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  14680. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  14681. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  14682. if ( !location ) continue;
  14683. uniform = uniforms[ j ][ 0 ];
  14684. type = uniform.type;
  14685. value = uniform.value;
  14686. if ( type === "i" ) { // single integer
  14687. _gl.uniform1i( location, value );
  14688. } else if ( type === "f" ) { // single float
  14689. _gl.uniform1f( location, value );
  14690. } else if ( type === "v2" ) { // single THREE.Vector2
  14691. _gl.uniform2f( location, value.x, value.y );
  14692. } else if ( type === "v3" ) { // single THREE.Vector3
  14693. _gl.uniform3f( location, value.x, value.y, value.z );
  14694. } else if ( type === "v4" ) { // single THREE.Vector4
  14695. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  14696. } else if ( type === "c" ) { // single THREE.Color
  14697. _gl.uniform3f( location, value.r, value.g, value.b );
  14698. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  14699. _gl.uniform1iv( location, value );
  14700. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  14701. _gl.uniform3iv( location, value );
  14702. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  14703. _gl.uniform1fv( location, value );
  14704. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  14705. _gl.uniform3fv( location, value );
  14706. } else if ( type === "v2v" ) { // array of THREE.Vector2
  14707. if ( uniform._array === undefined ) {
  14708. uniform._array = new Float32Array( 2 * value.length );
  14709. }
  14710. for ( i = 0, il = value.length; i < il; i ++ ) {
  14711. offset = i * 2;
  14712. uniform._array[ offset ] = value[ i ].x;
  14713. uniform._array[ offset + 1 ] = value[ i ].y;
  14714. }
  14715. _gl.uniform2fv( location, uniform._array );
  14716. } else if ( type === "v3v" ) { // array of THREE.Vector3
  14717. if ( uniform._array === undefined ) {
  14718. uniform._array = new Float32Array( 3 * value.length );
  14719. }
  14720. for ( i = 0, il = value.length; i < il; i ++ ) {
  14721. offset = i * 3;
  14722. uniform._array[ offset ] = value[ i ].x;
  14723. uniform._array[ offset + 1 ] = value[ i ].y;
  14724. uniform._array[ offset + 2 ] = value[ i ].z;
  14725. }
  14726. _gl.uniform3fv( location, uniform._array );
  14727. } else if ( type === "v4v" ) { // array of THREE.Vector4
  14728. if ( uniform._array === undefined ) {
  14729. uniform._array = new Float32Array( 4 * value.length );
  14730. }
  14731. for ( i = 0, il = value.length; i < il; i ++ ) {
  14732. offset = i * 4;
  14733. uniform._array[ offset ] = value[ i ].x;
  14734. uniform._array[ offset + 1 ] = value[ i ].y;
  14735. uniform._array[ offset + 2 ] = value[ i ].z;
  14736. uniform._array[ offset + 3 ] = value[ i ].w;
  14737. }
  14738. _gl.uniform4fv( location, uniform._array );
  14739. } else if ( type === "m4") { // single THREE.Matrix4
  14740. if ( uniform._array === undefined ) {
  14741. uniform._array = new Float32Array( 16 );
  14742. }
  14743. value.flattenToArray( uniform._array );
  14744. _gl.uniformMatrix4fv( location, false, uniform._array );
  14745. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  14746. if ( uniform._array === undefined ) {
  14747. uniform._array = new Float32Array( 16 * value.length );
  14748. }
  14749. for ( i = 0, il = value.length; i < il; i ++ ) {
  14750. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  14751. }
  14752. _gl.uniformMatrix4fv( location, false, uniform._array );
  14753. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  14754. texture = value;
  14755. textureUnit = getTextureUnit();
  14756. _gl.uniform1i( location, textureUnit );
  14757. if ( !texture ) continue;
  14758. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  14759. setCubeTexture( texture, textureUnit );
  14760. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  14761. setCubeTextureDynamic( texture, textureUnit );
  14762. } else {
  14763. _this.setTexture( texture, textureUnit );
  14764. }
  14765. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  14766. if ( uniform._array === undefined ) {
  14767. uniform._array = [];
  14768. }
  14769. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14770. uniform._array[ i ] = getTextureUnit();
  14771. }
  14772. _gl.uniform1iv( location, uniform._array );
  14773. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14774. texture = uniform.value[ i ];
  14775. textureUnit = uniform._array[ i ];
  14776. if ( !texture ) continue;
  14777. _this.setTexture( texture, textureUnit );
  14778. }
  14779. }
  14780. }
  14781. };
  14782. function setupMatrices ( object, camera ) {
  14783. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  14784. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  14785. };
  14786. //
  14787. function setColorGamma( array, offset, color, intensitySq ) {
  14788. array[ offset ] = color.r * color.r * intensitySq;
  14789. array[ offset + 1 ] = color.g * color.g * intensitySq;
  14790. array[ offset + 2 ] = color.b * color.b * intensitySq;
  14791. };
  14792. function setColorLinear( array, offset, color, intensity ) {
  14793. array[ offset ] = color.r * intensity;
  14794. array[ offset + 1 ] = color.g * intensity;
  14795. array[ offset + 2 ] = color.b * intensity;
  14796. };
  14797. function setupLights ( program, lights ) {
  14798. var l, ll, light, n,
  14799. r = 0, g = 0, b = 0,
  14800. color, skyColor, groundColor,
  14801. intensity, intensitySq,
  14802. position,
  14803. distance,
  14804. zlights = _lights,
  14805. dirColors = zlights.directional.colors,
  14806. dirPositions = zlights.directional.positions,
  14807. pointColors = zlights.point.colors,
  14808. pointPositions = zlights.point.positions,
  14809. pointDistances = zlights.point.distances,
  14810. spotColors = zlights.spot.colors,
  14811. spotPositions = zlights.spot.positions,
  14812. spotDistances = zlights.spot.distances,
  14813. spotDirections = zlights.spot.directions,
  14814. spotAnglesCos = zlights.spot.anglesCos,
  14815. spotExponents = zlights.spot.exponents,
  14816. hemiSkyColors = zlights.hemi.skyColors,
  14817. hemiGroundColors = zlights.hemi.groundColors,
  14818. hemiPositions = zlights.hemi.positions,
  14819. dirLength = 0,
  14820. pointLength = 0,
  14821. spotLength = 0,
  14822. hemiLength = 0,
  14823. dirCount = 0,
  14824. pointCount = 0,
  14825. spotCount = 0,
  14826. hemiCount = 0,
  14827. dirOffset = 0,
  14828. pointOffset = 0,
  14829. spotOffset = 0,
  14830. hemiOffset = 0;
  14831. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14832. light = lights[ l ];
  14833. if ( light.onlyShadow ) continue;
  14834. color = light.color;
  14835. intensity = light.intensity;
  14836. distance = light.distance;
  14837. if ( light instanceof THREE.AmbientLight ) {
  14838. if ( ! light.visible ) continue;
  14839. if ( _this.gammaInput ) {
  14840. r += color.r * color.r;
  14841. g += color.g * color.g;
  14842. b += color.b * color.b;
  14843. } else {
  14844. r += color.r;
  14845. g += color.g;
  14846. b += color.b;
  14847. }
  14848. } else if ( light instanceof THREE.DirectionalLight ) {
  14849. dirCount += 1;
  14850. if ( ! light.visible ) continue;
  14851. _direction.getPositionFromMatrix( light.matrixWorld );
  14852. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  14853. _direction.sub( _vector3 );
  14854. _direction.normalize();
  14855. // skip lights with undefined direction
  14856. // these create troubles in OpenGL (making pixel black)
  14857. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14858. dirOffset = dirLength * 3;
  14859. dirPositions[ dirOffset ] = _direction.x;
  14860. dirPositions[ dirOffset + 1 ] = _direction.y;
  14861. dirPositions[ dirOffset + 2 ] = _direction.z;
  14862. if ( _this.gammaInput ) {
  14863. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  14864. } else {
  14865. setColorLinear( dirColors, dirOffset, color, intensity );
  14866. }
  14867. dirLength += 1;
  14868. } else if ( light instanceof THREE.PointLight ) {
  14869. pointCount += 1;
  14870. if ( ! light.visible ) continue;
  14871. pointOffset = pointLength * 3;
  14872. if ( _this.gammaInput ) {
  14873. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  14874. } else {
  14875. setColorLinear( pointColors, pointOffset, color, intensity );
  14876. }
  14877. _vector3.getPositionFromMatrix( light.matrixWorld );
  14878. pointPositions[ pointOffset ] = _vector3.x;
  14879. pointPositions[ pointOffset + 1 ] = _vector3.y;
  14880. pointPositions[ pointOffset + 2 ] = _vector3.z;
  14881. pointDistances[ pointLength ] = distance;
  14882. pointLength += 1;
  14883. } else if ( light instanceof THREE.SpotLight ) {
  14884. spotCount += 1;
  14885. if ( ! light.visible ) continue;
  14886. spotOffset = spotLength * 3;
  14887. if ( _this.gammaInput ) {
  14888. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  14889. } else {
  14890. setColorLinear( spotColors, spotOffset, color, intensity );
  14891. }
  14892. _vector3.getPositionFromMatrix( light.matrixWorld );
  14893. spotPositions[ spotOffset ] = _vector3.x;
  14894. spotPositions[ spotOffset + 1 ] = _vector3.y;
  14895. spotPositions[ spotOffset + 2 ] = _vector3.z;
  14896. spotDistances[ spotLength ] = distance;
  14897. _direction.copy( _vector3 );
  14898. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  14899. _direction.sub( _vector3 );
  14900. _direction.normalize();
  14901. spotDirections[ spotOffset ] = _direction.x;
  14902. spotDirections[ spotOffset + 1 ] = _direction.y;
  14903. spotDirections[ spotOffset + 2 ] = _direction.z;
  14904. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  14905. spotExponents[ spotLength ] = light.exponent;
  14906. spotLength += 1;
  14907. } else if ( light instanceof THREE.HemisphereLight ) {
  14908. hemiCount += 1;
  14909. if ( ! light.visible ) continue;
  14910. _direction.getPositionFromMatrix( light.matrixWorld );
  14911. _direction.normalize();
  14912. // skip lights with undefined direction
  14913. // these create troubles in OpenGL (making pixel black)
  14914. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14915. hemiOffset = hemiLength * 3;
  14916. hemiPositions[ hemiOffset ] = _direction.x;
  14917. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  14918. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  14919. skyColor = light.color;
  14920. groundColor = light.groundColor;
  14921. if ( _this.gammaInput ) {
  14922. intensitySq = intensity * intensity;
  14923. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  14924. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  14925. } else {
  14926. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  14927. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  14928. }
  14929. hemiLength += 1;
  14930. }
  14931. }
  14932. // null eventual remains from removed lights
  14933. // (this is to avoid if in shader)
  14934. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  14935. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  14936. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  14937. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  14938. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  14939. zlights.directional.length = dirLength;
  14940. zlights.point.length = pointLength;
  14941. zlights.spot.length = spotLength;
  14942. zlights.hemi.length = hemiLength;
  14943. zlights.ambient[ 0 ] = r;
  14944. zlights.ambient[ 1 ] = g;
  14945. zlights.ambient[ 2 ] = b;
  14946. };
  14947. // GL state setting
  14948. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  14949. if ( cullFace === THREE.CullFaceNone ) {
  14950. _gl.disable( _gl.CULL_FACE );
  14951. } else {
  14952. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  14953. _gl.frontFace( _gl.CW );
  14954. } else {
  14955. _gl.frontFace( _gl.CCW );
  14956. }
  14957. if ( cullFace === THREE.CullFaceBack ) {
  14958. _gl.cullFace( _gl.BACK );
  14959. } else if ( cullFace === THREE.CullFaceFront ) {
  14960. _gl.cullFace( _gl.FRONT );
  14961. } else {
  14962. _gl.cullFace( _gl.FRONT_AND_BACK );
  14963. }
  14964. _gl.enable( _gl.CULL_FACE );
  14965. }
  14966. };
  14967. this.setMaterialFaces = function ( material ) {
  14968. var doubleSided = material.side === THREE.DoubleSide;
  14969. var flipSided = material.side === THREE.BackSide;
  14970. if ( _oldDoubleSided !== doubleSided ) {
  14971. if ( doubleSided ) {
  14972. _gl.disable( _gl.CULL_FACE );
  14973. } else {
  14974. _gl.enable( _gl.CULL_FACE );
  14975. }
  14976. _oldDoubleSided = doubleSided;
  14977. }
  14978. if ( _oldFlipSided !== flipSided ) {
  14979. if ( flipSided ) {
  14980. _gl.frontFace( _gl.CW );
  14981. } else {
  14982. _gl.frontFace( _gl.CCW );
  14983. }
  14984. _oldFlipSided = flipSided;
  14985. }
  14986. };
  14987. this.setDepthTest = function ( depthTest ) {
  14988. if ( _oldDepthTest !== depthTest ) {
  14989. if ( depthTest ) {
  14990. _gl.enable( _gl.DEPTH_TEST );
  14991. } else {
  14992. _gl.disable( _gl.DEPTH_TEST );
  14993. }
  14994. _oldDepthTest = depthTest;
  14995. }
  14996. };
  14997. this.setDepthWrite = function ( depthWrite ) {
  14998. if ( _oldDepthWrite !== depthWrite ) {
  14999. _gl.depthMask( depthWrite );
  15000. _oldDepthWrite = depthWrite;
  15001. }
  15002. };
  15003. function setLineWidth ( width ) {
  15004. if ( width !== _oldLineWidth ) {
  15005. _gl.lineWidth( width );
  15006. _oldLineWidth = width;
  15007. }
  15008. };
  15009. function setPolygonOffset ( polygonoffset, factor, units ) {
  15010. if ( _oldPolygonOffset !== polygonoffset ) {
  15011. if ( polygonoffset ) {
  15012. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  15013. } else {
  15014. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  15015. }
  15016. _oldPolygonOffset = polygonoffset;
  15017. }
  15018. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  15019. _gl.polygonOffset( factor, units );
  15020. _oldPolygonOffsetFactor = factor;
  15021. _oldPolygonOffsetUnits = units;
  15022. }
  15023. };
  15024. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  15025. if ( blending !== _oldBlending ) {
  15026. if ( blending === THREE.NoBlending ) {
  15027. _gl.disable( _gl.BLEND );
  15028. } else if ( blending === THREE.AdditiveBlending ) {
  15029. _gl.enable( _gl.BLEND );
  15030. _gl.blendEquation( _gl.FUNC_ADD );
  15031. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  15032. } else if ( blending === THREE.SubtractiveBlending ) {
  15033. // TODO: Find blendFuncSeparate() combination
  15034. _gl.enable( _gl.BLEND );
  15035. _gl.blendEquation( _gl.FUNC_ADD );
  15036. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  15037. } else if ( blending === THREE.MultiplyBlending ) {
  15038. // TODO: Find blendFuncSeparate() combination
  15039. _gl.enable( _gl.BLEND );
  15040. _gl.blendEquation( _gl.FUNC_ADD );
  15041. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  15042. } else if ( blending === THREE.CustomBlending ) {
  15043. _gl.enable( _gl.BLEND );
  15044. } else {
  15045. _gl.enable( _gl.BLEND );
  15046. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  15047. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  15048. }
  15049. _oldBlending = blending;
  15050. }
  15051. if ( blending === THREE.CustomBlending ) {
  15052. if ( blendEquation !== _oldBlendEquation ) {
  15053. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  15054. _oldBlendEquation = blendEquation;
  15055. }
  15056. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  15057. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  15058. _oldBlendSrc = blendSrc;
  15059. _oldBlendDst = blendDst;
  15060. }
  15061. } else {
  15062. _oldBlendEquation = null;
  15063. _oldBlendSrc = null;
  15064. _oldBlendDst = null;
  15065. }
  15066. };
  15067. // Defines
  15068. function generateDefines ( defines ) {
  15069. var value, chunk, chunks = [];
  15070. for ( var d in defines ) {
  15071. value = defines[ d ];
  15072. if ( value === false ) continue;
  15073. chunk = "#define " + d + " " + value;
  15074. chunks.push( chunk );
  15075. }
  15076. return chunks.join( "\n" );
  15077. };
  15078. // Shaders
  15079. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters ) {
  15080. var p, pl, d, program, code;
  15081. var chunks = [];
  15082. // Generate code
  15083. if ( shaderID ) {
  15084. chunks.push( shaderID );
  15085. } else {
  15086. chunks.push( fragmentShader );
  15087. chunks.push( vertexShader );
  15088. }
  15089. for ( d in defines ) {
  15090. chunks.push( d );
  15091. chunks.push( defines[ d ] );
  15092. }
  15093. for ( p in parameters ) {
  15094. chunks.push( p );
  15095. chunks.push( parameters[ p ] );
  15096. }
  15097. code = chunks.join();
  15098. // Check if code has been already compiled
  15099. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  15100. var programInfo = _programs[ p ];
  15101. if ( programInfo.code === code ) {
  15102. // console.log( "Code already compiled." /*: \n\n" + code*/ );
  15103. programInfo.usedTimes ++;
  15104. return programInfo.program;
  15105. }
  15106. }
  15107. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  15108. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  15109. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  15110. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  15111. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  15112. }
  15113. // console.log( "building new program " );
  15114. //
  15115. var customDefines = generateDefines( defines );
  15116. //
  15117. program = _gl.createProgram();
  15118. var prefix_vertex = [
  15119. "precision " + _precision + " float;",
  15120. customDefines,
  15121. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  15122. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  15123. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  15124. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  15125. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  15126. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  15127. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  15128. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  15129. "#define MAX_SHADOWS " + parameters.maxShadows,
  15130. "#define MAX_BONES " + parameters.maxBones,
  15131. parameters.map ? "#define USE_MAP" : "",
  15132. parameters.envMap ? "#define USE_ENVMAP" : "",
  15133. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  15134. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  15135. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  15136. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  15137. parameters.vertexColors ? "#define USE_COLOR" : "",
  15138. parameters.skinning ? "#define USE_SKINNING" : "",
  15139. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  15140. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  15141. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  15142. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  15143. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  15144. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  15145. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  15146. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  15147. parameters.flipSided ? "#define FLIP_SIDED" : "",
  15148. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  15149. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  15150. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  15151. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  15152. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  15153. "uniform mat4 modelMatrix;",
  15154. "uniform mat4 modelViewMatrix;",
  15155. "uniform mat4 projectionMatrix;",
  15156. "uniform mat4 viewMatrix;",
  15157. "uniform mat3 normalMatrix;",
  15158. "uniform vec3 cameraPosition;",
  15159. "attribute vec3 position;",
  15160. "attribute vec3 normal;",
  15161. "attribute vec2 uv;",
  15162. "attribute vec2 uv2;",
  15163. "#ifdef USE_COLOR",
  15164. "attribute vec3 color;",
  15165. "#endif",
  15166. "#ifdef USE_MORPHTARGETS",
  15167. "attribute vec3 morphTarget0;",
  15168. "attribute vec3 morphTarget1;",
  15169. "attribute vec3 morphTarget2;",
  15170. "attribute vec3 morphTarget3;",
  15171. "#ifdef USE_MORPHNORMALS",
  15172. "attribute vec3 morphNormal0;",
  15173. "attribute vec3 morphNormal1;",
  15174. "attribute vec3 morphNormal2;",
  15175. "attribute vec3 morphNormal3;",
  15176. "#else",
  15177. "attribute vec3 morphTarget4;",
  15178. "attribute vec3 morphTarget5;",
  15179. "attribute vec3 morphTarget6;",
  15180. "attribute vec3 morphTarget7;",
  15181. "#endif",
  15182. "#endif",
  15183. "#ifdef USE_SKINNING",
  15184. "attribute vec4 skinIndex;",
  15185. "attribute vec4 skinWeight;",
  15186. "#endif",
  15187. ""
  15188. ].join("\n");
  15189. var prefix_fragment = [
  15190. "precision " + _precision + " float;",
  15191. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  15192. customDefines,
  15193. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  15194. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  15195. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  15196. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  15197. "#define MAX_SHADOWS " + parameters.maxShadows,
  15198. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  15199. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  15200. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  15201. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  15202. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  15203. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  15204. parameters.map ? "#define USE_MAP" : "",
  15205. parameters.envMap ? "#define USE_ENVMAP" : "",
  15206. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  15207. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  15208. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  15209. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  15210. parameters.vertexColors ? "#define USE_COLOR" : "",
  15211. parameters.metal ? "#define METAL" : "",
  15212. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  15213. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  15214. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  15215. parameters.flipSided ? "#define FLIP_SIDED" : "",
  15216. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  15217. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  15218. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  15219. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  15220. "uniform mat4 viewMatrix;",
  15221. "uniform vec3 cameraPosition;",
  15222. ""
  15223. ].join("\n");
  15224. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  15225. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  15226. _gl.attachShader( program, glVertexShader );
  15227. _gl.attachShader( program, glFragmentShader );
  15228. _gl.linkProgram( program );
  15229. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  15230. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  15231. }
  15232. // clean up
  15233. _gl.deleteShader( glFragmentShader );
  15234. _gl.deleteShader( glVertexShader );
  15235. // console.log( prefix_fragment + fragmentShader );
  15236. // console.log( prefix_vertex + vertexShader );
  15237. program.uniforms = {};
  15238. program.attributes = {};
  15239. var identifiers, u, a, i;
  15240. // cache uniform locations
  15241. identifiers = [
  15242. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  15243. 'morphTargetInfluences'
  15244. ];
  15245. if ( parameters.useVertexTexture ) {
  15246. identifiers.push( 'boneTexture' );
  15247. } else {
  15248. identifiers.push( 'boneGlobalMatrices' );
  15249. }
  15250. for ( u in uniforms ) {
  15251. identifiers.push( u );
  15252. }
  15253. cacheUniformLocations( program, identifiers );
  15254. // cache attributes locations
  15255. identifiers = [
  15256. "position", "normal", "uv", "uv2", "tangent", "color",
  15257. "skinIndex", "skinWeight", "lineDistance"
  15258. ];
  15259. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  15260. identifiers.push( "morphTarget" + i );
  15261. }
  15262. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  15263. identifiers.push( "morphNormal" + i );
  15264. }
  15265. for ( a in attributes ) {
  15266. identifiers.push( a );
  15267. }
  15268. cacheAttributeLocations( program, identifiers );
  15269. program.id = _programs_counter ++;
  15270. _programs.push( { program: program, code: code, usedTimes: 1 } );
  15271. _this.info.memory.programs = _programs.length;
  15272. return program;
  15273. };
  15274. // Shader parameters cache
  15275. function cacheUniformLocations ( program, identifiers ) {
  15276. var i, l, id;
  15277. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  15278. id = identifiers[ i ];
  15279. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  15280. }
  15281. };
  15282. function cacheAttributeLocations ( program, identifiers ) {
  15283. var i, l, id;
  15284. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  15285. id = identifiers[ i ];
  15286. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  15287. }
  15288. };
  15289. function addLineNumbers ( string ) {
  15290. var chunks = string.split( "\n" );
  15291. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  15292. // Chrome reports shader errors on lines
  15293. // starting counting from 1
  15294. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  15295. }
  15296. return chunks.join( "\n" );
  15297. };
  15298. function getShader ( type, string ) {
  15299. var shader;
  15300. if ( type === "fragment" ) {
  15301. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  15302. } else if ( type === "vertex" ) {
  15303. shader = _gl.createShader( _gl.VERTEX_SHADER );
  15304. }
  15305. _gl.shaderSource( shader, string );
  15306. _gl.compileShader( shader );
  15307. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  15308. console.error( _gl.getShaderInfoLog( shader ) );
  15309. console.error( addLineNumbers( string ) );
  15310. return null;
  15311. }
  15312. return shader;
  15313. };
  15314. // Textures
  15315. function isPowerOfTwo ( value ) {
  15316. return ( value & ( value - 1 ) ) === 0;
  15317. };
  15318. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  15319. if ( isImagePowerOfTwo ) {
  15320. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  15321. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  15322. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  15323. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  15324. } else {
  15325. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  15326. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  15327. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  15328. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  15329. }
  15330. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  15331. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  15332. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  15333. texture.__oldAnisotropy = texture.anisotropy;
  15334. }
  15335. }
  15336. };
  15337. this.setTexture = function ( texture, slot ) {
  15338. if ( texture.needsUpdate ) {
  15339. if ( ! texture.__webglInit ) {
  15340. texture.__webglInit = true;
  15341. texture.addEventListener( 'dispose', onTextureDispose );
  15342. texture.__webglTexture = _gl.createTexture();
  15343. _this.info.memory.textures ++;
  15344. }
  15345. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15346. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15347. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15348. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  15349. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  15350. var image = texture.image,
  15351. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  15352. glFormat = paramThreeToGL( texture.format ),
  15353. glType = paramThreeToGL( texture.type );
  15354. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  15355. var mipmap, mipmaps = texture.mipmaps;
  15356. if ( texture instanceof THREE.DataTexture ) {
  15357. // use manually created mipmaps if available
  15358. // if there are no manual mipmaps
  15359. // set 0 level mipmap and then use GL to generate other mipmap levels
  15360. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15361. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15362. mipmap = mipmaps[ i ];
  15363. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15364. }
  15365. texture.generateMipmaps = false;
  15366. } else {
  15367. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  15368. }
  15369. } else if ( texture instanceof THREE.CompressedTexture ) {
  15370. // compressed textures can only use manually created mipmaps
  15371. // WebGL can't generate mipmaps for DDS textures
  15372. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15373. mipmap = mipmaps[ i ];
  15374. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15375. }
  15376. } else { // regular Texture (image, video, canvas)
  15377. // use manually created mipmaps if available
  15378. // if there are no manual mipmaps
  15379. // set 0 level mipmap and then use GL to generate other mipmap levels
  15380. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15381. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15382. mipmap = mipmaps[ i ];
  15383. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  15384. }
  15385. texture.generateMipmaps = false;
  15386. } else {
  15387. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  15388. }
  15389. }
  15390. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15391. texture.needsUpdate = false;
  15392. if ( texture.onUpdate ) texture.onUpdate();
  15393. } else {
  15394. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15395. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15396. }
  15397. };
  15398. function clampToMaxSize ( image, maxSize ) {
  15399. if ( image.width <= maxSize && image.height <= maxSize ) {
  15400. return image;
  15401. }
  15402. // Warning: Scaling through the canvas will only work with images that use
  15403. // premultiplied alpha.
  15404. var maxDimension = Math.max( image.width, image.height );
  15405. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  15406. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  15407. var canvas = document.createElement( 'canvas' );
  15408. canvas.width = newWidth;
  15409. canvas.height = newHeight;
  15410. var ctx = canvas.getContext( "2d" );
  15411. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  15412. return canvas;
  15413. }
  15414. function setCubeTexture ( texture, slot ) {
  15415. if ( texture.image.length === 6 ) {
  15416. if ( texture.needsUpdate ) {
  15417. if ( ! texture.image.__webglTextureCube ) {
  15418. texture.addEventListener( 'dispose', onTextureDispose );
  15419. texture.image.__webglTextureCube = _gl.createTexture();
  15420. _this.info.memory.textures ++;
  15421. }
  15422. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15423. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15424. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15425. var isCompressed = texture instanceof THREE.CompressedTexture;
  15426. var cubeImage = [];
  15427. for ( var i = 0; i < 6; i ++ ) {
  15428. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  15429. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  15430. } else {
  15431. cubeImage[ i ] = texture.image[ i ];
  15432. }
  15433. }
  15434. var image = cubeImage[ 0 ],
  15435. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  15436. glFormat = paramThreeToGL( texture.format ),
  15437. glType = paramThreeToGL( texture.type );
  15438. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  15439. for ( var i = 0; i < 6; i ++ ) {
  15440. if ( isCompressed ) {
  15441. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  15442. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  15443. mipmap = mipmaps[ j ];
  15444. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15445. }
  15446. } else {
  15447. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  15448. }
  15449. }
  15450. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  15451. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15452. }
  15453. texture.needsUpdate = false;
  15454. if ( texture.onUpdate ) texture.onUpdate();
  15455. } else {
  15456. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15457. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15458. }
  15459. }
  15460. };
  15461. function setCubeTextureDynamic ( texture, slot ) {
  15462. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15463. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  15464. };
  15465. // Render targets
  15466. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  15467. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15468. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  15469. };
  15470. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  15471. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15472. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15473. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  15474. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15475. /* For some reason this is not working. Defaulting to RGBA4.
  15476. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15477. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  15478. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15479. */
  15480. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15481. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15482. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15483. } else {
  15484. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  15485. }
  15486. };
  15487. this.setRenderTarget = function ( renderTarget ) {
  15488. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  15489. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  15490. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  15491. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  15492. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15493. renderTarget.__webglTexture = _gl.createTexture();
  15494. _this.info.memory.textures ++;
  15495. // Setup texture, create render and frame buffers
  15496. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  15497. glFormat = paramThreeToGL( renderTarget.format ),
  15498. glType = paramThreeToGL( renderTarget.type );
  15499. if ( isCube ) {
  15500. renderTarget.__webglFramebuffer = [];
  15501. renderTarget.__webglRenderbuffer = [];
  15502. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15503. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  15504. for ( var i = 0; i < 6; i ++ ) {
  15505. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15506. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  15507. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15508. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  15509. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  15510. }
  15511. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15512. } else {
  15513. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  15514. if ( renderTarget.shareDepthFrom ) {
  15515. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  15516. } else {
  15517. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  15518. }
  15519. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15520. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  15521. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15522. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  15523. if ( renderTarget.shareDepthFrom ) {
  15524. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15525. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15526. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15527. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15528. }
  15529. } else {
  15530. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  15531. }
  15532. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15533. }
  15534. // Release everything
  15535. if ( isCube ) {
  15536. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15537. } else {
  15538. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15539. }
  15540. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15541. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15542. }
  15543. var framebuffer, width, height, vx, vy;
  15544. if ( renderTarget ) {
  15545. if ( isCube ) {
  15546. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  15547. } else {
  15548. framebuffer = renderTarget.__webglFramebuffer;
  15549. }
  15550. width = renderTarget.width;
  15551. height = renderTarget.height;
  15552. vx = 0;
  15553. vy = 0;
  15554. } else {
  15555. framebuffer = null;
  15556. width = _viewportWidth;
  15557. height = _viewportHeight;
  15558. vx = _viewportX;
  15559. vy = _viewportY;
  15560. }
  15561. if ( framebuffer !== _currentFramebuffer ) {
  15562. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15563. _gl.viewport( vx, vy, width, height );
  15564. _currentFramebuffer = framebuffer;
  15565. }
  15566. _currentWidth = width;
  15567. _currentHeight = height;
  15568. };
  15569. function updateRenderTargetMipmap ( renderTarget ) {
  15570. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  15571. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15572. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15573. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15574. } else {
  15575. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15576. _gl.generateMipmap( _gl.TEXTURE_2D );
  15577. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15578. }
  15579. };
  15580. // Fallback filters for non-power-of-2 textures
  15581. function filterFallback ( f ) {
  15582. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  15583. return _gl.NEAREST;
  15584. }
  15585. return _gl.LINEAR;
  15586. };
  15587. // Map three.js constants to WebGL constants
  15588. function paramThreeToGL ( p ) {
  15589. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  15590. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  15591. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  15592. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  15593. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  15594. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  15595. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  15596. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  15597. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  15598. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  15599. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  15600. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  15601. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  15602. if ( p === THREE.ByteType ) return _gl.BYTE;
  15603. if ( p === THREE.ShortType ) return _gl.SHORT;
  15604. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  15605. if ( p === THREE.IntType ) return _gl.INT;
  15606. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  15607. if ( p === THREE.FloatType ) return _gl.FLOAT;
  15608. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  15609. if ( p === THREE.RGBFormat ) return _gl.RGB;
  15610. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  15611. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  15612. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  15613. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  15614. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  15615. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  15616. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  15617. if ( p === THREE.OneFactor ) return _gl.ONE;
  15618. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  15619. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  15620. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  15621. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  15622. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  15623. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  15624. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  15625. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  15626. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  15627. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  15628. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15629. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15630. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15631. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15632. }
  15633. return 0;
  15634. };
  15635. // Allocations
  15636. function allocateBones ( object ) {
  15637. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  15638. return 1024;
  15639. } else {
  15640. // default for when object is not specified
  15641. // ( for example when prebuilding shader
  15642. // to be used with multiple objects )
  15643. //
  15644. // - leave some extra space for other uniforms
  15645. // - limit here is ANGLE's 254 max uniform vectors
  15646. // (up to 54 should be safe)
  15647. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  15648. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  15649. var maxBones = nVertexMatrices;
  15650. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  15651. maxBones = Math.min( object.bones.length, maxBones );
  15652. if ( maxBones < object.bones.length ) {
  15653. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  15654. }
  15655. }
  15656. return maxBones;
  15657. }
  15658. };
  15659. function allocateLights( lights ) {
  15660. var dirLights = 0;
  15661. var pointLights = 0;
  15662. var spotLights = 0;
  15663. var hemiLights = 0;
  15664. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  15665. var light = lights[ l ];
  15666. if ( light.onlyShadow ) continue;
  15667. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  15668. if ( light instanceof THREE.PointLight ) pointLights ++;
  15669. if ( light instanceof THREE.SpotLight ) spotLights ++;
  15670. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  15671. }
  15672. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  15673. };
  15674. function allocateShadows( lights ) {
  15675. var maxShadows = 0;
  15676. for ( var l = 0, ll = lights.length; l < ll; l++ ) {
  15677. var light = lights[ l ];
  15678. if ( ! light.castShadow ) continue;
  15679. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  15680. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  15681. }
  15682. return maxShadows;
  15683. };
  15684. // Initialization
  15685. function initGL() {
  15686. try {
  15687. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  15688. throw 'Error creating WebGL context.';
  15689. }
  15690. } catch ( error ) {
  15691. console.error( error );
  15692. }
  15693. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  15694. _glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' );
  15695. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  15696. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15697. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15698. if ( ! _glExtensionTextureFloat ) {
  15699. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  15700. }
  15701. if ( ! _glExtensionStandardDerivatives ) {
  15702. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  15703. }
  15704. if ( ! _glExtensionTextureFilterAnisotropic ) {
  15705. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  15706. }
  15707. if ( ! _glExtensionCompressedTextureS3TC ) {
  15708. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  15709. }
  15710. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15711. _gl.getShaderPrecisionFormat = function() {
  15712. return {
  15713. "rangeMin" : 1,
  15714. "rangeMax" : 1,
  15715. "precision" : 1
  15716. };
  15717. }
  15718. }
  15719. };
  15720. function setDefaultGLState () {
  15721. _gl.clearColor( 0, 0, 0, 1 );
  15722. _gl.clearDepth( 1 );
  15723. _gl.clearStencil( 0 );
  15724. _gl.enable( _gl.DEPTH_TEST );
  15725. _gl.depthFunc( _gl.LEQUAL );
  15726. _gl.frontFace( _gl.CCW );
  15727. _gl.cullFace( _gl.BACK );
  15728. _gl.enable( _gl.CULL_FACE );
  15729. _gl.enable( _gl.BLEND );
  15730. _gl.blendEquation( _gl.FUNC_ADD );
  15731. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  15732. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  15733. };
  15734. // default plugins (order is important)
  15735. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  15736. this.addPrePlugin( this.shadowMapPlugin );
  15737. this.addPostPlugin( new THREE.SpritePlugin() );
  15738. this.addPostPlugin( new THREE.LensFlarePlugin() );
  15739. };
  15740. /**
  15741. * @author szimek / https://github.com/szimek/
  15742. * @author alteredq / http://alteredqualia.com/
  15743. */
  15744. THREE.WebGLRenderTarget = function ( width, height, options ) {
  15745. this.width = width;
  15746. this.height = height;
  15747. options = options || {};
  15748. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  15749. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  15750. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  15751. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  15752. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  15753. this.offset = new THREE.Vector2( 0, 0 );
  15754. this.repeat = new THREE.Vector2( 1, 1 );
  15755. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  15756. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  15757. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  15758. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  15759. this.generateMipmaps = true;
  15760. this.shareDepthFrom = null;
  15761. };
  15762. THREE.WebGLRenderTarget.prototype = {
  15763. constructor: THREE.WebGLRenderTarget,
  15764. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  15765. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  15766. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  15767. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  15768. clone: function () {
  15769. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  15770. tmp.wrapS = this.wrapS;
  15771. tmp.wrapT = this.wrapT;
  15772. tmp.magFilter = this.magFilter;
  15773. tmp.minFilter = this.minFilter;
  15774. tmp.anisotropy = this.anisotropy;
  15775. tmp.offset.copy( this.offset );
  15776. tmp.repeat.copy( this.repeat );
  15777. tmp.format = this.format;
  15778. tmp.type = this.type;
  15779. tmp.depthBuffer = this.depthBuffer;
  15780. tmp.stencilBuffer = this.stencilBuffer;
  15781. tmp.generateMipmaps = this.generateMipmaps;
  15782. tmp.shareDepthFrom = this.shareDepthFrom;
  15783. return tmp;
  15784. },
  15785. dispose: function () {
  15786. this.dispatchEvent( { type: 'dispose' } );
  15787. }
  15788. };
  15789. /**
  15790. * @author alteredq / http://alteredqualia.com
  15791. */
  15792. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  15793. THREE.WebGLRenderTarget.call( this, width, height, options );
  15794. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  15795. };
  15796. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  15797. /**
  15798. * @author mrdoob / http://mrdoob.com/
  15799. */
  15800. THREE.RenderableVertex = function () {
  15801. this.positionWorld = new THREE.Vector3();
  15802. this.positionScreen = new THREE.Vector4();
  15803. this.visible = true;
  15804. };
  15805. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  15806. this.positionWorld.copy( vertex.positionWorld );
  15807. this.positionScreen.copy( vertex.positionScreen );
  15808. };
  15809. /**
  15810. * @author mrdoob / http://mrdoob.com/
  15811. */
  15812. THREE.RenderableFace3 = function () {
  15813. this.v1 = new THREE.RenderableVertex();
  15814. this.v2 = new THREE.RenderableVertex();
  15815. this.v3 = new THREE.RenderableVertex();
  15816. this.centroidModel = new THREE.Vector3();
  15817. this.normalModel = new THREE.Vector3();
  15818. this.normalModelView = new THREE.Vector3();
  15819. this.vertexNormalsLength = 0;
  15820. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15821. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15822. this.color = null;
  15823. this.material = null;
  15824. this.uvs = [[]];
  15825. this.z = null;
  15826. };
  15827. /**
  15828. * @author mrdoob / http://mrdoob.com/
  15829. */
  15830. THREE.RenderableFace4 = function () {
  15831. this.v1 = new THREE.RenderableVertex();
  15832. this.v2 = new THREE.RenderableVertex();
  15833. this.v3 = new THREE.RenderableVertex();
  15834. this.v4 = new THREE.RenderableVertex();
  15835. this.centroidModel = new THREE.Vector3();
  15836. this.normalModel = new THREE.Vector3();
  15837. this.normalModelView = new THREE.Vector3();
  15838. this.vertexNormalsLength = 0;
  15839. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15840. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15841. this.color = null;
  15842. this.material = null;
  15843. this.uvs = [[]];
  15844. this.z = null;
  15845. };
  15846. /**
  15847. * @author mrdoob / http://mrdoob.com/
  15848. */
  15849. THREE.RenderableObject = function () {
  15850. this.object = null;
  15851. this.z = null;
  15852. };
  15853. /**
  15854. * @author mrdoob / http://mrdoob.com/
  15855. */
  15856. THREE.RenderableParticle = function () {
  15857. this.object = null;
  15858. this.x = null;
  15859. this.y = null;
  15860. this.z = null;
  15861. this.rotation = null;
  15862. this.scale = new THREE.Vector2();
  15863. this.material = null;
  15864. };
  15865. /**
  15866. * @author mrdoob / http://mrdoob.com/
  15867. */
  15868. THREE.RenderableLine = function () {
  15869. this.z = null;
  15870. this.v1 = new THREE.RenderableVertex();
  15871. this.v2 = new THREE.RenderableVertex();
  15872. this.vertexColors = [ new THREE.Color(), new THREE.Color() ];
  15873. this.material = null;
  15874. };
  15875. /**
  15876. * @author mrdoob / http://mrdoob.com/
  15877. * @author alteredq / http://alteredqualia.com/
  15878. */
  15879. THREE.GeometryUtils = {
  15880. // Merge two geometries or geometry and geometry from object (using object's transform)
  15881. merge: function ( geometry1, object2 /* mesh | geometry */, materialIndexOffset ) {
  15882. var matrix, normalMatrix,
  15883. vertexOffset = geometry1.vertices.length,
  15884. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  15885. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  15886. vertices1 = geometry1.vertices,
  15887. vertices2 = geometry2.vertices,
  15888. faces1 = geometry1.faces,
  15889. faces2 = geometry2.faces,
  15890. uvs1 = geometry1.faceVertexUvs[ 0 ],
  15891. uvs2 = geometry2.faceVertexUvs[ 0 ];
  15892. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  15893. if ( object2 instanceof THREE.Mesh ) {
  15894. object2.matrixAutoUpdate && object2.updateMatrix();
  15895. matrix = object2.matrix;
  15896. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  15897. }
  15898. // vertices
  15899. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  15900. var vertex = vertices2[ i ];
  15901. var vertexCopy = vertex.clone();
  15902. if ( matrix ) vertexCopy.applyMatrix4( matrix );
  15903. vertices1.push( vertexCopy );
  15904. }
  15905. // faces
  15906. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  15907. var face = faces2[ i ], faceCopy, normal, color,
  15908. faceVertexNormals = face.vertexNormals,
  15909. faceVertexColors = face.vertexColors;
  15910. if ( face instanceof THREE.Face3 ) {
  15911. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  15912. } else if ( face instanceof THREE.Face4 ) {
  15913. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  15914. }
  15915. faceCopy.normal.copy( face.normal );
  15916. if ( normalMatrix ) {
  15917. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  15918. }
  15919. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  15920. normal = faceVertexNormals[ j ].clone();
  15921. if ( normalMatrix ) {
  15922. normal.applyMatrix3( normalMatrix ).normalize();
  15923. }
  15924. faceCopy.vertexNormals.push( normal );
  15925. }
  15926. faceCopy.color.copy( face.color );
  15927. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  15928. color = faceVertexColors[ j ];
  15929. faceCopy.vertexColors.push( color.clone() );
  15930. }
  15931. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  15932. faceCopy.centroid.copy( face.centroid );
  15933. if ( matrix ) {
  15934. faceCopy.centroid.applyMatrix4( matrix );
  15935. }
  15936. faces1.push( faceCopy );
  15937. }
  15938. // uvs
  15939. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  15940. var uv = uvs2[ i ], uvCopy = [];
  15941. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  15942. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  15943. }
  15944. uvs1.push( uvCopy );
  15945. }
  15946. },
  15947. removeMaterials: function ( geometry, materialIndexArray ) {
  15948. var materialIndexMap = {};
  15949. for ( var i = 0, il = materialIndexArray.length; i < il; i ++ ) {
  15950. materialIndexMap[ materialIndexArray[i] ] = true;
  15951. }
  15952. var face, newFaces = [];
  15953. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15954. face = geometry.faces[ i ];
  15955. if ( ! ( face.materialIndex in materialIndexMap ) ) newFaces.push( face );
  15956. }
  15957. geometry.faces = newFaces;
  15958. },
  15959. // Get random point in triangle (via barycentric coordinates)
  15960. // (uniform distribution)
  15961. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  15962. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  15963. var a, b, c,
  15964. point = new THREE.Vector3(),
  15965. tmp = THREE.GeometryUtils.__v1;
  15966. a = THREE.GeometryUtils.random();
  15967. b = THREE.GeometryUtils.random();
  15968. if ( ( a + b ) > 1 ) {
  15969. a = 1 - a;
  15970. b = 1 - b;
  15971. }
  15972. c = 1 - a - b;
  15973. point.copy( vectorA );
  15974. point.multiplyScalar( a );
  15975. tmp.copy( vectorB );
  15976. tmp.multiplyScalar( b );
  15977. point.add( tmp );
  15978. tmp.copy( vectorC );
  15979. tmp.multiplyScalar( c );
  15980. point.add( tmp );
  15981. return point;
  15982. },
  15983. // Get random point in face (triangle / quad)
  15984. // (uniform distribution)
  15985. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  15986. var vA, vB, vC, vD;
  15987. if ( face instanceof THREE.Face3 ) {
  15988. vA = geometry.vertices[ face.a ];
  15989. vB = geometry.vertices[ face.b ];
  15990. vC = geometry.vertices[ face.c ];
  15991. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  15992. } else if ( face instanceof THREE.Face4 ) {
  15993. vA = geometry.vertices[ face.a ];
  15994. vB = geometry.vertices[ face.b ];
  15995. vC = geometry.vertices[ face.c ];
  15996. vD = geometry.vertices[ face.d ];
  15997. var area1, area2;
  15998. if ( useCachedAreas ) {
  15999. if ( face._area1 && face._area2 ) {
  16000. area1 = face._area1;
  16001. area2 = face._area2;
  16002. } else {
  16003. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  16004. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  16005. face._area1 = area1;
  16006. face._area2 = area2;
  16007. }
  16008. } else {
  16009. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  16010. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  16011. }
  16012. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  16013. if ( r < area1 ) {
  16014. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  16015. } else {
  16016. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  16017. }
  16018. }
  16019. },
  16020. // Get uniformly distributed random points in mesh
  16021. // - create array with cumulative sums of face areas
  16022. // - pick random number from 0 to total area
  16023. // - find corresponding place in area array by binary search
  16024. // - get random point in face
  16025. randomPointsInGeometry: function ( geometry, n ) {
  16026. var face, i,
  16027. faces = geometry.faces,
  16028. vertices = geometry.vertices,
  16029. il = faces.length,
  16030. totalArea = 0,
  16031. cumulativeAreas = [],
  16032. vA, vB, vC, vD;
  16033. // precompute face areas
  16034. for ( i = 0; i < il; i ++ ) {
  16035. face = faces[ i ];
  16036. if ( face instanceof THREE.Face3 ) {
  16037. vA = vertices[ face.a ];
  16038. vB = vertices[ face.b ];
  16039. vC = vertices[ face.c ];
  16040. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  16041. } else if ( face instanceof THREE.Face4 ) {
  16042. vA = vertices[ face.a ];
  16043. vB = vertices[ face.b ];
  16044. vC = vertices[ face.c ];
  16045. vD = vertices[ face.d ];
  16046. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  16047. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  16048. face._area = face._area1 + face._area2;
  16049. }
  16050. totalArea += face._area;
  16051. cumulativeAreas[ i ] = totalArea;
  16052. }
  16053. // binary search cumulative areas array
  16054. function binarySearchIndices( value ) {
  16055. function binarySearch( start, end ) {
  16056. // return closest larger index
  16057. // if exact number is not found
  16058. if ( end < start )
  16059. return start;
  16060. var mid = start + Math.floor( ( end - start ) / 2 );
  16061. if ( cumulativeAreas[ mid ] > value ) {
  16062. return binarySearch( start, mid - 1 );
  16063. } else if ( cumulativeAreas[ mid ] < value ) {
  16064. return binarySearch( mid + 1, end );
  16065. } else {
  16066. return mid;
  16067. }
  16068. }
  16069. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  16070. return result;
  16071. }
  16072. // pick random face weighted by face area
  16073. var r, index,
  16074. result = [];
  16075. var stats = {};
  16076. for ( i = 0; i < n; i ++ ) {
  16077. r = THREE.GeometryUtils.random() * totalArea;
  16078. index = binarySearchIndices( r );
  16079. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  16080. if ( ! stats[ index ] ) {
  16081. stats[ index ] = 1;
  16082. } else {
  16083. stats[ index ] += 1;
  16084. }
  16085. }
  16086. return result;
  16087. },
  16088. // Get triangle area (half of parallelogram)
  16089. // http://mathworld.wolfram.com/TriangleArea.html
  16090. triangleArea: function ( vectorA, vectorB, vectorC ) {
  16091. var tmp1 = THREE.GeometryUtils.__v1,
  16092. tmp2 = THREE.GeometryUtils.__v2;
  16093. tmp1.subVectors( vectorB, vectorA );
  16094. tmp2.subVectors( vectorC, vectorA );
  16095. tmp1.cross( tmp2 );
  16096. return 0.5 * tmp1.length();
  16097. },
  16098. // Center geometry so that 0,0,0 is in center of bounding box
  16099. center: function ( geometry ) {
  16100. geometry.computeBoundingBox();
  16101. var bb = geometry.boundingBox;
  16102. var offset = new THREE.Vector3();
  16103. offset.addVectors( bb.min, bb.max );
  16104. offset.multiplyScalar( -0.5 );
  16105. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  16106. geometry.computeBoundingBox();
  16107. return offset;
  16108. },
  16109. // Normalize UVs to be from <0,1>
  16110. // (for now just the first set of UVs)
  16111. normalizeUVs: function ( geometry ) {
  16112. var uvSet = geometry.faceVertexUvs[ 0 ];
  16113. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  16114. var uvs = uvSet[ i ];
  16115. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  16116. // texture repeat
  16117. if( uvs[ j ].x !== 1.0 ) uvs[ j ].x = uvs[ j ].x - Math.floor( uvs[ j ].x );
  16118. if( uvs[ j ].y !== 1.0 ) uvs[ j ].y = uvs[ j ].y - Math.floor( uvs[ j ].y );
  16119. }
  16120. }
  16121. },
  16122. triangulateQuads: function ( geometry ) {
  16123. var i, il, j, jl;
  16124. var faces = [];
  16125. var faceUvs = [];
  16126. var faceVertexUvs = [];
  16127. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  16128. faceUvs[ i ] = [];
  16129. }
  16130. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  16131. faceVertexUvs[ i ] = [];
  16132. }
  16133. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  16134. var face = geometry.faces[ i ];
  16135. if ( face instanceof THREE.Face4 ) {
  16136. var a = face.a;
  16137. var b = face.b;
  16138. var c = face.c;
  16139. var d = face.d;
  16140. var triA = new THREE.Face3();
  16141. var triB = new THREE.Face3();
  16142. triA.color.copy( face.color );
  16143. triB.color.copy( face.color );
  16144. triA.materialIndex = face.materialIndex;
  16145. triB.materialIndex = face.materialIndex;
  16146. triA.a = a;
  16147. triA.b = b;
  16148. triA.c = d;
  16149. triB.a = b;
  16150. triB.b = c;
  16151. triB.c = d;
  16152. if ( face.vertexColors.length === 4 ) {
  16153. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  16154. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  16155. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  16156. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  16157. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  16158. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  16159. }
  16160. faces.push( triA, triB );
  16161. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  16162. if ( geometry.faceVertexUvs[ j ].length ) {
  16163. var uvs = geometry.faceVertexUvs[ j ][ i ];
  16164. var uvA = uvs[ 0 ];
  16165. var uvB = uvs[ 1 ];
  16166. var uvC = uvs[ 2 ];
  16167. var uvD = uvs[ 3 ];
  16168. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  16169. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  16170. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  16171. }
  16172. }
  16173. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  16174. if ( geometry.faceUvs[ j ].length ) {
  16175. var faceUv = geometry.faceUvs[ j ][ i ];
  16176. faceUvs[ j ].push( faceUv, faceUv );
  16177. }
  16178. }
  16179. } else {
  16180. faces.push( face );
  16181. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  16182. faceUvs[ j ].push( geometry.faceUvs[ j ][ i ] );
  16183. }
  16184. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  16185. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  16186. }
  16187. }
  16188. }
  16189. geometry.faces = faces;
  16190. geometry.faceUvs = faceUvs;
  16191. geometry.faceVertexUvs = faceVertexUvs;
  16192. geometry.computeCentroids();
  16193. geometry.computeFaceNormals();
  16194. geometry.computeVertexNormals();
  16195. if ( geometry.hasTangents ) geometry.computeTangents();
  16196. },
  16197. setMaterialIndex: function ( geometry, index, startFace, endFace ){
  16198. var faces = geometry.faces;
  16199. var start = startFace || 0;
  16200. var end = endFace || faces.length - 1;
  16201. for ( var i = start; i <= end; i ++ ) {
  16202. faces[i].materialIndex = index;
  16203. }
  16204. }
  16205. };
  16206. THREE.GeometryUtils.random = THREE.Math.random16;
  16207. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  16208. THREE.GeometryUtils.__v2 = new THREE.Vector3();
  16209. /**
  16210. * @author alteredq / http://alteredqualia.com/
  16211. * @author mrdoob / http://mrdoob.com/
  16212. */
  16213. THREE.ImageUtils = {
  16214. crossOrigin: 'anonymous',
  16215. loadTexture: function ( url, mapping, onLoad, onError ) {
  16216. var image = new Image();
  16217. var texture = new THREE.Texture( image, mapping );
  16218. var loader = new THREE.ImageLoader();
  16219. loader.crossOrigin = this.crossOrigin;
  16220. loader.load( url, function ( image ) {
  16221. texture.image = image;
  16222. texture.needsUpdate = true;
  16223. if ( onLoad ) onLoad( texture );
  16224. } );
  16225. texture.sourceFile = url;
  16226. return texture;
  16227. },
  16228. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  16229. var texture = new THREE.CompressedTexture();
  16230. texture.mapping = mapping;
  16231. var request = new XMLHttpRequest();
  16232. request.onload = function () {
  16233. var buffer = request.response;
  16234. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16235. texture.format = dds.format;
  16236. texture.mipmaps = dds.mipmaps;
  16237. texture.image.width = dds.width;
  16238. texture.image.height = dds.height;
  16239. // gl.generateMipmap fails for compressed textures
  16240. // mipmaps must be embedded in the DDS file
  16241. // or texture filters must not use mipmapping
  16242. texture.generateMipmaps = false;
  16243. texture.needsUpdate = true;
  16244. if ( onLoad ) onLoad( texture );
  16245. }
  16246. request.onerror = onError;
  16247. request.open( 'GET', url, true );
  16248. request.responseType = "arraybuffer";
  16249. request.send( null );
  16250. return texture;
  16251. },
  16252. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  16253. var images = [];
  16254. images.loadCount = 0;
  16255. var texture = new THREE.Texture();
  16256. texture.image = images;
  16257. if ( mapping !== undefined ) texture.mapping = mapping;
  16258. // no flipping needed for cube textures
  16259. texture.flipY = false;
  16260. for ( var i = 0, il = array.length; i < il; ++ i ) {
  16261. var cubeImage = new Image();
  16262. images[ i ] = cubeImage;
  16263. cubeImage.onload = function () {
  16264. images.loadCount += 1;
  16265. if ( images.loadCount === 6 ) {
  16266. texture.needsUpdate = true;
  16267. if ( onLoad ) onLoad( texture );
  16268. }
  16269. };
  16270. cubeImage.onerror = onError;
  16271. cubeImage.crossOrigin = this.crossOrigin;
  16272. cubeImage.src = array[ i ];
  16273. }
  16274. return texture;
  16275. },
  16276. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  16277. var images = [];
  16278. images.loadCount = 0;
  16279. var texture = new THREE.CompressedTexture();
  16280. texture.image = images;
  16281. if ( mapping !== undefined ) texture.mapping = mapping;
  16282. // no flipping for cube textures
  16283. // (also flipping doesn't work for compressed textures )
  16284. texture.flipY = false;
  16285. // can't generate mipmaps for compressed textures
  16286. // mips must be embedded in DDS files
  16287. texture.generateMipmaps = false;
  16288. var generateCubeFaceCallback = function ( rq, img ) {
  16289. return function () {
  16290. var buffer = rq.response;
  16291. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16292. img.format = dds.format;
  16293. img.mipmaps = dds.mipmaps;
  16294. img.width = dds.width;
  16295. img.height = dds.height;
  16296. images.loadCount += 1;
  16297. if ( images.loadCount === 6 ) {
  16298. texture.format = dds.format;
  16299. texture.needsUpdate = true;
  16300. if ( onLoad ) onLoad( texture );
  16301. }
  16302. }
  16303. }
  16304. // compressed cubemap textures as 6 separate DDS files
  16305. if ( array instanceof Array ) {
  16306. for ( var i = 0, il = array.length; i < il; ++ i ) {
  16307. var cubeImage = {};
  16308. images[ i ] = cubeImage;
  16309. var request = new XMLHttpRequest();
  16310. request.onload = generateCubeFaceCallback( request, cubeImage );
  16311. request.onerror = onError;
  16312. var url = array[ i ];
  16313. request.open( 'GET', url, true );
  16314. request.responseType = "arraybuffer";
  16315. request.send( null );
  16316. }
  16317. // compressed cubemap texture stored in a single DDS file
  16318. } else {
  16319. var url = array;
  16320. var request = new XMLHttpRequest();
  16321. request.onload = function( ) {
  16322. var buffer = request.response;
  16323. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16324. if ( dds.isCubemap ) {
  16325. var faces = dds.mipmaps.length / dds.mipmapCount;
  16326. for ( var f = 0; f < faces; f ++ ) {
  16327. images[ f ] = { mipmaps : [] };
  16328. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16329. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  16330. images[ f ].format = dds.format;
  16331. images[ f ].width = dds.width;
  16332. images[ f ].height = dds.height;
  16333. }
  16334. }
  16335. texture.format = dds.format;
  16336. texture.needsUpdate = true;
  16337. if ( onLoad ) onLoad( texture );
  16338. }
  16339. }
  16340. request.onerror = onError;
  16341. request.open( 'GET', url, true );
  16342. request.responseType = "arraybuffer";
  16343. request.send( null );
  16344. }
  16345. return texture;
  16346. },
  16347. parseDDS: function ( buffer, loadMipmaps ) {
  16348. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  16349. // Adapted from @toji's DDS utils
  16350. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  16351. // All values and structures referenced from:
  16352. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  16353. var DDS_MAGIC = 0x20534444;
  16354. var DDSD_CAPS = 0x1,
  16355. DDSD_HEIGHT = 0x2,
  16356. DDSD_WIDTH = 0x4,
  16357. DDSD_PITCH = 0x8,
  16358. DDSD_PIXELFORMAT = 0x1000,
  16359. DDSD_MIPMAPCOUNT = 0x20000,
  16360. DDSD_LINEARSIZE = 0x80000,
  16361. DDSD_DEPTH = 0x800000;
  16362. var DDSCAPS_COMPLEX = 0x8,
  16363. DDSCAPS_MIPMAP = 0x400000,
  16364. DDSCAPS_TEXTURE = 0x1000;
  16365. var DDSCAPS2_CUBEMAP = 0x200,
  16366. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  16367. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  16368. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  16369. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  16370. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  16371. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  16372. DDSCAPS2_VOLUME = 0x200000;
  16373. var DDPF_ALPHAPIXELS = 0x1,
  16374. DDPF_ALPHA = 0x2,
  16375. DDPF_FOURCC = 0x4,
  16376. DDPF_RGB = 0x40,
  16377. DDPF_YUV = 0x200,
  16378. DDPF_LUMINANCE = 0x20000;
  16379. function fourCCToInt32( value ) {
  16380. return value.charCodeAt(0) +
  16381. (value.charCodeAt(1) << 8) +
  16382. (value.charCodeAt(2) << 16) +
  16383. (value.charCodeAt(3) << 24);
  16384. }
  16385. function int32ToFourCC( value ) {
  16386. return String.fromCharCode(
  16387. value & 0xff,
  16388. (value >> 8) & 0xff,
  16389. (value >> 16) & 0xff,
  16390. (value >> 24) & 0xff
  16391. );
  16392. }
  16393. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  16394. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  16395. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  16396. var headerLengthInt = 31; // The header length in 32 bit ints
  16397. // Offsets into the header array
  16398. var off_magic = 0;
  16399. var off_size = 1;
  16400. var off_flags = 2;
  16401. var off_height = 3;
  16402. var off_width = 4;
  16403. var off_mipmapCount = 7;
  16404. var off_pfFlags = 20;
  16405. var off_pfFourCC = 21;
  16406. var off_caps = 27;
  16407. var off_caps2 = 28;
  16408. var off_caps3 = 29;
  16409. var off_caps4 = 30;
  16410. // Parse header
  16411. var header = new Int32Array( buffer, 0, headerLengthInt );
  16412. if ( header[ off_magic ] !== DDS_MAGIC ) {
  16413. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  16414. return dds;
  16415. }
  16416. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  16417. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  16418. return dds;
  16419. }
  16420. var blockBytes;
  16421. var fourCC = header[ off_pfFourCC ];
  16422. switch ( fourCC ) {
  16423. case FOURCC_DXT1:
  16424. blockBytes = 8;
  16425. dds.format = THREE.RGB_S3TC_DXT1_Format;
  16426. break;
  16427. case FOURCC_DXT3:
  16428. blockBytes = 16;
  16429. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  16430. break;
  16431. case FOURCC_DXT5:
  16432. blockBytes = 16;
  16433. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  16434. break;
  16435. default:
  16436. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  16437. return dds;
  16438. }
  16439. dds.mipmapCount = 1;
  16440. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  16441. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  16442. }
  16443. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  16444. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  16445. dds.width = header[ off_width ];
  16446. dds.height = header[ off_height ];
  16447. var dataOffset = header[ off_size ] + 4;
  16448. // Extract mipmaps buffers
  16449. var width = dds.width;
  16450. var height = dds.height;
  16451. var faces = dds.isCubemap ? 6 : 1;
  16452. for ( var face = 0; face < faces; face ++ ) {
  16453. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16454. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  16455. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  16456. var mipmap = { "data": byteArray, "width": width, "height": height };
  16457. dds.mipmaps.push( mipmap );
  16458. dataOffset += dataLength;
  16459. width = Math.max( width * 0.5, 1 );
  16460. height = Math.max( height * 0.5, 1 );
  16461. }
  16462. width = dds.width;
  16463. height = dds.height;
  16464. }
  16465. return dds;
  16466. },
  16467. getNormalMap: function ( image, depth ) {
  16468. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  16469. var cross = function ( a, b ) {
  16470. 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 ] ];
  16471. }
  16472. var subtract = function ( a, b ) {
  16473. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  16474. }
  16475. var normalize = function ( a ) {
  16476. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  16477. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  16478. }
  16479. depth = depth | 1;
  16480. var width = image.width;
  16481. var height = image.height;
  16482. var canvas = document.createElement( 'canvas' );
  16483. canvas.width = width;
  16484. canvas.height = height;
  16485. var context = canvas.getContext( '2d' );
  16486. context.drawImage( image, 0, 0 );
  16487. var data = context.getImageData( 0, 0, width, height ).data;
  16488. var imageData = context.createImageData( width, height );
  16489. var output = imageData.data;
  16490. for ( var x = 0; x < width; x ++ ) {
  16491. for ( var y = 0; y < height; y ++ ) {
  16492. var ly = y - 1 < 0 ? 0 : y - 1;
  16493. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  16494. var lx = x - 1 < 0 ? 0 : x - 1;
  16495. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  16496. var points = [];
  16497. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  16498. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  16499. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  16500. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  16501. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  16502. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  16503. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  16504. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  16505. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  16506. var normals = [];
  16507. var num_points = points.length;
  16508. for ( var i = 0; i < num_points; i ++ ) {
  16509. var v1 = points[ i ];
  16510. var v2 = points[ ( i + 1 ) % num_points ];
  16511. v1 = subtract( v1, origin );
  16512. v2 = subtract( v2, origin );
  16513. normals.push( normalize( cross( v1, v2 ) ) );
  16514. }
  16515. var normal = [ 0, 0, 0 ];
  16516. for ( var i = 0; i < normals.length; i ++ ) {
  16517. normal[ 0 ] += normals[ i ][ 0 ];
  16518. normal[ 1 ] += normals[ i ][ 1 ];
  16519. normal[ 2 ] += normals[ i ][ 2 ];
  16520. }
  16521. normal[ 0 ] /= normals.length;
  16522. normal[ 1 ] /= normals.length;
  16523. normal[ 2 ] /= normals.length;
  16524. var idx = ( y * width + x ) * 4;
  16525. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16526. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16527. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  16528. output[ idx + 3 ] = 255;
  16529. }
  16530. }
  16531. context.putImageData( imageData, 0, 0 );
  16532. return canvas;
  16533. },
  16534. generateDataTexture: function ( width, height, color ) {
  16535. var size = width * height;
  16536. var data = new Uint8Array( 3 * size );
  16537. var r = Math.floor( color.r * 255 );
  16538. var g = Math.floor( color.g * 255 );
  16539. var b = Math.floor( color.b * 255 );
  16540. for ( var i = 0; i < size; i ++ ) {
  16541. data[ i * 3 ] = r;
  16542. data[ i * 3 + 1 ] = g;
  16543. data[ i * 3 + 2 ] = b;
  16544. }
  16545. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  16546. texture.needsUpdate = true;
  16547. return texture;
  16548. }
  16549. };
  16550. /**
  16551. * @author alteredq / http://alteredqualia.com/
  16552. */
  16553. THREE.SceneUtils = {
  16554. createMultiMaterialObject: function ( geometry, materials ) {
  16555. var group = new THREE.Object3D();
  16556. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  16557. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  16558. }
  16559. return group;
  16560. },
  16561. detach : function ( child, parent, scene ) {
  16562. child.applyMatrix( parent.matrixWorld );
  16563. parent.remove( child );
  16564. scene.add( child );
  16565. },
  16566. attach: function ( child, scene, parent ) {
  16567. var matrixWorldInverse = new THREE.Matrix4();
  16568. matrixWorldInverse.getInverse( parent.matrixWorld );
  16569. child.applyMatrix( matrixWorldInverse );
  16570. scene.remove( child );
  16571. parent.add( child );
  16572. }
  16573. };
  16574. /**
  16575. * @author zz85 / http://www.lab4games.net/zz85/blog
  16576. * @author alteredq / http://alteredqualia.com/
  16577. *
  16578. * For Text operations in three.js (See TextGeometry)
  16579. *
  16580. * It uses techniques used in:
  16581. *
  16582. * typeface.js and canvastext
  16583. * For converting fonts and rendering with javascript
  16584. * http://typeface.neocracy.org
  16585. *
  16586. * Triangulation ported from AS3
  16587. * Simple Polygon Triangulation
  16588. * http://actionsnippet.com/?p=1462
  16589. *
  16590. * A Method to triangulate shapes with holes
  16591. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  16592. *
  16593. */
  16594. THREE.FontUtils = {
  16595. faces : {},
  16596. // Just for now. face[weight][style]
  16597. face : "helvetiker",
  16598. weight: "normal",
  16599. style : "normal",
  16600. size : 150,
  16601. divisions : 10,
  16602. getFace : function() {
  16603. return this.faces[ this.face ][ this.weight ][ this.style ];
  16604. },
  16605. loadFace : function( data ) {
  16606. var family = data.familyName.toLowerCase();
  16607. var ThreeFont = this;
  16608. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  16609. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  16610. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16611. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16612. return data;
  16613. },
  16614. drawText : function( text ) {
  16615. var characterPts = [], allPts = [];
  16616. // RenderText
  16617. var i, p,
  16618. face = this.getFace(),
  16619. scale = this.size / face.resolution,
  16620. offset = 0,
  16621. chars = String( text ).split( '' ),
  16622. length = chars.length;
  16623. var fontPaths = [];
  16624. for ( i = 0; i < length; i ++ ) {
  16625. var path = new THREE.Path();
  16626. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  16627. offset += ret.offset;
  16628. fontPaths.push( ret.path );
  16629. }
  16630. // get the width
  16631. var width = offset / 2;
  16632. //
  16633. // for ( p = 0; p < allPts.length; p++ ) {
  16634. //
  16635. // allPts[ p ].x -= width;
  16636. //
  16637. // }
  16638. //var extract = this.extractPoints( allPts, characterPts );
  16639. //extract.contour = allPts;
  16640. //extract.paths = fontPaths;
  16641. //extract.offset = width;
  16642. return { paths : fontPaths, offset : width };
  16643. },
  16644. extractGlyphPoints : function( c, face, scale, offset, path ) {
  16645. var pts = [];
  16646. var i, i2, divisions,
  16647. outline, action, length,
  16648. scaleX, scaleY,
  16649. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16650. laste,
  16651. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16652. if ( !glyph ) return;
  16653. if ( glyph.o ) {
  16654. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16655. length = outline.length;
  16656. scaleX = scale;
  16657. scaleY = scale;
  16658. for ( i = 0; i < length; ) {
  16659. action = outline[ i ++ ];
  16660. //console.log( action );
  16661. switch( action ) {
  16662. case 'm':
  16663. // Move To
  16664. x = outline[ i++ ] * scaleX + offset;
  16665. y = outline[ i++ ] * scaleY;
  16666. path.moveTo( x, y );
  16667. break;
  16668. case 'l':
  16669. // Line To
  16670. x = outline[ i++ ] * scaleX + offset;
  16671. y = outline[ i++ ] * scaleY;
  16672. path.lineTo(x,y);
  16673. break;
  16674. case 'q':
  16675. // QuadraticCurveTo
  16676. cpx = outline[ i++ ] * scaleX + offset;
  16677. cpy = outline[ i++ ] * scaleY;
  16678. cpx1 = outline[ i++ ] * scaleX + offset;
  16679. cpy1 = outline[ i++ ] * scaleY;
  16680. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  16681. laste = pts[ pts.length - 1 ];
  16682. if ( laste ) {
  16683. cpx0 = laste.x;
  16684. cpy0 = laste.y;
  16685. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16686. var t = i2 / divisions;
  16687. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16688. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16689. }
  16690. }
  16691. break;
  16692. case 'b':
  16693. // Cubic Bezier Curve
  16694. cpx = outline[ i++ ] * scaleX + offset;
  16695. cpy = outline[ i++ ] * scaleY;
  16696. cpx1 = outline[ i++ ] * scaleX + offset;
  16697. cpy1 = outline[ i++ ] * -scaleY;
  16698. cpx2 = outline[ i++ ] * scaleX + offset;
  16699. cpy2 = outline[ i++ ] * -scaleY;
  16700. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  16701. laste = pts[ pts.length - 1 ];
  16702. if ( laste ) {
  16703. cpx0 = laste.x;
  16704. cpy0 = laste.y;
  16705. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16706. var t = i2 / divisions;
  16707. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16708. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16709. }
  16710. }
  16711. break;
  16712. }
  16713. }
  16714. }
  16715. return { offset: glyph.ha*scale, path:path};
  16716. }
  16717. };
  16718. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16719. // Parameters
  16720. parameters = parameters || {};
  16721. var size = parameters.size !== undefined ? parameters.size : 100;
  16722. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16723. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16724. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16725. var style = parameters.style !== undefined ? parameters.style : "normal";
  16726. THREE.FontUtils.size = size;
  16727. THREE.FontUtils.divisions = curveSegments;
  16728. THREE.FontUtils.face = font;
  16729. THREE.FontUtils.weight = weight;
  16730. THREE.FontUtils.style = style;
  16731. // Get a Font data json object
  16732. var data = THREE.FontUtils.drawText( text );
  16733. var paths = data.paths;
  16734. var shapes = [];
  16735. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16736. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16737. }
  16738. return shapes;
  16739. };
  16740. /**
  16741. * This code is a quick port of code written in C++ which was submitted to
  16742. * flipcode.com by John W. Ratcliff // July 22, 2000
  16743. * See original code and more information here:
  16744. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16745. *
  16746. * ported to actionscript by Zevan Rosser
  16747. * www.actionsnippet.com
  16748. *
  16749. * ported to javascript by Joshua Koo
  16750. * http://www.lab4games.net/zz85/blog
  16751. *
  16752. */
  16753. ( function( namespace ) {
  16754. var EPSILON = 0.0000000001;
  16755. // takes in an contour array and returns
  16756. var process = function( contour, indices ) {
  16757. var n = contour.length;
  16758. if ( n < 3 ) return null;
  16759. var result = [],
  16760. verts = [],
  16761. vertIndices = [];
  16762. /* we want a counter-clockwise polygon in verts */
  16763. var u, v, w;
  16764. if ( area( contour ) > 0.0 ) {
  16765. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16766. } else {
  16767. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16768. }
  16769. var nv = n;
  16770. /* remove nv - 2 vertices, creating 1 triangle every time */
  16771. var count = 2 * nv; /* error detection */
  16772. for( v = nv - 1; nv > 2; ) {
  16773. /* if we loop, it is probably a non-simple polygon */
  16774. if ( ( count-- ) <= 0 ) {
  16775. //** Triangulate: ERROR - probable bad polygon!
  16776. //throw ( "Warning, unable to triangulate polygon!" );
  16777. //return null;
  16778. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16779. console.log( "Warning, unable to triangulate polygon!" );
  16780. if ( indices ) return vertIndices;
  16781. return result;
  16782. }
  16783. /* three consecutive vertices in current polygon, <u,v,w> */
  16784. u = v; if ( nv <= u ) u = 0; /* previous */
  16785. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16786. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16787. if ( snip( contour, u, v, w, nv, verts ) ) {
  16788. var a, b, c, s, t;
  16789. /* true names of the vertices */
  16790. a = verts[ u ];
  16791. b = verts[ v ];
  16792. c = verts[ w ];
  16793. /* output Triangle */
  16794. result.push( [ contour[ a ],
  16795. contour[ b ],
  16796. contour[ c ] ] );
  16797. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16798. /* remove v from the remaining polygon */
  16799. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  16800. verts[ s ] = verts[ t ];
  16801. }
  16802. nv--;
  16803. /* reset error detection counter */
  16804. count = 2 * nv;
  16805. }
  16806. }
  16807. if ( indices ) return vertIndices;
  16808. return result;
  16809. };
  16810. // calculate area of the contour polygon
  16811. var area = function ( contour ) {
  16812. var n = contour.length;
  16813. var a = 0.0;
  16814. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16815. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16816. }
  16817. return a * 0.5;
  16818. };
  16819. var snip = function ( contour, u, v, w, n, verts ) {
  16820. var p;
  16821. var ax, ay, bx, by;
  16822. var cx, cy, px, py;
  16823. ax = contour[ verts[ u ] ].x;
  16824. ay = contour[ verts[ u ] ].y;
  16825. bx = contour[ verts[ v ] ].x;
  16826. by = contour[ verts[ v ] ].y;
  16827. cx = contour[ verts[ w ] ].x;
  16828. cy = contour[ verts[ w ] ].y;
  16829. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16830. var aX, aY, bX, bY, cX, cY;
  16831. var apx, apy, bpx, bpy, cpx, cpy;
  16832. var cCROSSap, bCROSScp, aCROSSbp;
  16833. aX = cx - bx; aY = cy - by;
  16834. bX = ax - cx; bY = ay - cy;
  16835. cX = bx - ax; cY = by - ay;
  16836. for ( p = 0; p < n; p++ ) {
  16837. if( (p === u) || (p === v) || (p === w) ) continue;
  16838. px = contour[ verts[ p ] ].x
  16839. py = contour[ verts[ p ] ].y
  16840. apx = px - ax; apy = py - ay;
  16841. bpx = px - bx; bpy = py - by;
  16842. cpx = px - cx; cpy = py - cy;
  16843. // see if p is inside triangle abc
  16844. aCROSSbp = aX*bpy - aY*bpx;
  16845. cCROSSap = cX*apy - cY*apx;
  16846. bCROSScp = bX*cpy - bY*cpx;
  16847. if ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) ) return false;
  16848. }
  16849. return true;
  16850. };
  16851. namespace.Triangulate = process;
  16852. namespace.Triangulate.area = area;
  16853. return namespace;
  16854. })(THREE.FontUtils);
  16855. // To use the typeface.js face files, hook up the API
  16856. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  16857. THREE.typeface_js = self._typeface_js;
  16858. /**
  16859. * @author zz85 / http://www.lab4games.net/zz85/blog
  16860. * Extensible curve object
  16861. *
  16862. * Some common of Curve methods
  16863. * .getPoint(t), getTangent(t)
  16864. * .getPointAt(u), getTagentAt(u)
  16865. * .getPoints(), .getSpacedPoints()
  16866. * .getLength()
  16867. * .updateArcLengths()
  16868. *
  16869. * This following classes subclasses THREE.Curve:
  16870. *
  16871. * -- 2d classes --
  16872. * THREE.LineCurve
  16873. * THREE.QuadraticBezierCurve
  16874. * THREE.CubicBezierCurve
  16875. * THREE.SplineCurve
  16876. * THREE.ArcCurve
  16877. * THREE.EllipseCurve
  16878. *
  16879. * -- 3d classes --
  16880. * THREE.LineCurve3
  16881. * THREE.QuadraticBezierCurve3
  16882. * THREE.CubicBezierCurve3
  16883. * THREE.SplineCurve3
  16884. * THREE.ClosedSplineCurve3
  16885. *
  16886. * A series of curves can be represented as a THREE.CurvePath
  16887. *
  16888. **/
  16889. /**************************************************************
  16890. * Abstract Curve base class
  16891. **************************************************************/
  16892. THREE.Curve = function () {
  16893. };
  16894. // Virtual base class method to overwrite and implement in subclasses
  16895. // - t [0 .. 1]
  16896. THREE.Curve.prototype.getPoint = function ( t ) {
  16897. console.log( "Warning, getPoint() not implemented!" );
  16898. return null;
  16899. };
  16900. // Get point at relative position in curve according to arc length
  16901. // - u [0 .. 1]
  16902. THREE.Curve.prototype.getPointAt = function ( u ) {
  16903. var t = this.getUtoTmapping( u );
  16904. return this.getPoint( t );
  16905. };
  16906. // Get sequence of points using getPoint( t )
  16907. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16908. if ( !divisions ) divisions = 5;
  16909. var d, pts = [];
  16910. for ( d = 0; d <= divisions; d ++ ) {
  16911. pts.push( this.getPoint( d / divisions ) );
  16912. }
  16913. return pts;
  16914. };
  16915. // Get sequence of points using getPointAt( u )
  16916. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16917. if ( !divisions ) divisions = 5;
  16918. var d, pts = [];
  16919. for ( d = 0; d <= divisions; d ++ ) {
  16920. pts.push( this.getPointAt( d / divisions ) );
  16921. }
  16922. return pts;
  16923. };
  16924. // Get total curve arc length
  16925. THREE.Curve.prototype.getLength = function () {
  16926. var lengths = this.getLengths();
  16927. return lengths[ lengths.length - 1 ];
  16928. };
  16929. // Get list of cumulative segment lengths
  16930. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16931. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16932. if ( this.cacheArcLengths
  16933. && ( this.cacheArcLengths.length == divisions + 1 )
  16934. && !this.needsUpdate) {
  16935. //console.log( "cached", this.cacheArcLengths );
  16936. return this.cacheArcLengths;
  16937. }
  16938. this.needsUpdate = false;
  16939. var cache = [];
  16940. var current, last = this.getPoint( 0 );
  16941. var p, sum = 0;
  16942. cache.push( 0 );
  16943. for ( p = 1; p <= divisions; p ++ ) {
  16944. current = this.getPoint ( p / divisions );
  16945. sum += current.distanceTo( last );
  16946. cache.push( sum );
  16947. last = current;
  16948. }
  16949. this.cacheArcLengths = cache;
  16950. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16951. };
  16952. THREE.Curve.prototype.updateArcLengths = function() {
  16953. this.needsUpdate = true;
  16954. this.getLengths();
  16955. };
  16956. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16957. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16958. var arcLengths = this.getLengths();
  16959. var i = 0, il = arcLengths.length;
  16960. var targetArcLength; // The targeted u distance value to get
  16961. if ( distance ) {
  16962. targetArcLength = distance;
  16963. } else {
  16964. targetArcLength = u * arcLengths[ il - 1 ];
  16965. }
  16966. //var time = Date.now();
  16967. // binary search for the index with largest value smaller than target u distance
  16968. var low = 0, high = il - 1, comparison;
  16969. while ( low <= high ) {
  16970. 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
  16971. comparison = arcLengths[ i ] - targetArcLength;
  16972. if ( comparison < 0 ) {
  16973. low = i + 1;
  16974. continue;
  16975. } else if ( comparison > 0 ) {
  16976. high = i - 1;
  16977. continue;
  16978. } else {
  16979. high = i;
  16980. break;
  16981. // DONE
  16982. }
  16983. }
  16984. i = high;
  16985. //console.log('b' , i, low, high, Date.now()- time);
  16986. if ( arcLengths[ i ] == targetArcLength ) {
  16987. var t = i / ( il - 1 );
  16988. return t;
  16989. }
  16990. // we could get finer grain at lengths, or use simple interpolatation between two points
  16991. var lengthBefore = arcLengths[ i ];
  16992. var lengthAfter = arcLengths[ i + 1 ];
  16993. var segmentLength = lengthAfter - lengthBefore;
  16994. // determine where we are between the 'before' and 'after' points
  16995. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16996. // add that fractional amount to t
  16997. var t = ( i + segmentFraction ) / ( il -1 );
  16998. return t;
  16999. };
  17000. // Returns a unit vector tangent at t
  17001. // In case any sub curve does not implement its tangent derivation,
  17002. // 2 points a small delta apart will be used to find its gradient
  17003. // which seems to give a reasonable approximation
  17004. THREE.Curve.prototype.getTangent = function( t ) {
  17005. var delta = 0.0001;
  17006. var t1 = t - delta;
  17007. var t2 = t + delta;
  17008. // Capping in case of danger
  17009. if ( t1 < 0 ) t1 = 0;
  17010. if ( t2 > 1 ) t2 = 1;
  17011. var pt1 = this.getPoint( t1 );
  17012. var pt2 = this.getPoint( t2 );
  17013. var vec = pt2.clone().sub(pt1);
  17014. return vec.normalize();
  17015. };
  17016. THREE.Curve.prototype.getTangentAt = function ( u ) {
  17017. var t = this.getUtoTmapping( u );
  17018. return this.getTangent( t );
  17019. };
  17020. /**************************************************************
  17021. * Utils
  17022. **************************************************************/
  17023. THREE.Curve.Utils = {
  17024. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  17025. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  17026. },
  17027. // Puay Bing, thanks for helping with this derivative!
  17028. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  17029. return -3 * p0 * (1 - t) * (1 - t) +
  17030. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  17031. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  17032. 3 * t * t * p3;
  17033. },
  17034. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  17035. // To check if my formulas are correct
  17036. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  17037. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  17038. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  17039. var h11 = 3 * t * t - 2 * t; // t3 − t2
  17040. return h00 + h10 + h01 + h11;
  17041. },
  17042. // Catmull-Rom
  17043. interpolate: function( p0, p1, p2, p3, t ) {
  17044. var v0 = ( p2 - p0 ) * 0.5;
  17045. var v1 = ( p3 - p1 ) * 0.5;
  17046. var t2 = t * t;
  17047. var t3 = t * t2;
  17048. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17049. }
  17050. };
  17051. // TODO: Transformation for Curves?
  17052. /**************************************************************
  17053. * 3D Curves
  17054. **************************************************************/
  17055. // A Factory method for creating new curve subclasses
  17056. THREE.Curve.create = function ( constructor, getPointFunc ) {
  17057. constructor.prototype = Object.create( THREE.Curve.prototype );
  17058. constructor.prototype.getPoint = getPointFunc;
  17059. return constructor;
  17060. };
  17061. /**
  17062. * @author zz85 / http://www.lab4games.net/zz85/blog
  17063. *
  17064. **/
  17065. /**************************************************************
  17066. * Curved Path - a curve path is simply a array of connected
  17067. * curves, but retains the api of a curve
  17068. **************************************************************/
  17069. THREE.CurvePath = function () {
  17070. this.curves = [];
  17071. this.bends = [];
  17072. this.autoClose = false; // Automatically closes the path
  17073. };
  17074. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  17075. THREE.CurvePath.prototype.add = function ( curve ) {
  17076. this.curves.push( curve );
  17077. };
  17078. THREE.CurvePath.prototype.checkConnection = function() {
  17079. // TODO
  17080. // If the ending of curve is not connected to the starting
  17081. // or the next curve, then, this is not a real path
  17082. };
  17083. THREE.CurvePath.prototype.closePath = function() {
  17084. // TODO Test
  17085. // and verify for vector3 (needs to implement equals)
  17086. // Add a line curve if start and end of lines are not connected
  17087. var startPoint = this.curves[0].getPoint(0);
  17088. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  17089. if (!startPoint.equals(endPoint)) {
  17090. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  17091. }
  17092. };
  17093. // To get accurate point with reference to
  17094. // entire path distance at time t,
  17095. // following has to be done:
  17096. // 1. Length of each sub path have to be known
  17097. // 2. Locate and identify type of curve
  17098. // 3. Get t for the curve
  17099. // 4. Return curve.getPointAt(t')
  17100. THREE.CurvePath.prototype.getPoint = function( t ) {
  17101. var d = t * this.getLength();
  17102. var curveLengths = this.getCurveLengths();
  17103. var i = 0, diff, curve;
  17104. // To think about boundaries points.
  17105. while ( i < curveLengths.length ) {
  17106. if ( curveLengths[ i ] >= d ) {
  17107. diff = curveLengths[ i ] - d;
  17108. curve = this.curves[ i ];
  17109. var u = 1 - diff / curve.getLength();
  17110. return curve.getPointAt( u );
  17111. break;
  17112. }
  17113. i ++;
  17114. }
  17115. return null;
  17116. // loop where sum != 0, sum > d , sum+1 <d
  17117. };
  17118. /*
  17119. THREE.CurvePath.prototype.getTangent = function( t ) {
  17120. };*/
  17121. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  17122. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  17123. // getPoint() depends on getLength
  17124. THREE.CurvePath.prototype.getLength = function() {
  17125. var lens = this.getCurveLengths();
  17126. return lens[ lens.length - 1 ];
  17127. };
  17128. // Compute lengths and cache them
  17129. // We cannot overwrite getLengths() because UtoT mapping uses it.
  17130. THREE.CurvePath.prototype.getCurveLengths = function() {
  17131. // We use cache values if curves and cache array are same length
  17132. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  17133. return this.cacheLengths;
  17134. };
  17135. // Get length of subsurve
  17136. // Push sums into cached array
  17137. var lengths = [], sums = 0;
  17138. var i, il = this.curves.length;
  17139. for ( i = 0; i < il; i ++ ) {
  17140. sums += this.curves[ i ].getLength();
  17141. lengths.push( sums );
  17142. }
  17143. this.cacheLengths = lengths;
  17144. return lengths;
  17145. };
  17146. // Returns min and max coordinates, as well as centroid
  17147. THREE.CurvePath.prototype.getBoundingBox = function () {
  17148. var points = this.getPoints();
  17149. var maxX, maxY, maxZ;
  17150. var minX, minY, minZ;
  17151. maxX = maxY = Number.NEGATIVE_INFINITY;
  17152. minX = minY = Number.POSITIVE_INFINITY;
  17153. var p, i, il, sum;
  17154. var v3 = points[0] instanceof THREE.Vector3;
  17155. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  17156. for ( i = 0, il = points.length; i < il; i ++ ) {
  17157. p = points[ i ];
  17158. if ( p.x > maxX ) maxX = p.x;
  17159. else if ( p.x < minX ) minX = p.x;
  17160. if ( p.y > maxY ) maxY = p.y;
  17161. else if ( p.y < minY ) minY = p.y;
  17162. if ( v3 ) {
  17163. if ( p.z > maxZ ) maxZ = p.z;
  17164. else if ( p.z < minZ ) minZ = p.z;
  17165. }
  17166. sum.add( p );
  17167. }
  17168. var ret = {
  17169. minX: minX,
  17170. minY: minY,
  17171. maxX: maxX,
  17172. maxY: maxY,
  17173. centroid: sum.divideScalar( il )
  17174. };
  17175. if ( v3 ) {
  17176. ret.maxZ = maxZ;
  17177. ret.minZ = minZ;
  17178. }
  17179. return ret;
  17180. };
  17181. /**************************************************************
  17182. * Create Geometries Helpers
  17183. **************************************************************/
  17184. /// Generate geometry from path points (for Line or ParticleSystem objects)
  17185. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  17186. var pts = this.getPoints( divisions, true );
  17187. return this.createGeometry( pts );
  17188. };
  17189. // Generate geometry from equidistance sampling along the path
  17190. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  17191. var pts = this.getSpacedPoints( divisions, true );
  17192. return this.createGeometry( pts );
  17193. };
  17194. THREE.CurvePath.prototype.createGeometry = function( points ) {
  17195. var geometry = new THREE.Geometry();
  17196. for ( var i = 0; i < points.length; i ++ ) {
  17197. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  17198. }
  17199. return geometry;
  17200. };
  17201. /**************************************************************
  17202. * Bend / Wrap Helper Methods
  17203. **************************************************************/
  17204. // Wrap path / Bend modifiers?
  17205. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  17206. this.bends.push( bendpath );
  17207. };
  17208. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  17209. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  17210. var i, il;
  17211. if ( !bends ) {
  17212. bends = this.bends;
  17213. }
  17214. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17215. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17216. }
  17217. return oldPts;
  17218. };
  17219. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  17220. var oldPts = this.getSpacedPoints( segments );
  17221. var i, il;
  17222. if ( !bends ) {
  17223. bends = this.bends;
  17224. }
  17225. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17226. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17227. }
  17228. return oldPts;
  17229. };
  17230. // This returns getPoints() bend/wrapped around the contour of a path.
  17231. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  17232. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  17233. var bounds = this.getBoundingBox();
  17234. var i, il, p, oldX, oldY, xNorm;
  17235. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  17236. p = oldPts[ i ];
  17237. oldX = p.x;
  17238. oldY = p.y;
  17239. xNorm = oldX / bounds.maxX;
  17240. // If using actual distance, for length > path, requires line extrusions
  17241. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  17242. xNorm = path.getUtoTmapping( xNorm, oldX );
  17243. // check for out of bounds?
  17244. var pathPt = path.getPoint( xNorm );
  17245. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  17246. p.x = pathPt.x + normal.x;
  17247. p.y = pathPt.y + normal.y;
  17248. }
  17249. return oldPts;
  17250. };
  17251. /**
  17252. * @author alteredq / http://alteredqualia.com/
  17253. */
  17254. THREE.Gyroscope = function () {
  17255. THREE.Object3D.call( this );
  17256. };
  17257. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  17258. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  17259. this.matrixAutoUpdate && this.updateMatrix();
  17260. // update matrixWorld
  17261. if ( this.matrixWorldNeedsUpdate || force ) {
  17262. if ( this.parent ) {
  17263. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  17264. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  17265. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  17266. this.matrixWorld.makeFromPositionQuaternionScale( this.translationWorld, this.rotationObject, this.scaleWorld );
  17267. } else {
  17268. this.matrixWorld.copy( this.matrix );
  17269. }
  17270. this.matrixWorldNeedsUpdate = false;
  17271. force = true;
  17272. }
  17273. // update children
  17274. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  17275. this.children[ i ].updateMatrixWorld( force );
  17276. }
  17277. };
  17278. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  17279. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  17280. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  17281. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  17282. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  17283. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  17284. /**
  17285. * @author zz85 / http://www.lab4games.net/zz85/blog
  17286. * Creates free form 2d path using series of points, lines or curves.
  17287. *
  17288. **/
  17289. THREE.Path = function ( points ) {
  17290. THREE.CurvePath.call(this);
  17291. this.actions = [];
  17292. if ( points ) {
  17293. this.fromPoints( points );
  17294. }
  17295. };
  17296. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  17297. THREE.PathActions = {
  17298. MOVE_TO: 'moveTo',
  17299. LINE_TO: 'lineTo',
  17300. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  17301. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  17302. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  17303. ARC: 'arc', // Circle
  17304. ELLIPSE: 'ellipse'
  17305. };
  17306. // TODO Clean up PATH API
  17307. // Create path using straight lines to connect all points
  17308. // - vectors: array of Vector2
  17309. THREE.Path.prototype.fromPoints = function ( vectors ) {
  17310. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  17311. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  17312. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  17313. };
  17314. };
  17315. // startPath() endPath()?
  17316. THREE.Path.prototype.moveTo = function ( x, y ) {
  17317. var args = Array.prototype.slice.call( arguments );
  17318. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  17319. };
  17320. THREE.Path.prototype.lineTo = function ( x, y ) {
  17321. var args = Array.prototype.slice.call( arguments );
  17322. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17323. var x0 = lastargs[ lastargs.length - 2 ];
  17324. var y0 = lastargs[ lastargs.length - 1 ];
  17325. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  17326. this.curves.push( curve );
  17327. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  17328. };
  17329. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  17330. var args = Array.prototype.slice.call( arguments );
  17331. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17332. var x0 = lastargs[ lastargs.length - 2 ];
  17333. var y0 = lastargs[ lastargs.length - 1 ];
  17334. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  17335. new THREE.Vector2( aCPx, aCPy ),
  17336. new THREE.Vector2( aX, aY ) );
  17337. this.curves.push( curve );
  17338. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  17339. };
  17340. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  17341. aCP2x, aCP2y,
  17342. aX, aY ) {
  17343. var args = Array.prototype.slice.call( arguments );
  17344. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17345. var x0 = lastargs[ lastargs.length - 2 ];
  17346. var y0 = lastargs[ lastargs.length - 1 ];
  17347. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  17348. new THREE.Vector2( aCP1x, aCP1y ),
  17349. new THREE.Vector2( aCP2x, aCP2y ),
  17350. new THREE.Vector2( aX, aY ) );
  17351. this.curves.push( curve );
  17352. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  17353. };
  17354. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  17355. var args = Array.prototype.slice.call( arguments );
  17356. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17357. var x0 = lastargs[ lastargs.length - 2 ];
  17358. var y0 = lastargs[ lastargs.length - 1 ];
  17359. //---
  17360. var npts = [ new THREE.Vector2( x0, y0 ) ];
  17361. Array.prototype.push.apply( npts, pts );
  17362. var curve = new THREE.SplineCurve( npts );
  17363. this.curves.push( curve );
  17364. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  17365. };
  17366. // FUTURE: Change the API or follow canvas API?
  17367. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  17368. aStartAngle, aEndAngle, aClockwise ) {
  17369. var lastargs = this.actions[ this.actions.length - 1].args;
  17370. var x0 = lastargs[ lastargs.length - 2 ];
  17371. var y0 = lastargs[ lastargs.length - 1 ];
  17372. this.absarc(aX + x0, aY + y0, aRadius,
  17373. aStartAngle, aEndAngle, aClockwise );
  17374. };
  17375. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  17376. aStartAngle, aEndAngle, aClockwise ) {
  17377. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  17378. };
  17379. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  17380. aStartAngle, aEndAngle, aClockwise ) {
  17381. var lastargs = this.actions[ this.actions.length - 1].args;
  17382. var x0 = lastargs[ lastargs.length - 2 ];
  17383. var y0 = lastargs[ lastargs.length - 1 ];
  17384. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  17385. aStartAngle, aEndAngle, aClockwise );
  17386. };
  17387. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  17388. aStartAngle, aEndAngle, aClockwise ) {
  17389. var args = Array.prototype.slice.call( arguments );
  17390. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  17391. aStartAngle, aEndAngle, aClockwise );
  17392. this.curves.push( curve );
  17393. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  17394. args.push(lastPoint.x);
  17395. args.push(lastPoint.y);
  17396. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  17397. };
  17398. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  17399. if ( ! divisions ) divisions = 40;
  17400. var points = [];
  17401. for ( var i = 0; i < divisions; i ++ ) {
  17402. points.push( this.getPoint( i / divisions ) );
  17403. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  17404. }
  17405. // if ( closedPath ) {
  17406. //
  17407. // points.push( points[ 0 ] );
  17408. //
  17409. // }
  17410. return points;
  17411. };
  17412. /* Return an array of vectors based on contour of the path */
  17413. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  17414. if (this.useSpacedPoints) {
  17415. console.log('tata');
  17416. return this.getSpacedPoints( divisions, closedPath );
  17417. }
  17418. divisions = divisions || 12;
  17419. var points = [];
  17420. var i, il, item, action, args;
  17421. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  17422. laste, j,
  17423. t, tx, ty;
  17424. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17425. item = this.actions[ i ];
  17426. action = item.action;
  17427. args = item.args;
  17428. switch( action ) {
  17429. case THREE.PathActions.MOVE_TO:
  17430. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17431. break;
  17432. case THREE.PathActions.LINE_TO:
  17433. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17434. break;
  17435. case THREE.PathActions.QUADRATIC_CURVE_TO:
  17436. cpx = args[ 2 ];
  17437. cpy = args[ 3 ];
  17438. cpx1 = args[ 0 ];
  17439. cpy1 = args[ 1 ];
  17440. if ( points.length > 0 ) {
  17441. laste = points[ points.length - 1 ];
  17442. cpx0 = laste.x;
  17443. cpy0 = laste.y;
  17444. } else {
  17445. laste = this.actions[ i - 1 ].args;
  17446. cpx0 = laste[ laste.length - 2 ];
  17447. cpy0 = laste[ laste.length - 1 ];
  17448. }
  17449. for ( j = 1; j <= divisions; j ++ ) {
  17450. t = j / divisions;
  17451. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17452. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17453. points.push( new THREE.Vector2( tx, ty ) );
  17454. }
  17455. break;
  17456. case THREE.PathActions.BEZIER_CURVE_TO:
  17457. cpx = args[ 4 ];
  17458. cpy = args[ 5 ];
  17459. cpx1 = args[ 0 ];
  17460. cpy1 = args[ 1 ];
  17461. cpx2 = args[ 2 ];
  17462. cpy2 = args[ 3 ];
  17463. if ( points.length > 0 ) {
  17464. laste = points[ points.length - 1 ];
  17465. cpx0 = laste.x;
  17466. cpy0 = laste.y;
  17467. } else {
  17468. laste = this.actions[ i - 1 ].args;
  17469. cpx0 = laste[ laste.length - 2 ];
  17470. cpy0 = laste[ laste.length - 1 ];
  17471. }
  17472. for ( j = 1; j <= divisions; j ++ ) {
  17473. t = j / divisions;
  17474. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17475. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17476. points.push( new THREE.Vector2( tx, ty ) );
  17477. }
  17478. break;
  17479. case THREE.PathActions.CSPLINE_THRU:
  17480. laste = this.actions[ i - 1 ].args;
  17481. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17482. var spts = [ last ];
  17483. var n = divisions * args[ 0 ].length;
  17484. spts = spts.concat( args[ 0 ] );
  17485. var spline = new THREE.SplineCurve( spts );
  17486. for ( j = 1; j <= n; j ++ ) {
  17487. points.push( spline.getPointAt( j / n ) ) ;
  17488. }
  17489. break;
  17490. case THREE.PathActions.ARC:
  17491. var aX = args[ 0 ], aY = args[ 1 ],
  17492. aRadius = args[ 2 ],
  17493. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17494. aClockwise = !!args[ 5 ];
  17495. var deltaAngle = aEndAngle - aStartAngle;
  17496. var angle;
  17497. var tdivisions = divisions * 2;
  17498. for ( j = 1; j <= tdivisions; j ++ ) {
  17499. t = j / tdivisions;
  17500. if ( ! aClockwise ) {
  17501. t = 1 - t;
  17502. }
  17503. angle = aStartAngle + t * deltaAngle;
  17504. tx = aX + aRadius * Math.cos( angle );
  17505. ty = aY + aRadius * Math.sin( angle );
  17506. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17507. points.push( new THREE.Vector2( tx, ty ) );
  17508. }
  17509. //console.log(points);
  17510. break;
  17511. case THREE.PathActions.ELLIPSE:
  17512. var aX = args[ 0 ], aY = args[ 1 ],
  17513. xRadius = args[ 2 ],
  17514. yRadius = args[ 3 ],
  17515. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17516. aClockwise = !!args[ 6 ];
  17517. var deltaAngle = aEndAngle - aStartAngle;
  17518. var angle;
  17519. var tdivisions = divisions * 2;
  17520. for ( j = 1; j <= tdivisions; j ++ ) {
  17521. t = j / tdivisions;
  17522. if ( ! aClockwise ) {
  17523. t = 1 - t;
  17524. }
  17525. angle = aStartAngle + t * deltaAngle;
  17526. tx = aX + xRadius * Math.cos( angle );
  17527. ty = aY + yRadius * Math.sin( angle );
  17528. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17529. points.push( new THREE.Vector2( tx, ty ) );
  17530. }
  17531. //console.log(points);
  17532. break;
  17533. } // end switch
  17534. }
  17535. // Normalize to remove the closing point by default.
  17536. var lastPoint = points[ points.length - 1];
  17537. var EPSILON = 0.0000000001;
  17538. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17539. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17540. points.splice( points.length - 1, 1);
  17541. if ( closedPath ) {
  17542. points.push( points[ 0 ] );
  17543. }
  17544. return points;
  17545. };
  17546. // Breaks path into shapes
  17547. THREE.Path.prototype.toShapes = function( isCCW ) {
  17548. var i, il, item, action, args;
  17549. var subPaths = [], lastPath = new THREE.Path();
  17550. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17551. item = this.actions[ i ];
  17552. args = item.args;
  17553. action = item.action;
  17554. if ( action == THREE.PathActions.MOVE_TO ) {
  17555. if ( lastPath.actions.length != 0 ) {
  17556. subPaths.push( lastPath );
  17557. lastPath = new THREE.Path();
  17558. }
  17559. }
  17560. lastPath[ action ].apply( lastPath, args );
  17561. }
  17562. if ( lastPath.actions.length != 0 ) {
  17563. subPaths.push( lastPath );
  17564. }
  17565. // console.log(subPaths);
  17566. if ( subPaths.length == 0 ) return [];
  17567. var solid, tmpPath, tmpShape, shapes = [];
  17568. if ( subPaths.length == 1) {
  17569. tmpPath = subPaths[0];
  17570. tmpShape = new THREE.Shape();
  17571. tmpShape.actions = tmpPath.actions;
  17572. tmpShape.curves = tmpPath.curves;
  17573. shapes.push( tmpShape );
  17574. return shapes;
  17575. }
  17576. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17577. holesFirst = isCCW ? !holesFirst : holesFirst;
  17578. // console.log("Holes first", holesFirst);
  17579. if ( holesFirst ) {
  17580. tmpShape = new THREE.Shape();
  17581. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17582. tmpPath = subPaths[ i ];
  17583. solid = THREE.Shape.Utils.isClockWise( tmpPath.getPoints() );
  17584. solid = isCCW ? !solid : solid;
  17585. if ( solid ) {
  17586. tmpShape.actions = tmpPath.actions;
  17587. tmpShape.curves = tmpPath.curves;
  17588. shapes.push( tmpShape );
  17589. tmpShape = new THREE.Shape();
  17590. //console.log('cw', i);
  17591. } else {
  17592. tmpShape.holes.push( tmpPath );
  17593. //console.log('ccw', i);
  17594. }
  17595. }
  17596. } else {
  17597. // Shapes first
  17598. tmpShape = undefined;
  17599. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17600. tmpPath = subPaths[ i ];
  17601. solid = THREE.Shape.Utils.isClockWise( tmpPath.getPoints() );
  17602. solid = isCCW ? !solid : solid;
  17603. if ( solid ) {
  17604. if ( tmpShape ) shapes.push( tmpShape );
  17605. tmpShape = new THREE.Shape();
  17606. tmpShape.actions = tmpPath.actions;
  17607. tmpShape.curves = tmpPath.curves;
  17608. } else {
  17609. tmpShape.holes.push( tmpPath );
  17610. }
  17611. }
  17612. shapes.push( tmpShape );
  17613. }
  17614. //console.log("shape", shapes);
  17615. return shapes;
  17616. };
  17617. /**
  17618. * @author zz85 / http://www.lab4games.net/zz85/blog
  17619. * Defines a 2d shape plane using paths.
  17620. **/
  17621. // STEP 1 Create a path.
  17622. // STEP 2 Turn path into shape.
  17623. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17624. // STEP 3a - Extract points from each shape, turn to vertices
  17625. // STEP 3b - Triangulate each shape, add faces.
  17626. THREE.Shape = function () {
  17627. THREE.Path.apply( this, arguments );
  17628. this.holes = [];
  17629. };
  17630. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17631. // Convenience method to return ExtrudeGeometry
  17632. THREE.Shape.prototype.extrude = function ( options ) {
  17633. var extruded = new THREE.ExtrudeGeometry( this, options );
  17634. return extruded;
  17635. };
  17636. // Convenience method to return ShapeGeometry
  17637. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17638. var geometry = new THREE.ShapeGeometry( this, options );
  17639. return geometry;
  17640. };
  17641. // Get points of holes
  17642. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17643. var i, il = this.holes.length, holesPts = [];
  17644. for ( i = 0; i < il; i ++ ) {
  17645. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17646. }
  17647. return holesPts;
  17648. };
  17649. // Get points of holes (spaced by regular distance)
  17650. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17651. var i, il = this.holes.length, holesPts = [];
  17652. for ( i = 0; i < il; i ++ ) {
  17653. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17654. }
  17655. return holesPts;
  17656. };
  17657. // Get points of shape and holes (keypoints based on segments parameter)
  17658. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17659. return {
  17660. shape: this.getTransformedPoints( divisions ),
  17661. holes: this.getPointsHoles( divisions )
  17662. };
  17663. };
  17664. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17665. if (this.useSpacedPoints) {
  17666. return this.extractAllSpacedPoints(divisions);
  17667. }
  17668. return this.extractAllPoints(divisions);
  17669. };
  17670. //
  17671. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17672. //
  17673. // return {
  17674. //
  17675. // shape: this.transform( bend, divisions ),
  17676. // holes: this.getPointsHoles( divisions, bend )
  17677. //
  17678. // };
  17679. //
  17680. // };
  17681. // Get points of shape and holes (spaced by regular distance)
  17682. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17683. return {
  17684. shape: this.getTransformedSpacedPoints( divisions ),
  17685. holes: this.getSpacedPointsHoles( divisions )
  17686. };
  17687. };
  17688. /**************************************************************
  17689. * Utils
  17690. **************************************************************/
  17691. THREE.Shape.Utils = {
  17692. /*
  17693. contour - array of vector2 for contour
  17694. holes - array of array of vector2
  17695. */
  17696. removeHoles: function ( contour, holes ) {
  17697. var shape = contour.concat(); // work on this shape
  17698. var allpoints = shape.concat();
  17699. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  17700. var prevShapeVert, nextShapeVert,
  17701. prevHoleVert, nextHoleVert,
  17702. holeIndex, shapeIndex,
  17703. shapeId, shapeGroup,
  17704. h, h2,
  17705. hole, shortest, d,
  17706. p, pts1, pts2,
  17707. tmpShape1, tmpShape2,
  17708. tmpHole1, tmpHole2,
  17709. verts = [];
  17710. for ( h = 0; h < holes.length; h ++ ) {
  17711. hole = holes[ h ];
  17712. /*
  17713. shapeholes[ h ].concat(); // preserves original
  17714. holes.push( hole );
  17715. */
  17716. Array.prototype.push.apply( allpoints, hole );
  17717. shortest = Number.POSITIVE_INFINITY;
  17718. // Find the shortest pair of pts between shape and hole
  17719. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  17720. // Using distanceToSquared() intead of distanceTo() should speed a little
  17721. // since running square roots operations are reduced.
  17722. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  17723. pts1 = hole[ h2 ];
  17724. var dist = [];
  17725. for ( p = 0; p < shape.length; p++ ) {
  17726. pts2 = shape[ p ];
  17727. d = pts1.distanceToSquared( pts2 );
  17728. dist.push( d );
  17729. if ( d < shortest ) {
  17730. shortest = d;
  17731. holeIndex = h2;
  17732. shapeIndex = p;
  17733. }
  17734. }
  17735. }
  17736. //console.log("shortest", shortest, dist);
  17737. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17738. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17739. var areaapts = [
  17740. hole[ holeIndex ],
  17741. shape[ shapeIndex ],
  17742. shape[ prevShapeVert ]
  17743. ];
  17744. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  17745. var areabpts = [
  17746. hole[ holeIndex ],
  17747. hole[ prevHoleVert ],
  17748. shape[ shapeIndex ]
  17749. ];
  17750. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  17751. var shapeOffset = 1;
  17752. var holeOffset = -1;
  17753. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  17754. shapeIndex += shapeOffset;
  17755. holeIndex += holeOffset;
  17756. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17757. shapeIndex %= shape.length;
  17758. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17759. holeIndex %= hole.length;
  17760. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17761. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17762. areaapts = [
  17763. hole[ holeIndex ],
  17764. shape[ shapeIndex ],
  17765. shape[ prevShapeVert ]
  17766. ];
  17767. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  17768. areabpts = [
  17769. hole[ holeIndex ],
  17770. hole[ prevHoleVert ],
  17771. shape[ shapeIndex ]
  17772. ];
  17773. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  17774. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  17775. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  17776. // In case areas are not correct.
  17777. //console.log("USE THIS");
  17778. shapeIndex = oldShapeIndex;
  17779. holeIndex = oldHoleIndex ;
  17780. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17781. shapeIndex %= shape.length;
  17782. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17783. holeIndex %= hole.length;
  17784. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17785. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17786. } else {
  17787. //console.log("USE THAT ")
  17788. }
  17789. tmpShape1 = shape.slice( 0, shapeIndex );
  17790. tmpShape2 = shape.slice( shapeIndex );
  17791. tmpHole1 = hole.slice( holeIndex );
  17792. tmpHole2 = hole.slice( 0, holeIndex );
  17793. // Should check orders here again?
  17794. var trianglea = [
  17795. hole[ holeIndex ],
  17796. shape[ shapeIndex ],
  17797. shape[ prevShapeVert ]
  17798. ];
  17799. var triangleb = [
  17800. hole[ holeIndex ] ,
  17801. hole[ prevHoleVert ],
  17802. shape[ shapeIndex ]
  17803. ];
  17804. verts.push( trianglea );
  17805. verts.push( triangleb );
  17806. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17807. }
  17808. return {
  17809. shape:shape, /* shape with no holes */
  17810. isolatedPts: verts, /* isolated faces */
  17811. allpoints: allpoints
  17812. }
  17813. },
  17814. triangulateShape: function ( contour, holes ) {
  17815. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  17816. var shape = shapeWithoutHoles.shape,
  17817. allpoints = shapeWithoutHoles.allpoints,
  17818. isolatedPts = shapeWithoutHoles.isolatedPts;
  17819. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  17820. // 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.
  17821. //console.log( "triangles",triangles, triangles.length );
  17822. //console.log( "allpoints",allpoints, allpoints.length );
  17823. var i, il, f, face,
  17824. key, index,
  17825. allPointsMap = {},
  17826. isolatedPointsMap = {};
  17827. // prepare all points map
  17828. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17829. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17830. if ( allPointsMap[ key ] !== undefined ) {
  17831. console.log( "Duplicate point", key );
  17832. }
  17833. allPointsMap[ key ] = i;
  17834. }
  17835. // check all face vertices against all points map
  17836. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17837. face = triangles[ i ];
  17838. for ( f = 0; f < 3; f ++ ) {
  17839. key = face[ f ].x + ":" + face[ f ].y;
  17840. index = allPointsMap[ key ];
  17841. if ( index !== undefined ) {
  17842. face[ f ] = index;
  17843. }
  17844. }
  17845. }
  17846. // check isolated points vertices against all points map
  17847. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  17848. face = isolatedPts[ i ];
  17849. for ( f = 0; f < 3; f ++ ) {
  17850. key = face[ f ].x + ":" + face[ f ].y;
  17851. index = allPointsMap[ key ];
  17852. if ( index !== undefined ) {
  17853. face[ f ] = index;
  17854. }
  17855. }
  17856. }
  17857. return triangles.concat( isolatedPts );
  17858. }, // end triangulate shapes
  17859. /*
  17860. triangulate2 : function( pts, holes ) {
  17861. // For use with Poly2Tri.js
  17862. var allpts = pts.concat();
  17863. var shape = [];
  17864. for (var p in pts) {
  17865. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  17866. }
  17867. var swctx = new js.poly2tri.SweepContext(shape);
  17868. for (var h in holes) {
  17869. var aHole = holes[h];
  17870. var newHole = []
  17871. for (i in aHole) {
  17872. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  17873. allpts.push(aHole[i]);
  17874. }
  17875. swctx.AddHole(newHole);
  17876. }
  17877. var find;
  17878. var findIndexForPt = function (pt) {
  17879. find = new THREE.Vector2(pt.x, pt.y);
  17880. var p;
  17881. for (p=0, pl = allpts.length; p<pl; p++) {
  17882. if (allpts[p].equals(find)) return p;
  17883. }
  17884. return -1;
  17885. };
  17886. // triangulate
  17887. js.poly2tri.sweep.Triangulate(swctx);
  17888. var triangles = swctx.GetTriangles();
  17889. var tr ;
  17890. var facesPts = [];
  17891. for (var t in triangles) {
  17892. tr = triangles[t];
  17893. facesPts.push([
  17894. findIndexForPt(tr.GetPoint(0)),
  17895. findIndexForPt(tr.GetPoint(1)),
  17896. findIndexForPt(tr.GetPoint(2))
  17897. ]);
  17898. }
  17899. // console.log(facesPts);
  17900. // console.log("triangles", triangles.length, triangles);
  17901. // Returns array of faces with 3 element each
  17902. return facesPts;
  17903. },
  17904. */
  17905. isClockWise: function ( pts ) {
  17906. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17907. },
  17908. // Bezier Curves formulas obtained from
  17909. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17910. // Quad Bezier Functions
  17911. b2p0: function ( t, p ) {
  17912. var k = 1 - t;
  17913. return k * k * p;
  17914. },
  17915. b2p1: function ( t, p ) {
  17916. return 2 * ( 1 - t ) * t * p;
  17917. },
  17918. b2p2: function ( t, p ) {
  17919. return t * t * p;
  17920. },
  17921. b2: function ( t, p0, p1, p2 ) {
  17922. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17923. },
  17924. // Cubic Bezier Functions
  17925. b3p0: function ( t, p ) {
  17926. var k = 1 - t;
  17927. return k * k * k * p;
  17928. },
  17929. b3p1: function ( t, p ) {
  17930. var k = 1 - t;
  17931. return 3 * k * k * t * p;
  17932. },
  17933. b3p2: function ( t, p ) {
  17934. var k = 1 - t;
  17935. return 3 * k * t * t * p;
  17936. },
  17937. b3p3: function ( t, p ) {
  17938. return t * t * t * p;
  17939. },
  17940. b3: function ( t, p0, p1, p2, p3 ) {
  17941. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17942. }
  17943. };
  17944. /**************************************************************
  17945. * Line
  17946. **************************************************************/
  17947. THREE.LineCurve = function ( v1, v2 ) {
  17948. this.v1 = v1;
  17949. this.v2 = v2;
  17950. };
  17951. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  17952. THREE.LineCurve.prototype.getPoint = function ( t ) {
  17953. var point = this.v2.clone().sub(this.v1);
  17954. point.multiplyScalar( t ).add( this.v1 );
  17955. return point;
  17956. };
  17957. // Line curve is linear, so we can overwrite default getPointAt
  17958. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  17959. return this.getPoint( u );
  17960. };
  17961. THREE.LineCurve.prototype.getTangent = function( t ) {
  17962. var tangent = this.v2.clone().sub(this.v1);
  17963. return tangent.normalize();
  17964. };
  17965. /**************************************************************
  17966. * Quadratic Bezier curve
  17967. **************************************************************/
  17968. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  17969. this.v0 = v0;
  17970. this.v1 = v1;
  17971. this.v2 = v2;
  17972. };
  17973. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17974. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  17975. var tx, ty;
  17976. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17977. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17978. return new THREE.Vector2( tx, ty );
  17979. };
  17980. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  17981. var tx, ty;
  17982. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  17983. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  17984. // returns unit vector
  17985. var tangent = new THREE.Vector2( tx, ty );
  17986. tangent.normalize();
  17987. return tangent;
  17988. };
  17989. /**************************************************************
  17990. * Cubic Bezier curve
  17991. **************************************************************/
  17992. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  17993. this.v0 = v0;
  17994. this.v1 = v1;
  17995. this.v2 = v2;
  17996. this.v3 = v3;
  17997. };
  17998. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17999. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  18000. var tx, ty;
  18001. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  18002. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  18003. return new THREE.Vector2( tx, ty );
  18004. };
  18005. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  18006. var tx, ty;
  18007. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  18008. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  18009. var tangent = new THREE.Vector2( tx, ty );
  18010. tangent.normalize();
  18011. return tangent;
  18012. };
  18013. /**************************************************************
  18014. * Spline curve
  18015. **************************************************************/
  18016. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  18017. this.points = (points == undefined) ? [] : points;
  18018. };
  18019. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  18020. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  18021. var v = new THREE.Vector2();
  18022. var c = [];
  18023. var points = this.points, point, intPoint, weight;
  18024. point = ( points.length - 1 ) * t;
  18025. intPoint = Math.floor( point );
  18026. weight = point - intPoint;
  18027. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18028. c[ 1 ] = intPoint;
  18029. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  18030. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  18031. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  18032. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  18033. return v;
  18034. };
  18035. /**************************************************************
  18036. * Ellipse curve
  18037. **************************************************************/
  18038. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  18039. aStartAngle, aEndAngle,
  18040. aClockwise ) {
  18041. this.aX = aX;
  18042. this.aY = aY;
  18043. this.xRadius = xRadius;
  18044. this.yRadius = yRadius;
  18045. this.aStartAngle = aStartAngle;
  18046. this.aEndAngle = aEndAngle;
  18047. this.aClockwise = aClockwise;
  18048. };
  18049. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  18050. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  18051. var deltaAngle = this.aEndAngle - this.aStartAngle;
  18052. if ( !this.aClockwise ) {
  18053. t = 1 - t;
  18054. }
  18055. var angle = this.aStartAngle + t * deltaAngle;
  18056. var tx = this.aX + this.xRadius * Math.cos( angle );
  18057. var ty = this.aY + this.yRadius * Math.sin( angle );
  18058. return new THREE.Vector2( tx, ty );
  18059. };
  18060. /**************************************************************
  18061. * Arc curve
  18062. **************************************************************/
  18063. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  18064. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  18065. };
  18066. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  18067. /**************************************************************
  18068. * Line3D
  18069. **************************************************************/
  18070. THREE.LineCurve3 = THREE.Curve.create(
  18071. function ( v1, v2 ) {
  18072. this.v1 = v1;
  18073. this.v2 = v2;
  18074. },
  18075. function ( t ) {
  18076. var r = new THREE.Vector3();
  18077. r.subVectors( this.v2, this.v1 ); // diff
  18078. r.multiplyScalar( t );
  18079. r.add( this.v1 );
  18080. return r;
  18081. }
  18082. );
  18083. /**************************************************************
  18084. * Quadratic Bezier 3D curve
  18085. **************************************************************/
  18086. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  18087. function ( v0, v1, v2 ) {
  18088. this.v0 = v0;
  18089. this.v1 = v1;
  18090. this.v2 = v2;
  18091. },
  18092. function ( t ) {
  18093. var tx, ty, tz;
  18094. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  18095. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  18096. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  18097. return new THREE.Vector3( tx, ty, tz );
  18098. }
  18099. );
  18100. /**************************************************************
  18101. * Cubic Bezier 3D curve
  18102. **************************************************************/
  18103. THREE.CubicBezierCurve3 = THREE.Curve.create(
  18104. function ( v0, v1, v2, v3 ) {
  18105. this.v0 = v0;
  18106. this.v1 = v1;
  18107. this.v2 = v2;
  18108. this.v3 = v3;
  18109. },
  18110. function ( t ) {
  18111. var tx, ty, tz;
  18112. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  18113. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  18114. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  18115. return new THREE.Vector3( tx, ty, tz );
  18116. }
  18117. );
  18118. /**************************************************************
  18119. * Spline 3D curve
  18120. **************************************************************/
  18121. THREE.SplineCurve3 = THREE.Curve.create(
  18122. function ( points /* array of Vector3 */) {
  18123. this.points = (points == undefined) ? [] : points;
  18124. },
  18125. function ( t ) {
  18126. var v = new THREE.Vector3();
  18127. var c = [];
  18128. var points = this.points, point, intPoint, weight;
  18129. point = ( points.length - 1 ) * t;
  18130. intPoint = Math.floor( point );
  18131. weight = point - intPoint;
  18132. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18133. c[ 1 ] = intPoint;
  18134. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  18135. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  18136. var pt0 = points[ c[0] ],
  18137. pt1 = points[ c[1] ],
  18138. pt2 = points[ c[2] ],
  18139. pt3 = points[ c[3] ];
  18140. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  18141. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  18142. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  18143. return v;
  18144. }
  18145. );
  18146. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  18147. // var v = new THREE.Vector3();
  18148. // var c = [];
  18149. // var points = this.points, point, intPoint, weight;
  18150. // point = ( points.length - 1 ) * t;
  18151. // intPoint = Math.floor( point );
  18152. // weight = point - intPoint;
  18153. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18154. // c[ 1 ] = intPoint;
  18155. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  18156. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  18157. // var pt0 = points[ c[0] ],
  18158. // pt1 = points[ c[1] ],
  18159. // pt2 = points[ c[2] ],
  18160. // pt3 = points[ c[3] ];
  18161. // // t = weight;
  18162. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  18163. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  18164. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  18165. // return v;
  18166. // }
  18167. /**************************************************************
  18168. * Closed Spline 3D curve
  18169. **************************************************************/
  18170. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  18171. function ( points /* array of Vector3 */) {
  18172. this.points = (points == undefined) ? [] : points;
  18173. },
  18174. function ( t ) {
  18175. var v = new THREE.Vector3();
  18176. var c = [];
  18177. var points = this.points, point, intPoint, weight;
  18178. point = ( points.length - 0 ) * t;
  18179. // This needs to be from 0-length +1
  18180. intPoint = Math.floor( point );
  18181. weight = point - intPoint;
  18182. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  18183. c[ 0 ] = ( intPoint - 1 ) % points.length;
  18184. c[ 1 ] = ( intPoint ) % points.length;
  18185. c[ 2 ] = ( intPoint + 1 ) % points.length;
  18186. c[ 3 ] = ( intPoint + 2 ) % points.length;
  18187. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  18188. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  18189. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  18190. return v;
  18191. }
  18192. );
  18193. /**
  18194. * @author mikael emtinger / http://gomo.se/
  18195. */
  18196. THREE.AnimationHandler = (function() {
  18197. var playing = [];
  18198. var library = {};
  18199. var that = {};
  18200. //--- update ---
  18201. that.update = function( deltaTimeMS ) {
  18202. for( var i = 0; i < playing.length; i ++ )
  18203. playing[ i ].update( deltaTimeMS );
  18204. };
  18205. //--- add ---
  18206. that.addToUpdate = function( animation ) {
  18207. if ( playing.indexOf( animation ) === -1 )
  18208. playing.push( animation );
  18209. };
  18210. //--- remove ---
  18211. that.removeFromUpdate = function( animation ) {
  18212. var index = playing.indexOf( animation );
  18213. if( index !== -1 )
  18214. playing.splice( index, 1 );
  18215. };
  18216. //--- add ---
  18217. that.add = function( data ) {
  18218. if ( library[ data.name ] !== undefined )
  18219. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  18220. library[ data.name ] = data;
  18221. initData( data );
  18222. };
  18223. //--- get ---
  18224. that.get = function( name ) {
  18225. if ( typeof name === "string" ) {
  18226. if ( library[ name ] ) {
  18227. return library[ name ];
  18228. } else {
  18229. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  18230. return null;
  18231. }
  18232. } else {
  18233. // todo: add simple tween library
  18234. }
  18235. };
  18236. //--- parse ---
  18237. that.parse = function( root ) {
  18238. // setup hierarchy
  18239. var hierarchy = [];
  18240. if ( root instanceof THREE.SkinnedMesh ) {
  18241. for( var b = 0; b < root.bones.length; b++ ) {
  18242. hierarchy.push( root.bones[ b ] );
  18243. }
  18244. } else {
  18245. parseRecurseHierarchy( root, hierarchy );
  18246. }
  18247. return hierarchy;
  18248. };
  18249. var parseRecurseHierarchy = function( root, hierarchy ) {
  18250. hierarchy.push( root );
  18251. for( var c = 0; c < root.children.length; c++ )
  18252. parseRecurseHierarchy( root.children[ c ], hierarchy );
  18253. }
  18254. //--- init data ---
  18255. var initData = function( data ) {
  18256. if( data.initialized === true )
  18257. return;
  18258. // loop through all keys
  18259. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  18260. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18261. // remove minus times
  18262. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  18263. data.hierarchy[ h ].keys[ k ].time = 0;
  18264. // create quaternions
  18265. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  18266. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  18267. var quat = data.hierarchy[ h ].keys[ k ].rot;
  18268. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  18269. }
  18270. }
  18271. // prepare morph target keys
  18272. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  18273. // get all used
  18274. var usedMorphTargets = {};
  18275. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18276. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18277. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  18278. usedMorphTargets[ morphTargetName ] = -1;
  18279. }
  18280. }
  18281. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  18282. // set all used on all frames
  18283. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18284. var influences = {};
  18285. for ( var morphTargetName in usedMorphTargets ) {
  18286. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18287. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  18288. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  18289. break;
  18290. }
  18291. }
  18292. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  18293. influences[ morphTargetName ] = 0;
  18294. }
  18295. }
  18296. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  18297. }
  18298. }
  18299. // remove all keys that are on the same time
  18300. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18301. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  18302. data.hierarchy[ h ].keys.splice( k, 1 );
  18303. k --;
  18304. }
  18305. }
  18306. // set index
  18307. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18308. data.hierarchy[ h ].keys[ k ].index = k;
  18309. }
  18310. }
  18311. // JIT
  18312. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  18313. data.JIT = {};
  18314. data.JIT.hierarchy = [];
  18315. for( var h = 0; h < data.hierarchy.length; h ++ )
  18316. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  18317. // done
  18318. data.initialized = true;
  18319. };
  18320. // interpolation types
  18321. that.LINEAR = 0;
  18322. that.CATMULLROM = 1;
  18323. that.CATMULLROM_FORWARD = 2;
  18324. return that;
  18325. }());
  18326. /**
  18327. * @author mikael emtinger / http://gomo.se/
  18328. * @author mrdoob / http://mrdoob.com/
  18329. * @author alteredq / http://alteredqualia.com/
  18330. */
  18331. THREE.Animation = function ( root, name, interpolationType ) {
  18332. this.root = root;
  18333. this.data = THREE.AnimationHandler.get( name );
  18334. this.hierarchy = THREE.AnimationHandler.parse( root );
  18335. this.currentTime = 0;
  18336. this.timeScale = 1;
  18337. this.isPlaying = false;
  18338. this.isPaused = true;
  18339. this.loop = true;
  18340. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  18341. this.points = [];
  18342. this.target = new THREE.Vector3();
  18343. };
  18344. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  18345. if ( this.isPlaying === false ) {
  18346. this.isPlaying = true;
  18347. this.loop = loop !== undefined ? loop : true;
  18348. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  18349. // reset key cache
  18350. var h, hl = this.hierarchy.length,
  18351. object;
  18352. for ( h = 0; h < hl; h ++ ) {
  18353. object = this.hierarchy[ h ];
  18354. object.matrixAutoUpdate = true;
  18355. if ( object.animationCache === undefined ) {
  18356. object.animationCache = {};
  18357. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  18358. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  18359. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18360. }
  18361. var prevKey = object.animationCache.prevKey;
  18362. var nextKey = object.animationCache.nextKey;
  18363. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  18364. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  18365. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  18366. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  18367. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  18368. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  18369. }
  18370. this.update( 0 );
  18371. }
  18372. this.isPaused = false;
  18373. THREE.AnimationHandler.addToUpdate( this );
  18374. };
  18375. THREE.Animation.prototype.pause = function() {
  18376. if ( this.isPaused === true ) {
  18377. THREE.AnimationHandler.addToUpdate( this );
  18378. } else {
  18379. THREE.AnimationHandler.removeFromUpdate( this );
  18380. }
  18381. this.isPaused = !this.isPaused;
  18382. };
  18383. THREE.Animation.prototype.stop = function() {
  18384. this.isPlaying = false;
  18385. this.isPaused = false;
  18386. THREE.AnimationHandler.removeFromUpdate( this );
  18387. };
  18388. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  18389. // early out
  18390. if ( this.isPlaying === false ) return;
  18391. // vars
  18392. var types = [ "pos", "rot", "scl" ];
  18393. var type;
  18394. var scale;
  18395. var vector;
  18396. var prevXYZ, nextXYZ;
  18397. var prevKey, nextKey;
  18398. var object;
  18399. var animationCache;
  18400. var frame;
  18401. var JIThierarchy = this.data.JIT.hierarchy;
  18402. var currentTime, unloopedCurrentTime;
  18403. var currentPoint, forwardPoint, angle;
  18404. this.currentTime += deltaTimeMS * this.timeScale;
  18405. unloopedCurrentTime = this.currentTime;
  18406. currentTime = this.currentTime = this.currentTime % this.data.length;
  18407. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18408. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18409. object = this.hierarchy[ h ];
  18410. animationCache = object.animationCache;
  18411. // loop through pos/rot/scl
  18412. for ( var t = 0; t < 3; t ++ ) {
  18413. // get keys
  18414. type = types[ t ];
  18415. prevKey = animationCache.prevKey[ type ];
  18416. nextKey = animationCache.nextKey[ type ];
  18417. // switch keys?
  18418. if ( nextKey.time <= unloopedCurrentTime ) {
  18419. // did we loop?
  18420. if ( currentTime < unloopedCurrentTime ) {
  18421. if ( this.loop ) {
  18422. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  18423. nextKey = this.getNextKeyWith( type, h, 1 );
  18424. while( nextKey.time < currentTime ) {
  18425. prevKey = nextKey;
  18426. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18427. }
  18428. } else {
  18429. this.stop();
  18430. return;
  18431. }
  18432. } else {
  18433. do {
  18434. prevKey = nextKey;
  18435. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18436. } while( nextKey.time < currentTime )
  18437. }
  18438. animationCache.prevKey[ type ] = prevKey;
  18439. animationCache.nextKey[ type ] = nextKey;
  18440. }
  18441. object.matrixAutoUpdate = true;
  18442. object.matrixWorldNeedsUpdate = true;
  18443. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  18444. prevXYZ = prevKey[ type ];
  18445. nextXYZ = nextKey[ type ];
  18446. // check scale error
  18447. if ( scale < 0 || scale > 1 ) {
  18448. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  18449. scale = scale < 0 ? 0 : 1;
  18450. }
  18451. // interpolate
  18452. if ( type === "pos" ) {
  18453. vector = object.position;
  18454. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  18455. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18456. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18457. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18458. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18459. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18460. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  18461. this.points[ 1 ] = prevXYZ;
  18462. this.points[ 2 ] = nextXYZ;
  18463. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  18464. scale = scale * 0.33 + 0.33;
  18465. currentPoint = this.interpolateCatmullRom( this.points, scale );
  18466. vector.x = currentPoint[ 0 ];
  18467. vector.y = currentPoint[ 1 ];
  18468. vector.z = currentPoint[ 2 ];
  18469. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18470. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  18471. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  18472. this.target.sub( vector );
  18473. this.target.y = 0;
  18474. this.target.normalize();
  18475. angle = Math.atan2( this.target.x, this.target.z );
  18476. object.rotation.set( 0, angle, 0 );
  18477. }
  18478. }
  18479. } else if ( type === "rot" ) {
  18480. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  18481. } else if ( type === "scl" ) {
  18482. vector = object.scale;
  18483. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18484. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18485. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18486. }
  18487. }
  18488. }
  18489. };
  18490. // Catmull-Rom spline
  18491. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  18492. var c = [], v3 = [],
  18493. point, intPoint, weight, w2, w3,
  18494. pa, pb, pc, pd;
  18495. point = ( points.length - 1 ) * scale;
  18496. intPoint = Math.floor( point );
  18497. weight = point - intPoint;
  18498. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  18499. c[ 1 ] = intPoint;
  18500. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  18501. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  18502. pa = points[ c[ 0 ] ];
  18503. pb = points[ c[ 1 ] ];
  18504. pc = points[ c[ 2 ] ];
  18505. pd = points[ c[ 3 ] ];
  18506. w2 = weight * weight;
  18507. w3 = weight * w2;
  18508. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  18509. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  18510. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  18511. return v3;
  18512. };
  18513. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  18514. var v0 = ( p2 - p0 ) * 0.5,
  18515. v1 = ( p3 - p1 ) * 0.5;
  18516. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18517. };
  18518. // Get next key with
  18519. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  18520. var keys = this.data.hierarchy[ h ].keys;
  18521. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18522. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18523. key = key < keys.length - 1 ? key : keys.length - 1;
  18524. } else {
  18525. key = key % keys.length;
  18526. }
  18527. for ( ; key < keys.length; key++ ) {
  18528. if ( keys[ key ][ type ] !== undefined ) {
  18529. return keys[ key ];
  18530. }
  18531. }
  18532. return this.data.hierarchy[ h ].keys[ 0 ];
  18533. };
  18534. // Get previous key with
  18535. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  18536. var keys = this.data.hierarchy[ h ].keys;
  18537. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18538. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18539. key = key > 0 ? key : 0;
  18540. } else {
  18541. key = key >= 0 ? key : key + keys.length;
  18542. }
  18543. for ( ; key >= 0; key -- ) {
  18544. if ( keys[ key ][ type ] !== undefined ) {
  18545. return keys[ key ];
  18546. }
  18547. }
  18548. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  18549. };
  18550. /**
  18551. * @author mikael emtinger / http://gomo.se/
  18552. * @author mrdoob / http://mrdoob.com/
  18553. * @author alteredq / http://alteredqualia.com/
  18554. * @author khang duong
  18555. * @author erik kitson
  18556. */
  18557. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  18558. this.root = root;
  18559. this.data = THREE.AnimationHandler.get( data );
  18560. this.hierarchy = THREE.AnimationHandler.parse( root );
  18561. this.currentTime = 0;
  18562. this.timeScale = 0.001;
  18563. this.isPlaying = false;
  18564. this.isPaused = true;
  18565. this.loop = true;
  18566. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  18567. // initialize to first keyframes
  18568. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18569. var keys = this.data.hierarchy[h].keys,
  18570. sids = this.data.hierarchy[h].sids,
  18571. obj = this.hierarchy[h];
  18572. if ( keys.length && sids ) {
  18573. for ( var s = 0; s < sids.length; s++ ) {
  18574. var sid = sids[ s ],
  18575. next = this.getNextKeyWith( sid, h, 0 );
  18576. if ( next ) {
  18577. next.apply( sid );
  18578. }
  18579. }
  18580. obj.matrixAutoUpdate = false;
  18581. this.data.hierarchy[h].node.updateMatrix();
  18582. obj.matrixWorldNeedsUpdate = true;
  18583. }
  18584. }
  18585. };
  18586. // Play
  18587. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  18588. if( !this.isPlaying ) {
  18589. this.isPlaying = true;
  18590. this.loop = loop !== undefined ? loop : true;
  18591. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  18592. this.startTimeMs = startTimeMS;
  18593. this.startTime = 10000000;
  18594. this.endTime = -this.startTime;
  18595. // reset key cache
  18596. var h, hl = this.hierarchy.length,
  18597. object,
  18598. node;
  18599. for ( h = 0; h < hl; h++ ) {
  18600. object = this.hierarchy[ h ];
  18601. node = this.data.hierarchy[ h ];
  18602. if ( node.animationCache === undefined ) {
  18603. node.animationCache = {};
  18604. node.animationCache.prevKey = null;
  18605. node.animationCache.nextKey = null;
  18606. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18607. }
  18608. var keys = this.data.hierarchy[h].keys;
  18609. if (keys.length) {
  18610. node.animationCache.prevKey = keys[ 0 ];
  18611. node.animationCache.nextKey = keys[ 1 ];
  18612. this.startTime = Math.min( keys[0].time, this.startTime );
  18613. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18614. }
  18615. }
  18616. this.update( 0 );
  18617. }
  18618. this.isPaused = false;
  18619. THREE.AnimationHandler.addToUpdate( this );
  18620. };
  18621. // Pause
  18622. THREE.KeyFrameAnimation.prototype.pause = function() {
  18623. if( this.isPaused ) {
  18624. THREE.AnimationHandler.addToUpdate( this );
  18625. } else {
  18626. THREE.AnimationHandler.removeFromUpdate( this );
  18627. }
  18628. this.isPaused = !this.isPaused;
  18629. };
  18630. // Stop
  18631. THREE.KeyFrameAnimation.prototype.stop = function() {
  18632. this.isPlaying = false;
  18633. this.isPaused = false;
  18634. THREE.AnimationHandler.removeFromUpdate( this );
  18635. // reset JIT matrix and remove cache
  18636. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  18637. var obj = this.hierarchy[ h ];
  18638. var node = this.data.hierarchy[ h ];
  18639. if ( node.animationCache !== undefined ) {
  18640. var original = node.animationCache.originalMatrix;
  18641. if( obj instanceof THREE.Bone ) {
  18642. original.copy( obj.skinMatrix );
  18643. obj.skinMatrix = original;
  18644. } else {
  18645. original.copy( obj.matrix );
  18646. obj.matrix = original;
  18647. }
  18648. delete node.animationCache;
  18649. }
  18650. }
  18651. };
  18652. // Update
  18653. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  18654. // early out
  18655. if( !this.isPlaying ) return;
  18656. // vars
  18657. var prevKey, nextKey;
  18658. var object;
  18659. var node;
  18660. var frame;
  18661. var JIThierarchy = this.data.JIT.hierarchy;
  18662. var currentTime, unloopedCurrentTime;
  18663. var looped;
  18664. // update
  18665. this.currentTime += deltaTimeMS * this.timeScale;
  18666. unloopedCurrentTime = this.currentTime;
  18667. currentTime = this.currentTime = this.currentTime % this.data.length;
  18668. // if looped around, the current time should be based on the startTime
  18669. if ( currentTime < this.startTimeMs ) {
  18670. currentTime = this.currentTime = this.startTimeMs + currentTime;
  18671. }
  18672. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18673. looped = currentTime < unloopedCurrentTime;
  18674. if ( looped && !this.loop ) {
  18675. // Set the animation to the last keyframes and stop
  18676. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18677. var keys = this.data.hierarchy[h].keys,
  18678. sids = this.data.hierarchy[h].sids,
  18679. end = keys.length-1,
  18680. obj = this.hierarchy[h];
  18681. if ( keys.length ) {
  18682. for ( var s = 0; s < sids.length; s++ ) {
  18683. var sid = sids[ s ],
  18684. prev = this.getPrevKeyWith( sid, h, end );
  18685. if ( prev ) {
  18686. prev.apply( sid );
  18687. }
  18688. }
  18689. this.data.hierarchy[h].node.updateMatrix();
  18690. obj.matrixWorldNeedsUpdate = true;
  18691. }
  18692. }
  18693. this.stop();
  18694. return;
  18695. }
  18696. // check pre-infinity
  18697. if ( currentTime < this.startTime ) {
  18698. return;
  18699. }
  18700. // update
  18701. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18702. object = this.hierarchy[ h ];
  18703. node = this.data.hierarchy[ h ];
  18704. var keys = node.keys,
  18705. animationCache = node.animationCache;
  18706. // use JIT?
  18707. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  18708. if( object instanceof THREE.Bone ) {
  18709. object.skinMatrix = JIThierarchy[ h ][ frame ];
  18710. object.matrixWorldNeedsUpdate = false;
  18711. } else {
  18712. object.matrix = JIThierarchy[ h ][ frame ];
  18713. object.matrixWorldNeedsUpdate = true;
  18714. }
  18715. // use interpolation
  18716. } else if ( keys.length ) {
  18717. // make sure so original matrix and not JIT matrix is set
  18718. if ( this.JITCompile && animationCache ) {
  18719. if( object instanceof THREE.Bone ) {
  18720. object.skinMatrix = animationCache.originalMatrix;
  18721. } else {
  18722. object.matrix = animationCache.originalMatrix;
  18723. }
  18724. }
  18725. prevKey = animationCache.prevKey;
  18726. nextKey = animationCache.nextKey;
  18727. if ( prevKey && nextKey ) {
  18728. // switch keys?
  18729. if ( nextKey.time <= unloopedCurrentTime ) {
  18730. // did we loop?
  18731. if ( looped && this.loop ) {
  18732. prevKey = keys[ 0 ];
  18733. nextKey = keys[ 1 ];
  18734. while ( nextKey.time < currentTime ) {
  18735. prevKey = nextKey;
  18736. nextKey = keys[ prevKey.index + 1 ];
  18737. }
  18738. } else if ( !looped ) {
  18739. var lastIndex = keys.length - 1;
  18740. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  18741. prevKey = nextKey;
  18742. nextKey = keys[ prevKey.index + 1 ];
  18743. }
  18744. }
  18745. animationCache.prevKey = prevKey;
  18746. animationCache.nextKey = nextKey;
  18747. }
  18748. if(nextKey.time >= currentTime)
  18749. prevKey.interpolate( nextKey, currentTime );
  18750. else
  18751. prevKey.interpolate( nextKey, nextKey.time);
  18752. }
  18753. this.data.hierarchy[h].node.updateMatrix();
  18754. object.matrixWorldNeedsUpdate = true;
  18755. }
  18756. }
  18757. // update JIT?
  18758. if ( this.JITCompile ) {
  18759. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  18760. this.hierarchy[ 0 ].updateMatrixWorld( true );
  18761. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  18762. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  18763. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  18764. } else {
  18765. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  18766. }
  18767. }
  18768. }
  18769. }
  18770. };
  18771. // Get next key with
  18772. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18773. var keys = this.data.hierarchy[ h ].keys;
  18774. key = key % keys.length;
  18775. for ( ; key < keys.length; key++ ) {
  18776. if ( keys[ key ].hasTarget( sid ) ) {
  18777. return keys[ key ];
  18778. }
  18779. }
  18780. return keys[ 0 ];
  18781. };
  18782. // Get previous key with
  18783. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18784. var keys = this.data.hierarchy[ h ].keys;
  18785. key = key >= 0 ? key : key + keys.length;
  18786. for ( ; key >= 0; key-- ) {
  18787. if ( keys[ key ].hasTarget( sid ) ) {
  18788. return keys[ key ];
  18789. }
  18790. }
  18791. return keys[ keys.length - 1 ];
  18792. };
  18793. /**
  18794. * Camera for rendering cube maps
  18795. * - renders scene into axis-aligned cube
  18796. *
  18797. * @author alteredq / http://alteredqualia.com/
  18798. */
  18799. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  18800. THREE.Object3D.call( this );
  18801. var fov = 90, aspect = 1;
  18802. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18803. cameraPX.up.set( 0, -1, 0 );
  18804. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  18805. this.add( cameraPX );
  18806. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18807. cameraNX.up.set( 0, -1, 0 );
  18808. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  18809. this.add( cameraNX );
  18810. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18811. cameraPY.up.set( 0, 0, 1 );
  18812. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  18813. this.add( cameraPY );
  18814. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18815. cameraNY.up.set( 0, 0, -1 );
  18816. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  18817. this.add( cameraNY );
  18818. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18819. cameraPZ.up.set( 0, -1, 0 );
  18820. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  18821. this.add( cameraPZ );
  18822. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18823. cameraNZ.up.set( 0, -1, 0 );
  18824. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  18825. this.add( cameraNZ );
  18826. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  18827. this.updateCubeMap = function ( renderer, scene ) {
  18828. var renderTarget = this.renderTarget;
  18829. var generateMipmaps = renderTarget.generateMipmaps;
  18830. renderTarget.generateMipmaps = false;
  18831. renderTarget.activeCubeFace = 0;
  18832. renderer.render( scene, cameraPX, renderTarget );
  18833. renderTarget.activeCubeFace = 1;
  18834. renderer.render( scene, cameraNX, renderTarget );
  18835. renderTarget.activeCubeFace = 2;
  18836. renderer.render( scene, cameraPY, renderTarget );
  18837. renderTarget.activeCubeFace = 3;
  18838. renderer.render( scene, cameraNY, renderTarget );
  18839. renderTarget.activeCubeFace = 4;
  18840. renderer.render( scene, cameraPZ, renderTarget );
  18841. renderTarget.generateMipmaps = generateMipmaps;
  18842. renderTarget.activeCubeFace = 5;
  18843. renderer.render( scene, cameraNZ, renderTarget );
  18844. };
  18845. };
  18846. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  18847. /*
  18848. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  18849. *
  18850. * A general perpose camera, for setting FOV, Lens Focal Length,
  18851. * and switching between perspective and orthographic views easily.
  18852. * Use this only if you do not wish to manage
  18853. * both a Orthographic and Perspective Camera
  18854. *
  18855. */
  18856. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  18857. THREE.Camera.call( this );
  18858. this.fov = fov;
  18859. this.left = -width / 2;
  18860. this.right = width / 2
  18861. this.top = height / 2;
  18862. this.bottom = -height / 2;
  18863. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  18864. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  18865. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  18866. this.zoom = 1;
  18867. this.toPerspective();
  18868. var aspect = width/height;
  18869. };
  18870. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  18871. THREE.CombinedCamera.prototype.toPerspective = function () {
  18872. // Switches to the Perspective Camera
  18873. this.near = this.cameraP.near;
  18874. this.far = this.cameraP.far;
  18875. this.cameraP.fov = this.fov / this.zoom ;
  18876. this.cameraP.updateProjectionMatrix();
  18877. this.projectionMatrix = this.cameraP.projectionMatrix;
  18878. this.inPerspectiveMode = true;
  18879. this.inOrthographicMode = false;
  18880. };
  18881. THREE.CombinedCamera.prototype.toOrthographic = function () {
  18882. // Switches to the Orthographic camera estimating viewport from Perspective
  18883. var fov = this.fov;
  18884. var aspect = this.cameraP.aspect;
  18885. var near = this.cameraP.near;
  18886. var far = this.cameraP.far;
  18887. // The size that we set is the mid plane of the viewing frustum
  18888. var hyperfocus = ( near + far ) / 2;
  18889. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  18890. var planeHeight = 2 * halfHeight;
  18891. var planeWidth = planeHeight * aspect;
  18892. var halfWidth = planeWidth / 2;
  18893. halfHeight /= this.zoom;
  18894. halfWidth /= this.zoom;
  18895. this.cameraO.left = -halfWidth;
  18896. this.cameraO.right = halfWidth;
  18897. this.cameraO.top = halfHeight;
  18898. this.cameraO.bottom = -halfHeight;
  18899. // this.cameraO.left = -farHalfWidth;
  18900. // this.cameraO.right = farHalfWidth;
  18901. // this.cameraO.top = farHalfHeight;
  18902. // this.cameraO.bottom = -farHalfHeight;
  18903. // this.cameraO.left = this.left / this.zoom;
  18904. // this.cameraO.right = this.right / this.zoom;
  18905. // this.cameraO.top = this.top / this.zoom;
  18906. // this.cameraO.bottom = this.bottom / this.zoom;
  18907. this.cameraO.updateProjectionMatrix();
  18908. this.near = this.cameraO.near;
  18909. this.far = this.cameraO.far;
  18910. this.projectionMatrix = this.cameraO.projectionMatrix;
  18911. this.inPerspectiveMode = false;
  18912. this.inOrthographicMode = true;
  18913. };
  18914. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  18915. this.cameraP.aspect = width / height;
  18916. this.left = -width / 2;
  18917. this.right = width / 2
  18918. this.top = height / 2;
  18919. this.bottom = -height / 2;
  18920. };
  18921. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  18922. this.fov = fov;
  18923. if ( this.inPerspectiveMode ) {
  18924. this.toPerspective();
  18925. } else {
  18926. this.toOrthographic();
  18927. }
  18928. };
  18929. // For mantaining similar API with PerspectiveCamera
  18930. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  18931. if ( this.inPerspectiveMode ) {
  18932. this.toPerspective();
  18933. } else {
  18934. this.toPerspective();
  18935. this.toOrthographic();
  18936. }
  18937. };
  18938. /*
  18939. * Uses Focal Length (in mm) to estimate and set FOV
  18940. * 35mm (fullframe) camera is used if frame size is not specified;
  18941. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  18942. */
  18943. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  18944. if ( frameHeight === undefined ) frameHeight = 24;
  18945. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  18946. this.setFov( fov );
  18947. return fov;
  18948. };
  18949. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  18950. this.zoom = zoom;
  18951. if ( this.inPerspectiveMode ) {
  18952. this.toPerspective();
  18953. } else {
  18954. this.toOrthographic();
  18955. }
  18956. };
  18957. THREE.CombinedCamera.prototype.toFrontView = function() {
  18958. this.rotation.x = 0;
  18959. this.rotation.y = 0;
  18960. this.rotation.z = 0;
  18961. // should we be modifing the matrix instead?
  18962. this.rotationAutoUpdate = false;
  18963. };
  18964. THREE.CombinedCamera.prototype.toBackView = function() {
  18965. this.rotation.x = 0;
  18966. this.rotation.y = Math.PI;
  18967. this.rotation.z = 0;
  18968. this.rotationAutoUpdate = false;
  18969. };
  18970. THREE.CombinedCamera.prototype.toLeftView = function() {
  18971. this.rotation.x = 0;
  18972. this.rotation.y = - Math.PI / 2;
  18973. this.rotation.z = 0;
  18974. this.rotationAutoUpdate = false;
  18975. };
  18976. THREE.CombinedCamera.prototype.toRightView = function() {
  18977. this.rotation.x = 0;
  18978. this.rotation.y = Math.PI / 2;
  18979. this.rotation.z = 0;
  18980. this.rotationAutoUpdate = false;
  18981. };
  18982. THREE.CombinedCamera.prototype.toTopView = function() {
  18983. this.rotation.x = - Math.PI / 2;
  18984. this.rotation.y = 0;
  18985. this.rotation.z = 0;
  18986. this.rotationAutoUpdate = false;
  18987. };
  18988. THREE.CombinedCamera.prototype.toBottomView = function() {
  18989. this.rotation.x = Math.PI / 2;
  18990. this.rotation.y = 0;
  18991. this.rotation.z = 0;
  18992. this.rotationAutoUpdate = false;
  18993. };
  18994. /**
  18995. * @author hughes
  18996. */
  18997. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18998. THREE.Geometry.call( this );
  18999. radius = radius || 50;
  19000. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19001. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19002. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  19003. var i, uvs = [],
  19004. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  19005. this.vertices.push(center);
  19006. uvs.push( centerUV );
  19007. for ( i = 0; i <= segments; i ++ ) {
  19008. var vertex = new THREE.Vector3();
  19009. var segment = thetaStart + i / segments * thetaLength;
  19010. vertex.x = radius * Math.cos( segment );
  19011. vertex.y = radius * Math.sin( segment );
  19012. this.vertices.push( vertex );
  19013. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, ( vertex.y / radius + 1 ) / 2 ) );
  19014. }
  19015. var n = new THREE.Vector3( 0, 0, 1 );
  19016. for ( i = 1; i <= segments; i ++ ) {
  19017. var v1 = i;
  19018. var v2 = i + 1 ;
  19019. var v3 = 0;
  19020. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  19021. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  19022. }
  19023. this.computeCentroids();
  19024. this.computeFaceNormals();
  19025. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19026. };
  19027. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19028. /**
  19029. * @author mrdoob / http://mrdoob.com/
  19030. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  19031. */
  19032. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  19033. THREE.Geometry.call( this );
  19034. var scope = this;
  19035. this.width = width;
  19036. this.height = height;
  19037. this.depth = depth;
  19038. this.widthSegments = widthSegments || 1;
  19039. this.heightSegments = heightSegments || 1;
  19040. this.depthSegments = depthSegments || 1;
  19041. var width_half = this.width / 2;
  19042. var height_half = this.height / 2;
  19043. var depth_half = this.depth / 2;
  19044. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  19045. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  19046. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  19047. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  19048. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  19049. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  19050. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  19051. var w, ix, iy,
  19052. gridX = scope.widthSegments,
  19053. gridY = scope.heightSegments,
  19054. width_half = width / 2,
  19055. height_half = height / 2,
  19056. offset = scope.vertices.length;
  19057. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  19058. w = 'z';
  19059. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  19060. w = 'y';
  19061. gridY = scope.depthSegments;
  19062. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  19063. w = 'x';
  19064. gridX = scope.depthSegments;
  19065. }
  19066. var gridX1 = gridX + 1,
  19067. gridY1 = gridY + 1,
  19068. segment_width = width / gridX,
  19069. segment_height = height / gridY,
  19070. normal = new THREE.Vector3();
  19071. normal[ w ] = depth > 0 ? 1 : - 1;
  19072. for ( iy = 0; iy < gridY1; iy ++ ) {
  19073. for ( ix = 0; ix < gridX1; ix ++ ) {
  19074. var vector = new THREE.Vector3();
  19075. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  19076. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  19077. vector[ w ] = depth;
  19078. scope.vertices.push( vector );
  19079. }
  19080. }
  19081. for ( iy = 0; iy < gridY; iy++ ) {
  19082. for ( ix = 0; ix < gridX; ix++ ) {
  19083. var a = ix + gridX1 * iy;
  19084. var b = ix + gridX1 * ( iy + 1 );
  19085. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  19086. var d = ( ix + 1 ) + gridX1 * iy;
  19087. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  19088. face.normal.copy( normal );
  19089. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  19090. face.materialIndex = materialIndex;
  19091. scope.faces.push( face );
  19092. scope.faceVertexUvs[ 0 ].push( [
  19093. new THREE.Vector2( ix / gridX, 1 - iy / gridY ),
  19094. new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  19095. new THREE.Vector2( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  19096. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY )
  19097. ] );
  19098. }
  19099. }
  19100. }
  19101. this.computeCentroids();
  19102. this.mergeVertices();
  19103. };
  19104. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19105. /**
  19106. * @author mrdoob / http://mrdoob.com/
  19107. */
  19108. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded ) {
  19109. THREE.Geometry.call( this );
  19110. this.radiusTop = radiusTop = radiusTop !== undefined ? radiusTop : 20;
  19111. this.radiusBottom = radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  19112. this.height = height = height !== undefined ? height : 100;
  19113. this.radialSegments = radialSegments = radialSegments || 8;
  19114. this.heightSegments = heightSegments = heightSegments || 1;
  19115. this.openEnded = openEnded = openEnded !== undefined ? openEnded : false;
  19116. var heightHalf = height / 2;
  19117. var x, y, vertices = [], uvs = [];
  19118. for ( y = 0; y <= heightSegments; y ++ ) {
  19119. var verticesRow = [];
  19120. var uvsRow = [];
  19121. var v = y / heightSegments;
  19122. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  19123. for ( x = 0; x <= radialSegments; x ++ ) {
  19124. var u = x / radialSegments;
  19125. var vertex = new THREE.Vector3();
  19126. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  19127. vertex.y = - v * height + heightHalf;
  19128. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  19129. this.vertices.push( vertex );
  19130. verticesRow.push( this.vertices.length - 1 );
  19131. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19132. }
  19133. vertices.push( verticesRow );
  19134. uvs.push( uvsRow );
  19135. }
  19136. var tanTheta = ( radiusBottom - radiusTop ) / height;
  19137. var na, nb;
  19138. for ( x = 0; x < radialSegments; x ++ ) {
  19139. if ( radiusTop !== 0 ) {
  19140. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  19141. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  19142. } else {
  19143. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  19144. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  19145. }
  19146. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  19147. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  19148. for ( y = 0; y < heightSegments; y ++ ) {
  19149. var v1 = vertices[ y ][ x ];
  19150. var v2 = vertices[ y + 1 ][ x ];
  19151. var v3 = vertices[ y + 1 ][ x + 1 ];
  19152. var v4 = vertices[ y ][ x + 1 ];
  19153. var n1 = na.clone();
  19154. var n2 = na.clone();
  19155. var n3 = nb.clone();
  19156. var n4 = nb.clone();
  19157. var uv1 = uvs[ y ][ x ].clone();
  19158. var uv2 = uvs[ y + 1 ][ x ].clone();
  19159. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  19160. var uv4 = uvs[ y ][ x + 1 ].clone();
  19161. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  19162. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  19163. }
  19164. }
  19165. // top cap
  19166. if ( openEnded === false && radiusTop > 0 ) {
  19167. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  19168. for ( x = 0; x < radialSegments; x ++ ) {
  19169. var v1 = vertices[ 0 ][ x ];
  19170. var v2 = vertices[ 0 ][ x + 1 ];
  19171. var v3 = this.vertices.length - 1;
  19172. var n1 = new THREE.Vector3( 0, 1, 0 );
  19173. var n2 = new THREE.Vector3( 0, 1, 0 );
  19174. var n3 = new THREE.Vector3( 0, 1, 0 );
  19175. var uv1 = uvs[ 0 ][ x ].clone();
  19176. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  19177. var uv3 = new THREE.Vector2( uv2.u, 0 );
  19178. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19179. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19180. }
  19181. }
  19182. // bottom cap
  19183. if ( openEnded === false && radiusBottom > 0 ) {
  19184. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  19185. for ( x = 0; x < radialSegments; x ++ ) {
  19186. var v1 = vertices[ y ][ x + 1 ];
  19187. var v2 = vertices[ y ][ x ];
  19188. var v3 = this.vertices.length - 1;
  19189. var n1 = new THREE.Vector3( 0, - 1, 0 );
  19190. var n2 = new THREE.Vector3( 0, - 1, 0 );
  19191. var n3 = new THREE.Vector3( 0, - 1, 0 );
  19192. var uv1 = uvs[ y ][ x + 1 ].clone();
  19193. var uv2 = uvs[ y ][ x ].clone();
  19194. var uv3 = new THREE.Vector2( uv2.u, 1 );
  19195. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19196. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19197. }
  19198. }
  19199. this.computeCentroids();
  19200. this.computeFaceNormals();
  19201. }
  19202. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19203. /**
  19204. * @author zz85 / http://www.lab4games.net/zz85/blog
  19205. *
  19206. * Creates extruded geometry from a path shape.
  19207. *
  19208. * parameters = {
  19209. *
  19210. * size: <float>, // size of the text
  19211. * height: <float>, // thickness to extrude text
  19212. * curveSegments: <int>, // number of points on the curves
  19213. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  19214. * amount: <int>, // Amount
  19215. *
  19216. * bevelEnabled: <bool>, // turn on bevel
  19217. * bevelThickness: <float>, // how deep into text bevel goes
  19218. * bevelSize: <float>, // how far from text outline is bevel
  19219. * bevelSegments: <int>, // number of bevel layers
  19220. *
  19221. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  19222. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  19223. *
  19224. * material: <int> // material index for front and back faces
  19225. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  19226. * uvGenerator: <Object> // object that provides UV generator functions
  19227. *
  19228. * }
  19229. **/
  19230. THREE.ExtrudeGeometry = function ( shapes, options ) {
  19231. if ( typeof( shapes ) === "undefined" ) {
  19232. shapes = [];
  19233. return;
  19234. }
  19235. THREE.Geometry.call( this );
  19236. shapes = shapes instanceof Array ? shapes : [ shapes ];
  19237. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19238. this.addShapeList( shapes, options );
  19239. this.computeCentroids();
  19240. this.computeFaceNormals();
  19241. // can't really use automatic vertex normals
  19242. // as then front and back sides get smoothed too
  19243. // should do separate smoothing just for sides
  19244. //this.computeVertexNormals();
  19245. //console.log( "took", ( Date.now() - startTime ) );
  19246. };
  19247. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19248. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19249. var sl = shapes.length;
  19250. for ( var s = 0; s < sl; s ++ ) {
  19251. var shape = shapes[ s ];
  19252. this.addShape( shape, options );
  19253. }
  19254. };
  19255. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  19256. var amount = options.amount !== undefined ? options.amount : 100;
  19257. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  19258. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  19259. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19260. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  19261. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19262. var steps = options.steps !== undefined ? options.steps : 1;
  19263. var extrudePath = options.extrudePath;
  19264. var extrudePts, extrudeByPath = false;
  19265. var material = options.material;
  19266. var extrudeMaterial = options.extrudeMaterial;
  19267. // Use default WorldUVGenerator if no UV generators are specified.
  19268. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  19269. var shapebb = this.shapebb;
  19270. //shapebb = shape.getBoundingBox();
  19271. var splineTube, binormal, normal, position2;
  19272. if ( extrudePath ) {
  19273. extrudePts = extrudePath.getSpacedPoints( steps );
  19274. extrudeByPath = true;
  19275. bevelEnabled = false; // bevels not supported for path extrusion
  19276. // SETUP TNB variables
  19277. // Reuse TNB from TubeGeomtry for now.
  19278. // TODO1 - have a .isClosed in spline?
  19279. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  19280. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19281. binormal = new THREE.Vector3();
  19282. normal = new THREE.Vector3();
  19283. position2 = new THREE.Vector3();
  19284. }
  19285. // Safeguards if bevels are not enabled
  19286. if ( ! bevelEnabled ) {
  19287. bevelSegments = 0;
  19288. bevelThickness = 0;
  19289. bevelSize = 0;
  19290. }
  19291. // Variables initalization
  19292. var ahole, h, hl; // looping of holes
  19293. var scope = this;
  19294. var bevelPoints = [];
  19295. var shapesOffset = this.vertices.length;
  19296. var shapePoints = shape.extractPoints( curveSegments );
  19297. var vertices = shapePoints.shape;
  19298. var holes = shapePoints.holes;
  19299. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  19300. if ( reverse ) {
  19301. vertices = vertices.reverse();
  19302. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19303. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19304. ahole = holes[ h ];
  19305. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  19306. holes[ h ] = ahole.reverse();
  19307. }
  19308. }
  19309. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  19310. }
  19311. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  19312. /* Vertices */
  19313. var contour = vertices; // vertices has all points but contour has only points of circumference
  19314. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19315. ahole = holes[ h ];
  19316. vertices = vertices.concat( ahole );
  19317. }
  19318. function scalePt2 ( pt, vec, size ) {
  19319. if ( !vec ) console.log( "die" );
  19320. return vec.clone().multiplyScalar( size ).add( pt );
  19321. }
  19322. var b, bs, t, z,
  19323. vert, vlen = vertices.length,
  19324. face, flen = faces.length,
  19325. cont, clen = contour.length;
  19326. // Find directions for point movement
  19327. var RAD_TO_DEGREES = 180 / Math.PI;
  19328. function getBevelVec( pt_i, pt_j, pt_k ) {
  19329. // Algorithm 2
  19330. return getBevelVec2( pt_i, pt_j, pt_k );
  19331. }
  19332. function getBevelVec1( pt_i, pt_j, pt_k ) {
  19333. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  19334. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  19335. if ( anglea > angleb ) {
  19336. angleb += Math.PI * 2;
  19337. }
  19338. var anglec = ( anglea + angleb ) / 2;
  19339. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  19340. var x = - Math.cos( anglec );
  19341. var y = - Math.sin( anglec );
  19342. var vec = new THREE.Vector2( x, y ); //.normalize();
  19343. return vec;
  19344. }
  19345. function getBevelVec2( pt_i, pt_j, pt_k ) {
  19346. var a = THREE.ExtrudeGeometry.__v1,
  19347. b = THREE.ExtrudeGeometry.__v2,
  19348. v_hat = THREE.ExtrudeGeometry.__v3,
  19349. w_hat = THREE.ExtrudeGeometry.__v4,
  19350. p = THREE.ExtrudeGeometry.__v5,
  19351. q = THREE.ExtrudeGeometry.__v6,
  19352. v, w,
  19353. v_dot_w_hat, q_sub_p_dot_w_hat,
  19354. s, intersection;
  19355. // good reading for line-line intersection
  19356. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  19357. // define a as vector j->i
  19358. // define b as vectot k->i
  19359. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  19360. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  19361. // get unit vectors
  19362. v = a.normalize();
  19363. w = b.normalize();
  19364. // normals from pt i
  19365. v_hat.set( -v.y, v.x );
  19366. w_hat.set( w.y, -w.x );
  19367. // pts from i
  19368. p.copy( pt_i ).add( v_hat );
  19369. q.copy( pt_i ).add( w_hat );
  19370. if ( p.equals( q ) ) {
  19371. //console.log("Warning: lines are straight");
  19372. return w_hat.clone();
  19373. }
  19374. // Points from j, k. helps prevents points cross overover most of the time
  19375. p.copy( pt_j ).add( v_hat );
  19376. q.copy( pt_k ).add( w_hat );
  19377. v_dot_w_hat = v.dot( w_hat );
  19378. q_sub_p_dot_w_hat = q.sub( p ).dot( w_hat );
  19379. // We should not reach these conditions
  19380. if ( v_dot_w_hat === 0 ) {
  19381. console.log( "Either infinite or no solutions!" );
  19382. if ( q_sub_p_dot_w_hat === 0 ) {
  19383. console.log( "Its finite solutions." );
  19384. } else {
  19385. console.log( "Too bad, no solutions." );
  19386. }
  19387. }
  19388. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  19389. if ( s < 0 ) {
  19390. // in case of emergecy, revert to algorithm 1.
  19391. return getBevelVec1( pt_i, pt_j, pt_k );
  19392. }
  19393. intersection = v.multiplyScalar( s ).add( p );
  19394. return intersection.sub( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  19395. }
  19396. var contourMovements = [];
  19397. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19398. if ( j === il ) j = 0;
  19399. if ( k === il ) k = 0;
  19400. // (j)---(i)---(k)
  19401. // console.log('i,j,k', i, j , k)
  19402. var pt_i = contour[ i ];
  19403. var pt_j = contour[ j ];
  19404. var pt_k = contour[ k ];
  19405. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  19406. }
  19407. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  19408. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19409. ahole = holes[ h ];
  19410. oneHoleMovements = [];
  19411. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19412. if ( j === il ) j = 0;
  19413. if ( k === il ) k = 0;
  19414. // (j)---(i)---(k)
  19415. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  19416. }
  19417. holesMovements.push( oneHoleMovements );
  19418. verticesMovements = verticesMovements.concat( oneHoleMovements );
  19419. }
  19420. // Loop bevelSegments, 1 for the front, 1 for the back
  19421. for ( b = 0; b < bevelSegments; b ++ ) {
  19422. //for ( b = bevelSegments; b > 0; b -- ) {
  19423. t = b / bevelSegments;
  19424. z = bevelThickness * ( 1 - t );
  19425. //z = bevelThickness * t;
  19426. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  19427. //bs = bevelSize * t ; // linear
  19428. // contract shape
  19429. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19430. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19431. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  19432. v( vert.x, vert.y, - z );
  19433. }
  19434. // expand holes
  19435. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  19436. ahole = holes[ h ];
  19437. oneHoleMovements = holesMovements[ h ];
  19438. for ( i = 0, il = ahole.length; i < il; i++ ) {
  19439. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19440. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  19441. v( vert.x, vert.y, -z );
  19442. }
  19443. }
  19444. }
  19445. bs = bevelSize;
  19446. // Back facing vertices
  19447. for ( i = 0; i < vlen; i ++ ) {
  19448. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19449. if ( !extrudeByPath ) {
  19450. v( vert.x, vert.y, 0 );
  19451. } else {
  19452. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19453. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  19454. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  19455. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  19456. v( position2.x, position2.y, position2.z );
  19457. }
  19458. }
  19459. // Add stepped vertices...
  19460. // Including front facing vertices
  19461. var s;
  19462. for ( s = 1; s <= steps; s ++ ) {
  19463. for ( i = 0; i < vlen; i ++ ) {
  19464. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19465. if ( !extrudeByPath ) {
  19466. v( vert.x, vert.y, amount / steps * s );
  19467. } else {
  19468. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19469. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  19470. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  19471. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  19472. v( position2.x, position2.y, position2.z );
  19473. }
  19474. }
  19475. }
  19476. // Add bevel segments planes
  19477. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19478. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  19479. t = b / bevelSegments;
  19480. z = bevelThickness * ( 1 - t );
  19481. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  19482. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  19483. // contract shape
  19484. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19485. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19486. v( vert.x, vert.y, amount + z );
  19487. }
  19488. // expand holes
  19489. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19490. ahole = holes[ h ];
  19491. oneHoleMovements = holesMovements[ h ];
  19492. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  19493. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19494. if ( !extrudeByPath ) {
  19495. v( vert.x, vert.y, amount + z );
  19496. } else {
  19497. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19498. }
  19499. }
  19500. }
  19501. }
  19502. /* Faces */
  19503. // Top and bottom faces
  19504. buildLidFaces();
  19505. // Sides faces
  19506. buildSideFaces();
  19507. ///// Internal functions
  19508. function buildLidFaces() {
  19509. if ( bevelEnabled ) {
  19510. var layer = 0 ; // steps + 1
  19511. var offset = vlen * layer;
  19512. // Bottom faces
  19513. for ( i = 0; i < flen; i ++ ) {
  19514. face = faces[ i ];
  19515. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  19516. }
  19517. layer = steps + bevelSegments * 2;
  19518. offset = vlen * layer;
  19519. // Top faces
  19520. for ( i = 0; i < flen; i ++ ) {
  19521. face = faces[ i ];
  19522. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  19523. }
  19524. } else {
  19525. // Bottom faces
  19526. for ( i = 0; i < flen; i++ ) {
  19527. face = faces[ i ];
  19528. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  19529. }
  19530. // Top faces
  19531. for ( i = 0; i < flen; i ++ ) {
  19532. face = faces[ i ];
  19533. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  19534. }
  19535. }
  19536. }
  19537. // Create faces for the z-sides of the shape
  19538. function buildSideFaces() {
  19539. var layeroffset = 0;
  19540. sidewalls( contour, layeroffset );
  19541. layeroffset += contour.length;
  19542. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19543. ahole = holes[ h ];
  19544. sidewalls( ahole, layeroffset );
  19545. //, true
  19546. layeroffset += ahole.length;
  19547. }
  19548. }
  19549. function sidewalls( contour, layeroffset ) {
  19550. var j, k;
  19551. i = contour.length;
  19552. while ( --i >= 0 ) {
  19553. j = i;
  19554. k = i - 1;
  19555. if ( k < 0 ) k = contour.length - 1;
  19556. //console.log('b', i,j, i-1, k,vertices.length);
  19557. var s = 0, sl = steps + bevelSegments * 2;
  19558. for ( s = 0; s < sl; s ++ ) {
  19559. var slen1 = vlen * s;
  19560. var slen2 = vlen * ( s + 1 );
  19561. var a = layeroffset + j + slen1,
  19562. b = layeroffset + k + slen1,
  19563. c = layeroffset + k + slen2,
  19564. d = layeroffset + j + slen2;
  19565. f4( a, b, c, d, contour, s, sl, j, k );
  19566. }
  19567. }
  19568. }
  19569. function v( x, y, z ) {
  19570. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  19571. }
  19572. function f3( a, b, c, isBottom ) {
  19573. a += shapesOffset;
  19574. b += shapesOffset;
  19575. c += shapesOffset;
  19576. // normal, color, material
  19577. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19578. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  19579. scope.faceVertexUvs[ 0 ].push( uvs );
  19580. }
  19581. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19582. a += shapesOffset;
  19583. b += shapesOffset;
  19584. c += shapesOffset;
  19585. d += shapesOffset;
  19586. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  19587. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  19588. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  19589. scope.faceVertexUvs[ 0 ].push( uvs );
  19590. }
  19591. };
  19592. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19593. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19594. var ax = geometry.vertices[ indexA ].x,
  19595. ay = geometry.vertices[ indexA ].y,
  19596. bx = geometry.vertices[ indexB ].x,
  19597. by = geometry.vertices[ indexB ].y,
  19598. cx = geometry.vertices[ indexC ].x,
  19599. cy = geometry.vertices[ indexC ].y;
  19600. return [
  19601. new THREE.Vector2( ax, ay ),
  19602. new THREE.Vector2( bx, by ),
  19603. new THREE.Vector2( cx, cy )
  19604. ];
  19605. },
  19606. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19607. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19608. },
  19609. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19610. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19611. contourIndex1, contourIndex2 ) {
  19612. var ax = geometry.vertices[ indexA ].x,
  19613. ay = geometry.vertices[ indexA ].y,
  19614. az = geometry.vertices[ indexA ].z,
  19615. bx = geometry.vertices[ indexB ].x,
  19616. by = geometry.vertices[ indexB ].y,
  19617. bz = geometry.vertices[ indexB ].z,
  19618. cx = geometry.vertices[ indexC ].x,
  19619. cy = geometry.vertices[ indexC ].y,
  19620. cz = geometry.vertices[ indexC ].z,
  19621. dx = geometry.vertices[ indexD ].x,
  19622. dy = geometry.vertices[ indexD ].y,
  19623. dz = geometry.vertices[ indexD ].z;
  19624. if ( Math.abs( ay - by ) < 0.01 ) {
  19625. return [
  19626. new THREE.Vector2( ax, 1 - az ),
  19627. new THREE.Vector2( bx, 1 - bz ),
  19628. new THREE.Vector2( cx, 1 - cz ),
  19629. new THREE.Vector2( dx, 1 - dz )
  19630. ];
  19631. } else {
  19632. return [
  19633. new THREE.Vector2( ay, 1 - az ),
  19634. new THREE.Vector2( by, 1 - bz ),
  19635. new THREE.Vector2( cy, 1 - cz ),
  19636. new THREE.Vector2( dy, 1 - dz )
  19637. ];
  19638. }
  19639. }
  19640. };
  19641. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19642. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19643. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19644. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19645. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19646. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19647. /**
  19648. * @author jonobr1 / http://jonobr1.com
  19649. *
  19650. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19651. * ExtrudeGeometry.
  19652. *
  19653. * parameters = {
  19654. *
  19655. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19656. *
  19657. * material: <int> // material index for front and back faces
  19658. * uvGenerator: <Object> // object that provides UV generator functions
  19659. *
  19660. * }
  19661. **/
  19662. THREE.ShapeGeometry = function ( shapes, options ) {
  19663. THREE.Geometry.call( this );
  19664. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19665. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19666. this.addShapeList( shapes, options );
  19667. this.computeCentroids();
  19668. this.computeFaceNormals();
  19669. };
  19670. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19671. /**
  19672. * Add an array of shapes to THREE.ShapeGeometry.
  19673. */
  19674. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19675. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19676. this.addShape( shapes[ i ], options );
  19677. }
  19678. return this;
  19679. };
  19680. /**
  19681. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19682. */
  19683. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19684. if ( options === undefined ) options = {};
  19685. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19686. var material = options.material;
  19687. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19688. var shapebb = this.shapebb;
  19689. //
  19690. var i, l, hole, s;
  19691. var shapesOffset = this.vertices.length;
  19692. var shapePoints = shape.extractPoints( curveSegments );
  19693. var vertices = shapePoints.shape;
  19694. var holes = shapePoints.holes;
  19695. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19696. if ( reverse ) {
  19697. vertices = vertices.reverse();
  19698. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19699. for ( i = 0, l = holes.length; i < l; i++ ) {
  19700. hole = holes[ i ];
  19701. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19702. holes[ i ] = hole.reverse();
  19703. }
  19704. }
  19705. reverse = false;
  19706. }
  19707. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19708. // Vertices
  19709. var contour = vertices;
  19710. for ( i = 0, l = holes.length; i < l; i++ ) {
  19711. hole = holes[ i ];
  19712. vertices = vertices.concat( hole );
  19713. }
  19714. //
  19715. var vert, vlen = vertices.length;
  19716. var face, flen = faces.length;
  19717. var cont, clen = contour.length;
  19718. for ( i = 0; i < vlen; i++ ) {
  19719. vert = vertices[ i ];
  19720. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19721. }
  19722. for ( i = 0; i < flen; i++ ) {
  19723. face = faces[ i ];
  19724. var a = face[ 0 ] + shapesOffset;
  19725. var b = face[ 1 ] + shapesOffset;
  19726. var c = face[ 2 ] + shapesOffset;
  19727. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19728. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19729. }
  19730. };
  19731. /**
  19732. * @author astrodud / http://astrodud.isgreat.org/
  19733. * @author zz85 / https://github.com/zz85
  19734. * @author bhouston / http://exocortex.com
  19735. */
  19736. // points - to create a closed torus, one must use a set of points
  19737. // like so: [ a, b, c, d, a ], see first is the same as last.
  19738. // segments - the number of circumference segments to create
  19739. // phiStart - the starting radian
  19740. // phiLength - the radian (0 to 2*PI) range of the lathed section
  19741. // 2*pi is a closed lathe, less than 2PI is a portion.
  19742. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  19743. THREE.Geometry.call( this );
  19744. segments = segments || 12;
  19745. phiStart = phiStart || 0;
  19746. phiLength = phiLength || 2 * Math.PI;
  19747. var inversePointLength = 1.0 / ( points.length - 1 );
  19748. var inverseSegments = 1.0 / segments;
  19749. for ( var i = 0, il = segments; i <= il; i ++ ) {
  19750. var phi = phiStart + i * inverseSegments * phiLength;
  19751. var c = Math.cos( phi ),
  19752. s = Math.sin( phi );
  19753. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  19754. var pt = points[ j ];
  19755. var vertex = new THREE.Vector3();
  19756. vertex.x = c * pt.x - s * pt.y;
  19757. vertex.y = s * pt.x + c * pt.y;
  19758. vertex.z = pt.z;
  19759. this.vertices.push( vertex );
  19760. }
  19761. }
  19762. var np = points.length;
  19763. for ( var i = 0, il = segments; i < il; i ++ ) {
  19764. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  19765. var base = j + np * i;
  19766. var a = base;
  19767. var b = base + np;
  19768. var c = base + 1 + np;
  19769. var d = base + 1;
  19770. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19771. var u0 = i * inverseSegments;
  19772. var v0 = j * inversePointLength;
  19773. var u1 = u0 + inverseSegments;
  19774. var v1 = v0 + inversePointLength;
  19775. this.faceVertexUvs[ 0 ].push( [
  19776. new THREE.Vector2( u0, v0 ),
  19777. new THREE.Vector2( u1, v0 ),
  19778. new THREE.Vector2( u1, v1 ),
  19779. new THREE.Vector2( u0, v1 )
  19780. ] );
  19781. }
  19782. }
  19783. this.mergeVertices();
  19784. this.computeCentroids();
  19785. this.computeFaceNormals();
  19786. this.computeVertexNormals();
  19787. };
  19788. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19789. /**
  19790. * @author mrdoob / http://mrdoob.com/
  19791. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19792. */
  19793. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19794. THREE.Geometry.call( this );
  19795. this.width = width;
  19796. this.height = height;
  19797. this.widthSegments = widthSegments || 1;
  19798. this.heightSegments = heightSegments || 1;
  19799. var ix, iz;
  19800. var width_half = width / 2;
  19801. var height_half = height / 2;
  19802. var gridX = this.widthSegments;
  19803. var gridZ = this.heightSegments;
  19804. var gridX1 = gridX + 1;
  19805. var gridZ1 = gridZ + 1;
  19806. var segment_width = this.width / gridX;
  19807. var segment_height = this.height / gridZ;
  19808. var normal = new THREE.Vector3( 0, 0, 1 );
  19809. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19810. for ( ix = 0; ix < gridX1; ix ++ ) {
  19811. var x = ix * segment_width - width_half;
  19812. var y = iz * segment_height - height_half;
  19813. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19814. }
  19815. }
  19816. for ( iz = 0; iz < gridZ; iz ++ ) {
  19817. for ( ix = 0; ix < gridX; ix ++ ) {
  19818. var a = ix + gridX1 * iz;
  19819. var b = ix + gridX1 * ( iz + 1 );
  19820. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19821. var d = ( ix + 1 ) + gridX1 * iz;
  19822. var face = new THREE.Face4( a, b, c, d );
  19823. face.normal.copy( normal );
  19824. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  19825. this.faces.push( face );
  19826. this.faceVertexUvs[ 0 ].push( [
  19827. new THREE.Vector2( ix / gridX, 1 - iz / gridZ ),
  19828. new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  19829. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  19830. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  19831. ] );
  19832. }
  19833. }
  19834. this.computeCentroids();
  19835. };
  19836. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19837. /**
  19838. * @author Kaleb Murphy
  19839. */
  19840. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19841. THREE.Geometry.call( this );
  19842. innerRadius = innerRadius || 0;
  19843. outerRadius = outerRadius || 50;
  19844. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19845. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19846. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  19847. phiSegments = phiSegments !== undefined ? Math.max( 3, phiSegments ) : 8;
  19848. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19849. for ( i = 0; i <= phiSegments; i ++ ) { // concentric circles inside ring
  19850. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19851. var vertex = new THREE.Vector3();
  19852. var segment = thetaStart + o / thetaSegments * thetaLength;
  19853. vertex.x = radius * Math.cos( segment );
  19854. vertex.y = radius * Math.sin( segment );
  19855. this.vertices.push( vertex );
  19856. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  19857. }
  19858. radius += radiusStep;
  19859. }
  19860. var n = new THREE.Vector3( 0, 0, 1 );
  19861. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  19862. var thetaSegment = i * thetaSegments;
  19863. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19864. var segment = o + thetaSegment;
  19865. var v1 = segment + i;
  19866. var v2 = segment + thetaSegments + i;
  19867. var v3 = segment + thetaSegments + 1 + i;
  19868. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  19869. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ], uvs[ v2 ], uvs[ v3 ] ]);
  19870. v1 = segment + i;
  19871. v2 = segment + thetaSegments + 1 + i;
  19872. v3 = segment + 1 + i;
  19873. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  19874. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ], uvs[ v2 ], uvs[ v3 ] ]);
  19875. }
  19876. }
  19877. this.computeCentroids();
  19878. this.computeFaceNormals();
  19879. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19880. };
  19881. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19882. /**
  19883. * @author mrdoob / http://mrdoob.com/
  19884. */
  19885. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19886. THREE.Geometry.call( this );
  19887. this.radius = radius = radius || 50;
  19888. this.widthSegments = widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19889. this.heightSegments = heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19890. this.phiStart = phiStart = phiStart !== undefined ? phiStart : 0;
  19891. this.phiLength = phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19892. this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19893. this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19894. var x, y, vertices = [], uvs = [];
  19895. for ( y = 0; y <= heightSegments; y ++ ) {
  19896. var verticesRow = [];
  19897. var uvsRow = [];
  19898. for ( x = 0; x <= widthSegments; x ++ ) {
  19899. var u = x / widthSegments;
  19900. var v = y / heightSegments;
  19901. var vertex = new THREE.Vector3();
  19902. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19903. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  19904. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19905. this.vertices.push( vertex );
  19906. verticesRow.push( this.vertices.length - 1 );
  19907. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19908. }
  19909. vertices.push( verticesRow );
  19910. uvs.push( uvsRow );
  19911. }
  19912. for ( y = 0; y < this.heightSegments; y ++ ) {
  19913. for ( x = 0; x < this.widthSegments; x ++ ) {
  19914. var v1 = vertices[ y ][ x + 1 ];
  19915. var v2 = vertices[ y ][ x ];
  19916. var v3 = vertices[ y + 1 ][ x ];
  19917. var v4 = vertices[ y + 1 ][ x + 1 ];
  19918. var n1 = this.vertices[ v1 ].clone().normalize();
  19919. var n2 = this.vertices[ v2 ].clone().normalize();
  19920. var n3 = this.vertices[ v3 ].clone().normalize();
  19921. var n4 = this.vertices[ v4 ].clone().normalize();
  19922. var uv1 = uvs[ y ][ x + 1 ].clone();
  19923. var uv2 = uvs[ y ][ x ].clone();
  19924. var uv3 = uvs[ y + 1 ][ x ].clone();
  19925. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19926. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  19927. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19928. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19929. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  19930. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19931. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19932. } else {
  19933. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  19934. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  19935. }
  19936. }
  19937. }
  19938. this.computeCentroids();
  19939. this.computeFaceNormals();
  19940. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19941. };
  19942. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19943. /**
  19944. * @author zz85 / http://www.lab4games.net/zz85/blog
  19945. * @author alteredq / http://alteredqualia.com/
  19946. *
  19947. * For creating 3D text geometry in three.js
  19948. *
  19949. * Text = 3D Text
  19950. *
  19951. * parameters = {
  19952. * size: <float>, // size of the text
  19953. * height: <float>, // thickness to extrude text
  19954. * curveSegments: <int>, // number of points on the curves
  19955. *
  19956. * font: <string>, // font name
  19957. * weight: <string>, // font weight (normal, bold)
  19958. * style: <string>, // font style (normal, italics)
  19959. *
  19960. * bevelEnabled: <bool>, // turn on bevel
  19961. * bevelThickness: <float>, // how deep into text bevel goes
  19962. * bevelSize: <float>, // how far from text outline is bevel
  19963. * }
  19964. *
  19965. */
  19966. /* Usage Examples
  19967. // TextGeometry wrapper
  19968. var text3d = new TextGeometry( text, options );
  19969. // Complete manner
  19970. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19971. var text3d = new ExtrudeGeometry( textShapes, options );
  19972. */
  19973. THREE.TextGeometry = function ( text, parameters ) {
  19974. parameters = parameters || {};
  19975. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19976. // translate parameters to ExtrudeGeometry API
  19977. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19978. // defaults
  19979. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19980. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19981. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19982. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19983. };
  19984. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19985. /**
  19986. * @author oosmoxiecode
  19987. * @author mrdoob / http://mrdoob.com/
  19988. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19989. */
  19990. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19991. THREE.Geometry.call( this );
  19992. var scope = this;
  19993. this.radius = radius || 100;
  19994. this.tube = tube || 40;
  19995. this.radialSegments = radialSegments || 8;
  19996. this.tubularSegments = tubularSegments || 6;
  19997. this.arc = arc || Math.PI * 2;
  19998. var center = new THREE.Vector3(), uvs = [], normals = [];
  19999. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  20000. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  20001. var u = i / this.tubularSegments * this.arc;
  20002. var v = j / this.radialSegments * Math.PI * 2;
  20003. center.x = this.radius * Math.cos( u );
  20004. center.y = this.radius * Math.sin( u );
  20005. var vertex = new THREE.Vector3();
  20006. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  20007. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  20008. vertex.z = this.tube * Math.sin( v );
  20009. this.vertices.push( vertex );
  20010. uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
  20011. normals.push( vertex.clone().sub( center ).normalize() );
  20012. }
  20013. }
  20014. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  20015. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  20016. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  20017. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  20018. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  20019. var d = ( this.tubularSegments + 1 ) * j + i;
  20020. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  20021. face.normal.add( normals[ a ] );
  20022. face.normal.add( normals[ b ] );
  20023. face.normal.add( normals[ c ] );
  20024. face.normal.add( normals[ d ] );
  20025. face.normal.normalize();
  20026. this.faces.push( face );
  20027. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  20028. }
  20029. }
  20030. this.computeCentroids();
  20031. };
  20032. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20033. /**
  20034. * @author oosmoxiecode
  20035. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  20036. */
  20037. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  20038. THREE.Geometry.call( this );
  20039. var scope = this;
  20040. this.radius = radius || 100;
  20041. this.tube = tube || 40;
  20042. this.radialSegments = radialSegments || 64;
  20043. this.tubularSegments = tubularSegments || 8;
  20044. this.p = p || 2;
  20045. this.q = q || 3;
  20046. this.heightScale = heightScale || 1;
  20047. this.grid = new Array( this.radialSegments );
  20048. var tang = new THREE.Vector3();
  20049. var n = new THREE.Vector3();
  20050. var bitan = new THREE.Vector3();
  20051. for ( var i = 0; i < this.radialSegments; ++ i ) {
  20052. this.grid[ i ] = new Array( this.tubularSegments );
  20053. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  20054. var p1 = getPos( u, this.q, this.p, this.radius, this.heightScale );
  20055. var p2 = getPos( u + 0.01, this.q, this.p, this.radius, this.heightScale );
  20056. tang.subVectors( p2, p1 );
  20057. n.addVectors( p2, p1 );
  20058. bitan.crossVectors( tang, n );
  20059. n.crossVectors( bitan, tang );
  20060. bitan.normalize();
  20061. n.normalize();
  20062. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  20063. var v = j / this.tubularSegments * 2 * Math.PI;
  20064. var cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  20065. var cy = this.tube * Math.sin( v );
  20066. var pos = new THREE.Vector3();
  20067. pos.x = p1.x + cx * n.x + cy * bitan.x;
  20068. pos.y = p1.y + cx * n.y + cy * bitan.y;
  20069. pos.z = p1.z + cx * n.z + cy * bitan.z;
  20070. this.grid[ i ][ j ] = scope.vertices.push( pos ) - 1;
  20071. }
  20072. }
  20073. for ( var i = 0; i < this.radialSegments; ++ i ) {
  20074. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  20075. var ip = ( i + 1 ) % this.radialSegments;
  20076. var jp = ( j + 1 ) % this.tubularSegments;
  20077. var a = this.grid[ i ][ j ];
  20078. var b = this.grid[ ip ][ j ];
  20079. var c = this.grid[ ip ][ jp ];
  20080. var d = this.grid[ i ][ jp ];
  20081. var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
  20082. var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  20083. var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  20084. var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  20085. this.faces.push( new THREE.Face4( a, b, c, d ) );
  20086. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  20087. }
  20088. }
  20089. this.computeCentroids();
  20090. this.computeFaceNormals();
  20091. this.computeVertexNormals();
  20092. function getPos( u, in_q, in_p, radius, heightScale ) {
  20093. var cu = Math.cos( u );
  20094. var su = Math.sin( u );
  20095. var quOverP = in_q / in_p * u;
  20096. var cs = Math.cos( quOverP );
  20097. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  20098. var ty = radius * ( 2 + cs ) * su * 0.5;
  20099. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  20100. return new THREE.Vector3( tx, ty, tz );
  20101. }
  20102. };
  20103. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20104. /**
  20105. * @author WestLangley / https://github.com/WestLangley
  20106. * @author zz85 / https://github.com/zz85
  20107. * @author miningold / https://github.com/miningold
  20108. *
  20109. * Modified from the TorusKnotGeometry by @oosmoxiecode
  20110. *
  20111. * Creates a tube which extrudes along a 3d spline
  20112. *
  20113. * Uses parallel transport frames as described in
  20114. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  20115. */
  20116. THREE.TubeGeometry = function( path, segments, radius, radialSegments, closed ) {
  20117. THREE.Geometry.call( this );
  20118. this.path = path;
  20119. this.segments = segments || 64;
  20120. this.radius = radius || 1;
  20121. this.radialSegments = radialSegments || 8;
  20122. this.closed = closed || false;
  20123. this.grid = [];
  20124. var scope = this,
  20125. tangent,
  20126. normal,
  20127. binormal,
  20128. numpoints = this.segments + 1,
  20129. x, y, z,
  20130. tx, ty, tz,
  20131. u, v,
  20132. cx, cy,
  20133. pos, pos2 = new THREE.Vector3(),
  20134. i, j,
  20135. ip, jp,
  20136. a, b, c, d,
  20137. uva, uvb, uvc, uvd;
  20138. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  20139. tangents = frames.tangents,
  20140. normals = frames.normals,
  20141. binormals = frames.binormals;
  20142. // proxy internals
  20143. this.tangents = tangents;
  20144. this.normals = normals;
  20145. this.binormals = binormals;
  20146. function vert( x, y, z ) {
  20147. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  20148. }
  20149. // consruct the grid
  20150. for ( i = 0; i < numpoints; i++ ) {
  20151. this.grid[ i ] = [];
  20152. u = i / ( numpoints - 1 );
  20153. pos = path.getPointAt( u );
  20154. tangent = tangents[ i ];
  20155. normal = normals[ i ];
  20156. binormal = binormals[ i ];
  20157. for ( j = 0; j < this.radialSegments; j++ ) {
  20158. v = j / this.radialSegments * 2 * Math.PI;
  20159. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  20160. cy = this.radius * Math.sin( v );
  20161. pos2.copy( pos );
  20162. pos2.x += cx * normal.x + cy * binormal.x;
  20163. pos2.y += cx * normal.y + cy * binormal.y;
  20164. pos2.z += cx * normal.z + cy * binormal.z;
  20165. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  20166. }
  20167. }
  20168. // construct the mesh
  20169. for ( i = 0; i < this.segments; i++ ) {
  20170. for ( j = 0; j < this.radialSegments; j++ ) {
  20171. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  20172. jp = (j + 1) % this.radialSegments;
  20173. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  20174. b = this.grid[ ip ][ j ];
  20175. c = this.grid[ ip ][ jp ];
  20176. d = this.grid[ i ][ jp ];
  20177. uva = new THREE.Vector2( i / this.segments, j / this.radialSegments );
  20178. uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radialSegments );
  20179. uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radialSegments );
  20180. uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radialSegments );
  20181. this.faces.push( new THREE.Face4( a, b, c, d ) );
  20182. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  20183. }
  20184. }
  20185. this.computeCentroids();
  20186. this.computeFaceNormals();
  20187. this.computeVertexNormals();
  20188. };
  20189. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20190. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  20191. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  20192. var tangent = new THREE.Vector3(),
  20193. normal = new THREE.Vector3(),
  20194. binormal = new THREE.Vector3(),
  20195. tangents = [],
  20196. normals = [],
  20197. binormals = [],
  20198. vec = new THREE.Vector3(),
  20199. mat = new THREE.Matrix4(),
  20200. numpoints = segments + 1,
  20201. theta,
  20202. epsilon = 0.0001,
  20203. smallest,
  20204. tx, ty, tz,
  20205. i, u, v;
  20206. // expose internals
  20207. this.tangents = tangents;
  20208. this.normals = normals;
  20209. this.binormals = binormals;
  20210. // compute the tangent vectors for each segment on the path
  20211. for ( i = 0; i < numpoints; i++ ) {
  20212. u = i / ( numpoints - 1 );
  20213. tangents[ i ] = path.getTangentAt( u );
  20214. tangents[ i ].normalize();
  20215. }
  20216. initialNormal3();
  20217. function initialNormal1(lastBinormal) {
  20218. // fixed start binormal. Has dangers of 0 vectors
  20219. normals[ 0 ] = new THREE.Vector3();
  20220. binormals[ 0 ] = new THREE.Vector3();
  20221. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  20222. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  20223. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20224. }
  20225. function initialNormal2() {
  20226. // This uses the Frenet-Serret formula for deriving binormal
  20227. var t2 = path.getTangentAt( epsilon );
  20228. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  20229. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  20230. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  20231. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20232. }
  20233. function initialNormal3() {
  20234. // select an initial normal vector perpenicular to the first tangent vector,
  20235. // and in the direction of the smallest tangent xyz component
  20236. normals[ 0 ] = new THREE.Vector3();
  20237. binormals[ 0 ] = new THREE.Vector3();
  20238. smallest = Number.MAX_VALUE;
  20239. tx = Math.abs( tangents[ 0 ].x );
  20240. ty = Math.abs( tangents[ 0 ].y );
  20241. tz = Math.abs( tangents[ 0 ].z );
  20242. if ( tx <= smallest ) {
  20243. smallest = tx;
  20244. normal.set( 1, 0, 0 );
  20245. }
  20246. if ( ty <= smallest ) {
  20247. smallest = ty;
  20248. normal.set( 0, 1, 0 );
  20249. }
  20250. if ( tz <= smallest ) {
  20251. normal.set( 0, 0, 1 );
  20252. }
  20253. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  20254. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  20255. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  20256. }
  20257. // compute the slowly-varying normal and binormal vectors for each segment on the path
  20258. for ( i = 1; i < numpoints; i++ ) {
  20259. normals[ i ] = normals[ i-1 ].clone();
  20260. binormals[ i ] = binormals[ i-1 ].clone();
  20261. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  20262. if ( vec.length() > epsilon ) {
  20263. vec.normalize();
  20264. theta = Math.acos( THREE.Math.clamp( tangents[ i-1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  20265. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  20266. }
  20267. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20268. }
  20269. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  20270. if ( closed ) {
  20271. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints-1 ] ), -1, 1 ) );
  20272. theta /= ( numpoints - 1 );
  20273. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  20274. theta = -theta;
  20275. }
  20276. for ( i = 1; i < numpoints; i++ ) {
  20277. // twist a little...
  20278. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  20279. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20280. }
  20281. }
  20282. };
  20283. /**
  20284. * @author clockworkgeek / https://github.com/clockworkgeek
  20285. * @author timothypratley / https://github.com/timothypratley
  20286. * @author WestLangley / http://github.com/WestLangley
  20287. */
  20288. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  20289. THREE.Geometry.call( this );
  20290. radius = radius || 1;
  20291. detail = detail || 0;
  20292. var that = this;
  20293. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  20294. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  20295. }
  20296. var midpoints = [], p = this.vertices;
  20297. var f = [];
  20298. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20299. var v1 = p[ faces[ i ][ 0 ] ];
  20300. var v2 = p[ faces[ i ][ 1 ] ];
  20301. var v3 = p[ faces[ i ][ 2 ] ];
  20302. f[ i ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  20303. }
  20304. for ( var i = 0, l = f.length; i < l; i ++ ) {
  20305. subdivide(f[ i ], detail);
  20306. }
  20307. // Handle case when face straddles the seam
  20308. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  20309. var uvs = this.faceVertexUvs[ 0 ][ i ];
  20310. var x0 = uvs[ 0 ].x;
  20311. var x1 = uvs[ 1 ].x;
  20312. var x2 = uvs[ 2 ].x;
  20313. var max = Math.max( x0, Math.max( x1, x2 ) );
  20314. var min = Math.min( x0, Math.min( x1, x2 ) );
  20315. if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
  20316. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  20317. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  20318. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  20319. }
  20320. }
  20321. // Apply radius
  20322. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  20323. this.vertices[ i ].multiplyScalar( radius );
  20324. }
  20325. // Merge vertices
  20326. this.mergeVertices();
  20327. this.computeCentroids();
  20328. this.computeFaceNormals();
  20329. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  20330. // Project vector onto sphere's surface
  20331. function prepare( vector ) {
  20332. var vertex = vector.normalize().clone();
  20333. vertex.index = that.vertices.push( vertex ) - 1;
  20334. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  20335. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  20336. var v = inclination( vector ) / Math.PI + 0.5;
  20337. vertex.uv = new THREE.Vector2( u, 1 - v );
  20338. return vertex;
  20339. }
  20340. // Approximate a curved face with recursively sub-divided triangles.
  20341. function make( v1, v2, v3 ) {
  20342. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  20343. face.centroid.add( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  20344. that.faces.push( face );
  20345. var azi = azimuth( face.centroid );
  20346. that.faceVertexUvs[ 0 ].push( [
  20347. correctUV( v1.uv, v1, azi ),
  20348. correctUV( v2.uv, v2, azi ),
  20349. correctUV( v3.uv, v3, azi )
  20350. ] );
  20351. }
  20352. // Analytically subdivide a face to the required detail level.
  20353. function subdivide(face, detail ) {
  20354. var cols = Math.pow(2, detail);
  20355. var cells = Math.pow(4, detail);
  20356. var a = prepare( that.vertices[ face.a ] );
  20357. var b = prepare( that.vertices[ face.b ] );
  20358. var c = prepare( that.vertices[ face.c ] );
  20359. var v = [];
  20360. // Construct all of the vertices for this subdivision.
  20361. for ( var i = 0 ; i <= cols; i ++ ) {
  20362. v[ i ] = [];
  20363. var aj = prepare( a.clone().lerp( c, i / cols ) );
  20364. var bj = prepare( b.clone().lerp( c, i / cols ) );
  20365. var rows = cols - i;
  20366. for ( var j = 0; j <= rows; j ++) {
  20367. if ( j == 0 && i == cols ) {
  20368. v[ i ][ j ] = aj;
  20369. } else {
  20370. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  20371. }
  20372. }
  20373. }
  20374. // Construct all of the faces.
  20375. for ( var i = 0; i < cols ; i ++ ) {
  20376. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  20377. var k = Math.floor( j / 2 );
  20378. if ( j % 2 == 0 ) {
  20379. make(
  20380. v[ i ][ k + 1],
  20381. v[ i + 1 ][ k ],
  20382. v[ i ][ k ]
  20383. );
  20384. } else {
  20385. make(
  20386. v[ i ][ k + 1 ],
  20387. v[ i + 1][ k + 1],
  20388. v[ i + 1 ][ k ]
  20389. );
  20390. }
  20391. }
  20392. }
  20393. }
  20394. // Angle around the Y axis, counter-clockwise when looking from above.
  20395. function azimuth( vector ) {
  20396. return Math.atan2( vector.z, -vector.x );
  20397. }
  20398. // Angle above the XZ plane.
  20399. function inclination( vector ) {
  20400. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20401. }
  20402. // Texture fixing helper. Spheres have some odd behaviours.
  20403. function correctUV( uv, vector, azimuth ) {
  20404. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  20405. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  20406. return uv.clone();
  20407. }
  20408. };
  20409. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20410. /**
  20411. * @author timothypratley / https://github.com/timothypratley
  20412. */
  20413. THREE.IcosahedronGeometry = function ( radius, detail ) {
  20414. this.radius = radius;
  20415. this.detail = detail;
  20416. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20417. var vertices = [
  20418. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  20419. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  20420. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  20421. ];
  20422. var faces = [
  20423. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  20424. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  20425. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  20426. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  20427. ];
  20428. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20429. };
  20430. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20431. /**
  20432. * @author timothypratley / https://github.com/timothypratley
  20433. */
  20434. THREE.OctahedronGeometry = function ( radius, detail ) {
  20435. var vertices = [
  20436. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  20437. ];
  20438. var faces = [
  20439. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  20440. ];
  20441. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20442. };
  20443. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20444. /**
  20445. * @author timothypratley / https://github.com/timothypratley
  20446. */
  20447. THREE.TetrahedronGeometry = function ( radius, detail ) {
  20448. var vertices = [
  20449. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  20450. ];
  20451. var faces = [
  20452. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  20453. ];
  20454. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20455. };
  20456. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20457. /**
  20458. * @author zz85 / https://github.com/zz85
  20459. * Parametric Surfaces Geometry
  20460. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  20461. *
  20462. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  20463. *
  20464. */
  20465. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  20466. THREE.Geometry.call( this );
  20467. var verts = this.vertices;
  20468. var faces = this.faces;
  20469. var uvs = this.faceVertexUvs[ 0 ];
  20470. useTris = (useTris === undefined) ? false : useTris;
  20471. var i, il, j, p;
  20472. var u, v;
  20473. var stackCount = stacks + 1;
  20474. var sliceCount = slices + 1;
  20475. for ( i = 0; i <= stacks; i ++ ) {
  20476. v = i / stacks;
  20477. for ( j = 0; j <= slices; j ++ ) {
  20478. u = j / slices;
  20479. p = func( u, v );
  20480. verts.push( p );
  20481. }
  20482. }
  20483. var a, b, c, d;
  20484. var uva, uvb, uvc, uvd;
  20485. for ( i = 0; i < stacks; i ++ ) {
  20486. for ( j = 0; j < slices; j ++ ) {
  20487. a = i * sliceCount + j;
  20488. b = i * sliceCount + j + 1;
  20489. c = (i + 1) * sliceCount + j;
  20490. d = (i + 1) * sliceCount + j + 1;
  20491. uva = new THREE.Vector2( j / slices, i / stacks );
  20492. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  20493. uvc = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  20494. uvd = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  20495. if ( useTris ) {
  20496. faces.push( new THREE.Face3( a, b, c ) );
  20497. faces.push( new THREE.Face3( b, d, c ) );
  20498. uvs.push( [ uva, uvb, uvc ] );
  20499. uvs.push( [ uvb, uvd, uvc ] );
  20500. } else {
  20501. faces.push( new THREE.Face4( a, b, d, c ) );
  20502. uvs.push( [ uva, uvb, uvd, uvc ] );
  20503. }
  20504. }
  20505. }
  20506. // console.log(this);
  20507. // magic bullet
  20508. // var diff = this.mergeVertices();
  20509. // console.log('removed ', diff, ' vertices by merging');
  20510. this.computeCentroids();
  20511. this.computeFaceNormals();
  20512. this.computeVertexNormals();
  20513. };
  20514. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20515. /**
  20516. * @author qiao / https://github.com/qiao
  20517. * @fileoverview This is a convex hull generator using the incremental method.
  20518. * The complexity is O(n^2) where n is the number of vertices.
  20519. * O(nlogn) algorithms do exist, but they are much more complicated.
  20520. *
  20521. * Benchmark:
  20522. *
  20523. * Platform: CPU: P7350 @2.00GHz Engine: V8
  20524. *
  20525. * Num Vertices Time(ms)
  20526. *
  20527. * 10 1
  20528. * 20 3
  20529. * 30 19
  20530. * 40 48
  20531. * 50 107
  20532. */
  20533. THREE.ConvexGeometry = function( vertices ) {
  20534. THREE.Geometry.call( this );
  20535. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  20536. for ( var i = 3; i < vertices.length; i++ ) {
  20537. addPoint( i );
  20538. }
  20539. function addPoint( vertexId ) {
  20540. var vertex = vertices[ vertexId ].clone();
  20541. var mag = vertex.length();
  20542. vertex.x += mag * randomOffset();
  20543. vertex.y += mag * randomOffset();
  20544. vertex.z += mag * randomOffset();
  20545. var hole = [];
  20546. for ( var f = 0; f < faces.length; ) {
  20547. var face = faces[ f ];
  20548. // for each face, if the vertex can see it,
  20549. // then we try to add the face's edges into the hole.
  20550. if ( visible( face, vertex ) ) {
  20551. for ( var e = 0; e < 3; e++ ) {
  20552. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  20553. var boundary = true;
  20554. // remove duplicated edges.
  20555. for ( var h = 0; h < hole.length; h++ ) {
  20556. if ( equalEdge( hole[ h ], edge ) ) {
  20557. hole[ h ] = hole[ hole.length - 1 ];
  20558. hole.pop();
  20559. boundary = false;
  20560. break;
  20561. }
  20562. }
  20563. if ( boundary ) {
  20564. hole.push( edge );
  20565. }
  20566. }
  20567. // remove faces[ f ]
  20568. faces[ f ] = faces[ faces.length - 1 ];
  20569. faces.pop();
  20570. } else { // not visible
  20571. f++;
  20572. }
  20573. }
  20574. // construct the new faces formed by the edges of the hole and the vertex
  20575. for ( var h = 0; h < hole.length; h++ ) {
  20576. faces.push( [
  20577. hole[ h ][ 0 ],
  20578. hole[ h ][ 1 ],
  20579. vertexId
  20580. ] );
  20581. }
  20582. }
  20583. /**
  20584. * Whether the face is visible from the vertex
  20585. */
  20586. function visible( face, vertex ) {
  20587. var va = vertices[ face[ 0 ] ];
  20588. var vb = vertices[ face[ 1 ] ];
  20589. var vc = vertices[ face[ 2 ] ];
  20590. var n = normal( va, vb, vc );
  20591. // distance from face to origin
  20592. var dist = n.dot( va );
  20593. return n.dot( vertex ) >= dist;
  20594. }
  20595. /**
  20596. * Face normal
  20597. */
  20598. function normal( va, vb, vc ) {
  20599. var cb = new THREE.Vector3();
  20600. var ab = new THREE.Vector3();
  20601. cb.subVectors( vc, vb );
  20602. ab.subVectors( va, vb );
  20603. cb.cross( ab );
  20604. cb.normalize();
  20605. return cb;
  20606. }
  20607. /**
  20608. * Detect whether two edges are equal.
  20609. * Note that when constructing the convex hull, two same edges can only
  20610. * be of the negative direction.
  20611. */
  20612. function equalEdge( ea, eb ) {
  20613. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  20614. }
  20615. /**
  20616. * Create a random offset between -1e-6 and 1e-6.
  20617. */
  20618. function randomOffset() {
  20619. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  20620. }
  20621. /**
  20622. * XXX: Not sure if this is the correct approach. Need someone to review.
  20623. */
  20624. function vertexUv( vertex ) {
  20625. var mag = vertex.length();
  20626. return new THREE.Vector2( vertex.x / mag, vertex.y / mag );
  20627. }
  20628. // Push vertices into `this.vertices`, skipping those inside the hull
  20629. var id = 0;
  20630. var newId = new Array( vertices.length ); // map from old vertex id to new id
  20631. for ( var i = 0; i < faces.length; i++ ) {
  20632. var face = faces[ i ];
  20633. for ( var j = 0; j < 3; j++ ) {
  20634. if ( newId[ face[ j ] ] === undefined ) {
  20635. newId[ face[ j ] ] = id++;
  20636. this.vertices.push( vertices[ face[ j ] ] );
  20637. }
  20638. face[ j ] = newId[ face[ j ] ];
  20639. }
  20640. }
  20641. // Convert faces into instances of THREE.Face3
  20642. for ( var i = 0; i < faces.length; i++ ) {
  20643. this.faces.push( new THREE.Face3(
  20644. faces[ i ][ 0 ],
  20645. faces[ i ][ 1 ],
  20646. faces[ i ][ 2 ]
  20647. ) );
  20648. }
  20649. // Compute UVs
  20650. for ( var i = 0; i < this.faces.length; i++ ) {
  20651. var face = this.faces[ i ];
  20652. this.faceVertexUvs[ 0 ].push( [
  20653. vertexUv( this.vertices[ face.a ] ),
  20654. vertexUv( this.vertices[ face.b ] ),
  20655. vertexUv( this.vertices[ face.c ])
  20656. ] );
  20657. }
  20658. this.computeCentroids();
  20659. this.computeFaceNormals();
  20660. this.computeVertexNormals();
  20661. };
  20662. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20663. /**
  20664. * @author sroucheray / http://sroucheray.org/
  20665. * @author mrdoob / http://mrdoob.com/
  20666. */
  20667. THREE.AxisHelper = function ( size ) {
  20668. size = size || 1;
  20669. var geometry = new THREE.Geometry();
  20670. geometry.vertices.push(
  20671. new THREE.Vector3(), new THREE.Vector3( size, 0, 0 ),
  20672. new THREE.Vector3(), new THREE.Vector3( 0, size, 0 ),
  20673. new THREE.Vector3(), new THREE.Vector3( 0, 0, size )
  20674. );
  20675. geometry.colors.push(
  20676. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  20677. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  20678. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  20679. );
  20680. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20681. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20682. };
  20683. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20684. /**
  20685. * @author WestLangley / http://github.com/WestLangley
  20686. * @author zz85 / http://github.com/zz85
  20687. * @author bhouston / http://exocortex.com
  20688. *
  20689. * Creates an arrow for visualizing directions
  20690. *
  20691. * Parameters:
  20692. * dir - Vector3
  20693. * origin - Vector3
  20694. * length - Number
  20695. * hex - color in hex value
  20696. */
  20697. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  20698. // dir is assumed to be normalized
  20699. THREE.Object3D.call( this );
  20700. if ( hex === undefined ) hex = 0xffff00;
  20701. if ( length === undefined ) length = 1;
  20702. this.position = origin;
  20703. var lineGeometry = new THREE.Geometry();
  20704. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  20705. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  20706. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  20707. this.line.matrixAutoUpdate = false;
  20708. this.add( this.line );
  20709. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  20710. coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, 0.875, 0 ) );
  20711. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  20712. this.cone.matrixAutoUpdate = false;
  20713. this.add( this.cone );
  20714. this.setDirection( dir );
  20715. this.setLength( length );
  20716. };
  20717. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20718. THREE.ArrowHelper.prototype.setDirection = function () {
  20719. var axis = new THREE.Vector3();
  20720. var radians;
  20721. return function ( dir ) {
  20722. // dir is assumed to be normalized
  20723. if ( dir.y > 0.99999 ) {
  20724. this.quaternion.set( 0, 0, 0, 1 );
  20725. } else if ( dir.y < - 0.99999 ) {
  20726. this.quaternion.set( 1, 0, 0, 0 );
  20727. } else {
  20728. axis.set( dir.z, 0, - dir.x ).normalize();
  20729. radians = Math.acos( dir.y );
  20730. this.quaternion.setFromAxisAngle( axis, radians );
  20731. }
  20732. };
  20733. }();
  20734. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  20735. this.scale.set( length, length, length );
  20736. };
  20737. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  20738. this.line.material.color.setHex( hex );
  20739. this.cone.material.color.setHex( hex );
  20740. };
  20741. /**
  20742. * @author mrdoob / http://mrdoob.com/
  20743. */
  20744. THREE.BoxHelper = function ( object ) {
  20745. // 5____4
  20746. // 1/___0/|
  20747. // | 6__|_7
  20748. // 2/___3/
  20749. var vertices = [
  20750. new THREE.Vector3( 1, 1, 1 ),
  20751. new THREE.Vector3( - 1, 1, 1 ),
  20752. new THREE.Vector3( - 1, - 1, 1 ),
  20753. new THREE.Vector3( 1, - 1, 1 ),
  20754. new THREE.Vector3( 1, 1, - 1 ),
  20755. new THREE.Vector3( - 1, 1, - 1 ),
  20756. new THREE.Vector3( - 1, - 1, - 1 ),
  20757. new THREE.Vector3( 1, - 1, - 1 )
  20758. ];
  20759. this.vertices = vertices;
  20760. // TODO: Wouldn't be nice if Line had .segments?
  20761. var geometry = new THREE.Geometry();
  20762. geometry.vertices.push(
  20763. vertices[ 0 ], vertices[ 1 ],
  20764. vertices[ 1 ], vertices[ 2 ],
  20765. vertices[ 2 ], vertices[ 3 ],
  20766. vertices[ 3 ], vertices[ 0 ],
  20767. vertices[ 4 ], vertices[ 5 ],
  20768. vertices[ 5 ], vertices[ 6 ],
  20769. vertices[ 6 ], vertices[ 7 ],
  20770. vertices[ 7 ], vertices[ 4 ],
  20771. vertices[ 0 ], vertices[ 4 ],
  20772. vertices[ 1 ], vertices[ 5 ],
  20773. vertices[ 2 ], vertices[ 6 ],
  20774. vertices[ 3 ], vertices[ 7 ]
  20775. );
  20776. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces );
  20777. if ( object !== undefined ) {
  20778. this.update( object );
  20779. }
  20780. };
  20781. THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype );
  20782. THREE.BoxHelper.prototype.update = function ( object ) {
  20783. var geometry = object.geometry;
  20784. if ( geometry.boundingBox === null ) {
  20785. geometry.computeBoundingBox();
  20786. }
  20787. var min = geometry.boundingBox.min;
  20788. var max = geometry.boundingBox.max;
  20789. var vertices = this.vertices;
  20790. vertices[ 0 ].set( max.x, max.y, max.z );
  20791. vertices[ 1 ].set( min.x, max.y, max.z );
  20792. vertices[ 2 ].set( min.x, min.y, max.z );
  20793. vertices[ 3 ].set( max.x, min.y, max.z );
  20794. vertices[ 4 ].set( max.x, max.y, min.z );
  20795. vertices[ 5 ].set( min.x, max.y, min.z );
  20796. vertices[ 6 ].set( min.x, min.y, min.z );
  20797. vertices[ 7 ].set( max.x, min.y, min.z );
  20798. this.geometry.computeBoundingSphere();
  20799. this.geometry.verticesNeedUpdate = true;
  20800. this.matrixAutoUpdate = false;
  20801. this.matrixWorld = object.matrixWorld;
  20802. };
  20803. /**
  20804. * @author WestLangley / http://github.com/WestLangley
  20805. */
  20806. // a helper to show the world-axis-aligned bounding box for an object
  20807. THREE.BoundingBoxHelper = function ( object, hex ) {
  20808. var color = hex || 0x888888;
  20809. this.object = object;
  20810. this.box = new THREE.Box3();
  20811. THREE.Mesh.call( this, new THREE.CubeGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  20812. };
  20813. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  20814. THREE.BoundingBoxHelper.prototype.update = function () {
  20815. this.box.setFromObject( this.object );
  20816. this.box.size( this.scale );
  20817. this.box.center( this.position );
  20818. };
  20819. /**
  20820. * @author alteredq / http://alteredqualia.com/
  20821. *
  20822. * - shows frustum, line of sight and up of the camera
  20823. * - suitable for fast updates
  20824. * - based on frustum visualization in lightgl.js shadowmap example
  20825. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20826. */
  20827. THREE.CameraHelper = function ( camera ) {
  20828. THREE.Line.call( this );
  20829. var geometry = new THREE.Geometry();
  20830. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20831. var pointMap = {};
  20832. // colors
  20833. var hexFrustum = 0xffaa00;
  20834. var hexCone = 0xff0000;
  20835. var hexUp = 0x00aaff;
  20836. var hexTarget = 0xffffff;
  20837. var hexCross = 0x333333;
  20838. // near
  20839. addLine( "n1", "n2", hexFrustum );
  20840. addLine( "n2", "n4", hexFrustum );
  20841. addLine( "n4", "n3", hexFrustum );
  20842. addLine( "n3", "n1", hexFrustum );
  20843. // far
  20844. addLine( "f1", "f2", hexFrustum );
  20845. addLine( "f2", "f4", hexFrustum );
  20846. addLine( "f4", "f3", hexFrustum );
  20847. addLine( "f3", "f1", hexFrustum );
  20848. // sides
  20849. addLine( "n1", "f1", hexFrustum );
  20850. addLine( "n2", "f2", hexFrustum );
  20851. addLine( "n3", "f3", hexFrustum );
  20852. addLine( "n4", "f4", hexFrustum );
  20853. // cone
  20854. addLine( "p", "n1", hexCone );
  20855. addLine( "p", "n2", hexCone );
  20856. addLine( "p", "n3", hexCone );
  20857. addLine( "p", "n4", hexCone );
  20858. // up
  20859. addLine( "u1", "u2", hexUp );
  20860. addLine( "u2", "u3", hexUp );
  20861. addLine( "u3", "u1", hexUp );
  20862. // target
  20863. addLine( "c", "t", hexTarget );
  20864. addLine( "p", "c", hexCross );
  20865. // cross
  20866. addLine( "cn1", "cn2", hexCross );
  20867. addLine( "cn3", "cn4", hexCross );
  20868. addLine( "cf1", "cf2", hexCross );
  20869. addLine( "cf3", "cf4", hexCross );
  20870. function addLine( a, b, hex ) {
  20871. addPoint( a, hex );
  20872. addPoint( b, hex );
  20873. }
  20874. function addPoint( id, hex ) {
  20875. geometry.vertices.push( new THREE.Vector3() );
  20876. geometry.colors.push( new THREE.Color( hex ) );
  20877. if ( pointMap[ id ] === undefined ) {
  20878. pointMap[ id ] = [];
  20879. }
  20880. pointMap[ id ].push( geometry.vertices.length - 1 );
  20881. }
  20882. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20883. this.camera = camera;
  20884. this.matrixWorld = camera.matrixWorld;
  20885. this.matrixAutoUpdate = false;
  20886. this.pointMap = pointMap;
  20887. this.update();
  20888. };
  20889. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20890. THREE.CameraHelper.prototype.update = function () {
  20891. var vector = new THREE.Vector3();
  20892. var camera = new THREE.Camera();
  20893. var projector = new THREE.Projector();
  20894. return function () {
  20895. var scope = this;
  20896. var w = 1, h = 1;
  20897. // we need just camera projection matrix
  20898. // world matrix must be identity
  20899. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  20900. // center / target
  20901. setPoint( "c", 0, 0, -1 );
  20902. setPoint( "t", 0, 0, 1 );
  20903. // near
  20904. setPoint( "n1", -w, -h, -1 );
  20905. setPoint( "n2", w, -h, -1 );
  20906. setPoint( "n3", -w, h, -1 );
  20907. setPoint( "n4", w, h, -1 );
  20908. // far
  20909. setPoint( "f1", -w, -h, 1 );
  20910. setPoint( "f2", w, -h, 1 );
  20911. setPoint( "f3", -w, h, 1 );
  20912. setPoint( "f4", w, h, 1 );
  20913. // up
  20914. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  20915. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  20916. setPoint( "u3", 0, h * 2, -1 );
  20917. // cross
  20918. setPoint( "cf1", -w, 0, 1 );
  20919. setPoint( "cf2", w, 0, 1 );
  20920. setPoint( "cf3", 0, -h, 1 );
  20921. setPoint( "cf4", 0, h, 1 );
  20922. setPoint( "cn1", -w, 0, -1 );
  20923. setPoint( "cn2", w, 0, -1 );
  20924. setPoint( "cn3", 0, -h, -1 );
  20925. setPoint( "cn4", 0, h, -1 );
  20926. function setPoint( point, x, y, z ) {
  20927. vector.set( x, y, z );
  20928. projector.unprojectVector( vector, camera );
  20929. var points = scope.pointMap[ point ];
  20930. if ( points !== undefined ) {
  20931. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20932. scope.geometry.vertices[ points[ i ] ].copy( vector );
  20933. }
  20934. }
  20935. }
  20936. this.geometry.verticesNeedUpdate = true;
  20937. };
  20938. }();
  20939. /**
  20940. * @author alteredq / http://alteredqualia.com/
  20941. * @author mrdoob / http://mrdoob.com/
  20942. */
  20943. THREE.DirectionalLightHelper = function ( light, sphereSize ) {
  20944. THREE.Object3D.call( this );
  20945. this.matrixAutoUpdate = false;
  20946. this.light = light;
  20947. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20948. var material = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  20949. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20950. this.lightSphere = new THREE.Mesh( geometry, material );
  20951. this.lightSphere.matrixWorld = this.light.matrixWorld;
  20952. this.lightSphere.matrixAutoUpdate = false;
  20953. this.add( this.lightSphere );
  20954. /*
  20955. this.targetSphere = new THREE.Mesh( geometry, material );
  20956. this.targetSphere.position = this.light.target.position;
  20957. this.add( this.targetSphere );
  20958. */
  20959. geometry = new THREE.Geometry();
  20960. geometry.vertices.push( this.light.position );
  20961. geometry.vertices.push( this.light.target.position );
  20962. geometry.computeLineDistances();
  20963. material = new THREE.LineDashedMaterial( { dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20964. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20965. this.targetLine = new THREE.Line( geometry, material );
  20966. this.add( this.targetLine );
  20967. }
  20968. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20969. THREE.DirectionalLightHelper.prototype.update = function () {
  20970. this.lightSphere.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20971. this.targetLine.geometry.computeLineDistances();
  20972. this.targetLine.geometry.verticesNeedUpdate = true;
  20973. this.targetLine.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20974. };
  20975. /**
  20976. * @author mrdoob / http://mrdoob.com/
  20977. * @author WestLangley / http://github.com/WestLangley
  20978. */
  20979. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  20980. this.object = object;
  20981. this.size = size || 1;
  20982. var color = hex || 0xffff00;
  20983. var width = linewidth || 1;
  20984. var geometry = new THREE.Geometry();
  20985. var faces = this.object.geometry.faces;
  20986. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20987. geometry.vertices.push( new THREE.Vector3() );
  20988. geometry.vertices.push( new THREE.Vector3() );
  20989. }
  20990. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20991. this.matrixAutoUpdate = false;
  20992. this.normalMatrix = new THREE.Matrix3();
  20993. this.update();
  20994. };
  20995. THREE.FaceNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20996. THREE.FaceNormalsHelper.prototype.update = ( function ( object ) {
  20997. var v1 = new THREE.Vector3();
  20998. return function( object ) {
  20999. this.object.updateMatrixWorld( true );
  21000. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  21001. var vertices = this.geometry.vertices;
  21002. var faces = this.object.geometry.faces;
  21003. var worldMatrix = this.object.matrixWorld;
  21004. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21005. var face = faces[ i ];
  21006. v1.copy( face.normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  21007. var idx = 2 * i;
  21008. vertices[ idx ].copy( face.centroid ).applyMatrix4( worldMatrix );
  21009. vertices[ idx + 1 ].addVectors( vertices[ idx ], v1 );
  21010. }
  21011. this.geometry.verticesNeedUpdate = true;
  21012. return this;
  21013. }
  21014. }());
  21015. /**
  21016. * @author mrdoob / http://mrdoob.com/
  21017. */
  21018. THREE.GridHelper = function ( size, step ) {
  21019. var geometry = new THREE.Geometry();
  21020. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  21021. this.color1 = new THREE.Color( 0x444444 );
  21022. this.color2 = new THREE.Color( 0x888888 );
  21023. for ( var i = - size; i <= size; i += step ) {
  21024. geometry.vertices.push(
  21025. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  21026. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  21027. );
  21028. var color = i === 0 ? this.color1 : this.color2;
  21029. geometry.colors.push( color, color, color, color );
  21030. }
  21031. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  21032. };
  21033. THREE.GridHelper.prototype = Object.create( THREE.Line.prototype );
  21034. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  21035. this.color1.set( colorCenterLine );
  21036. this.color2.set( colorGrid );
  21037. this.geometry.colorsNeedUpdate = true;
  21038. }
  21039. /**
  21040. * @author alteredq / http://alteredqualia.com/
  21041. * @author mrdoob / http://mrdoob.com/
  21042. */
  21043. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  21044. THREE.Object3D.call( this );
  21045. this.light = light;
  21046. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  21047. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  21048. for ( var i = 0, il = 8; i < il; i ++ ) {
  21049. geometry.faces[ i ].materialIndex = i < 4 ? 0 : 1;
  21050. }
  21051. var materialSky = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  21052. materialSky.color.copy( light.color ).multiplyScalar( light.intensity );
  21053. var materialGround = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  21054. materialGround.color.copy( light.groundColor ).multiplyScalar( light.intensity );
  21055. this.lightSphere = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( [ materialSky, materialGround ] ) );
  21056. this.lightSphere.position = light.position;
  21057. this.lightSphere.lookAt( new THREE.Vector3() );
  21058. this.add( this.lightSphere );
  21059. };
  21060. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  21061. THREE.HemisphereLightHelper.prototype.update = function () {
  21062. this.lightSphere.lookAt( new THREE.Vector3() );
  21063. this.lightSphere.material.materials[ 0 ].color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21064. this.lightSphere.material.materials[ 1 ].color.copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  21065. };
  21066. /**
  21067. * @author alteredq / http://alteredqualia.com/
  21068. * @author mrdoob / http://mrdoob.com/
  21069. */
  21070. THREE.PointLightHelper = function ( light, sphereSize ) {
  21071. THREE.Object3D.call( this );
  21072. this.matrixAutoUpdate = false;
  21073. this.light = light;
  21074. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  21075. var material = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  21076. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21077. this.lightSphere = new THREE.Mesh( geometry, material );
  21078. this.lightSphere.matrixWorld = this.light.matrixWorld;
  21079. this.lightSphere.matrixAutoUpdate = false;
  21080. this.add( this.lightSphere );
  21081. /*
  21082. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  21083. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  21084. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  21085. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  21086. var d = light.distance;
  21087. if ( d === 0.0 ) {
  21088. this.lightDistance.visible = false;
  21089. } else {
  21090. this.lightDistance.scale.set( d, d, d );
  21091. }
  21092. this.add( this.lightDistance );
  21093. */
  21094. };
  21095. THREE.PointLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  21096. THREE.PointLightHelper.prototype.update = function () {
  21097. this.lightSphere.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21098. /*
  21099. this.lightDistance.material.color.copy( this.color );
  21100. var d = this.light.distance;
  21101. if ( d === 0.0 ) {
  21102. this.lightDistance.visible = false;
  21103. } else {
  21104. this.lightDistance.visible = true;
  21105. this.lightDistance.scale.set( d, d, d );
  21106. }
  21107. */
  21108. };
  21109. /**
  21110. * @author alteredq / http://alteredqualia.com/
  21111. * @author mrdoob / http://mrdoob.com/
  21112. * @author WestLangley / http://github.com/WestLangley
  21113. */
  21114. THREE.SpotLightHelper = function ( light ) {
  21115. // spotlight helper must be a child of the scene
  21116. this.light = light;
  21117. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  21118. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, -0.5, 0 ) );
  21119. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  21120. var material = new THREE.MeshBasicMaterial( { wireframe: true, opacity: 0.3, transparent: true } );
  21121. THREE.Mesh.call( this, geometry, material );
  21122. this.update();
  21123. };
  21124. THREE.SpotLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  21125. THREE.SpotLightHelper.prototype.update = ( function () {
  21126. var targetPosition = new THREE.Vector3();
  21127. return function() {
  21128. var coneLength = this.light.distance ? this.light.distance : 10000;
  21129. var coneWidth = coneLength * Math.tan( this.light.angle );
  21130. this.scale.set( coneWidth, coneWidth, coneLength );
  21131. this.light.updateMatrixWorld( true );
  21132. this.position.getPositionFromMatrix( this.light.matrixWorld );
  21133. this.light.target.updateMatrixWorld( true );
  21134. targetPosition.getPositionFromMatrix( this.light.target.matrixWorld );
  21135. this.lookAt( targetPosition );
  21136. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21137. }
  21138. }());
  21139. /**
  21140. * @author mrdoob / http://mrdoob.com/
  21141. * @author WestLangley / http://github.com/WestLangley
  21142. */
  21143. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  21144. this.object = object;
  21145. this.size = size || 1;
  21146. var color = hex || 0xff0000;
  21147. var width = linewidth || 1;
  21148. var geometry = new THREE.Geometry();
  21149. var vertices = object.geometry.vertices;
  21150. var faces = object.geometry.faces;
  21151. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21152. var face = faces[ i ];
  21153. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  21154. geometry.vertices.push( new THREE.Vector3() );
  21155. geometry.vertices.push( new THREE.Vector3() );
  21156. }
  21157. }
  21158. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21159. this.matrixAutoUpdate = false;
  21160. this.normalMatrix = new THREE.Matrix3();
  21161. this.update();
  21162. };
  21163. THREE.VertexNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  21164. THREE.VertexNormalsHelper.prototype.update = ( function ( object ) {
  21165. var v1 = new THREE.Vector3();
  21166. return function( object ) {
  21167. var keys = [ 'a', 'b', 'c', 'd' ];
  21168. this.object.updateMatrixWorld( true );
  21169. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  21170. var vertices = this.geometry.vertices;
  21171. var verts = this.object.geometry.vertices;
  21172. var faces = this.object.geometry.faces;
  21173. var worldMatrix = this.object.matrixWorld;
  21174. var idx = 0;
  21175. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21176. var face = faces[ i ];
  21177. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  21178. var vertexId = face[ keys[ j ] ];
  21179. var vertex = verts[ vertexId ];
  21180. var normal = face.vertexNormals[ j ];
  21181. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  21182. v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  21183. v1.add( vertices[ idx ] );
  21184. idx = idx + 1;
  21185. vertices[ idx ].copy( v1 );
  21186. idx = idx + 1;
  21187. }
  21188. }
  21189. this.geometry.verticesNeedUpdate = true;
  21190. return this;
  21191. }
  21192. }());
  21193. /**
  21194. * @author mrdoob / http://mrdoob.com/
  21195. * @author WestLangley / http://github.com/WestLangley
  21196. */
  21197. THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) {
  21198. this.object = object;
  21199. this.size = size || 1;
  21200. var color = hex || 0x0000ff;
  21201. var width = linewidth || 1;
  21202. var geometry = new THREE.Geometry();
  21203. var vertices = object.geometry.vertices;
  21204. var faces = object.geometry.faces;
  21205. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21206. var face = faces[ i ];
  21207. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  21208. geometry.vertices.push( new THREE.Vector3() );
  21209. geometry.vertices.push( new THREE.Vector3() );
  21210. }
  21211. }
  21212. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21213. this.matrixAutoUpdate = false;
  21214. this.update();
  21215. };
  21216. THREE.VertexTangentsHelper.prototype = Object.create( THREE.Line.prototype );
  21217. THREE.VertexTangentsHelper.prototype.update = ( function ( object ) {
  21218. var v1 = new THREE.Vector3();
  21219. return function( object ) {
  21220. var keys = [ 'a', 'b', 'c', 'd' ];
  21221. this.object.updateMatrixWorld( true );
  21222. var vertices = this.geometry.vertices;
  21223. var verts = this.object.geometry.vertices;
  21224. var faces = this.object.geometry.faces;
  21225. var worldMatrix = this.object.matrixWorld;
  21226. var idx = 0;
  21227. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21228. var face = faces[ i ];
  21229. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  21230. var vertexId = face[ keys[ j ] ];
  21231. var vertex = verts[ vertexId ];
  21232. var tangent = face.vertexTangents[ j ];
  21233. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  21234. v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size );
  21235. v1.add( vertices[ idx ] );
  21236. idx = idx + 1;
  21237. vertices[ idx ].copy( v1 );
  21238. idx = idx + 1;
  21239. }
  21240. }
  21241. this.geometry.verticesNeedUpdate = true;
  21242. return this;
  21243. }
  21244. }());
  21245. /**
  21246. * @author mrdoob / http://mrdoob.com/
  21247. */
  21248. THREE.WireframeHelper = function ( object ) {
  21249. var edge = [ 0, 0 ], hash = {};
  21250. var sortFunction = function ( a, b ) { return a - b };
  21251. var keys = [ 'a', 'b', 'c', 'd' ];
  21252. var geometry = new THREE.Geometry();
  21253. var vertices = object.geometry.vertices;
  21254. var faces = object.geometry.faces;
  21255. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21256. var face = faces[ i ];
  21257. var length = face instanceof THREE.Face4 ? 4 : 3;
  21258. for ( var j = 0; j < length; j ++ ) {
  21259. edge[ 0 ] = face[ keys[ j ] ];
  21260. edge[ 1 ] = face[ keys[ ( j + 1 ) % length ] ];
  21261. edge.sort( sortFunction );
  21262. var key = edge.toString();
  21263. if ( hash[ key ] === undefined ) {
  21264. geometry.vertices.push( vertices[ edge[ 0 ] ] );
  21265. geometry.vertices.push( vertices[ edge[ 1 ] ] );
  21266. hash[ key ] = true;
  21267. }
  21268. }
  21269. }
  21270. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffffff } ), THREE.LinePieces );
  21271. this.matrixAutoUpdate = false;
  21272. this.matrixWorld = object.matrixWorld;
  21273. };
  21274. THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype );
  21275. /**
  21276. * @author alteredq / http://alteredqualia.com/
  21277. */
  21278. THREE.ImmediateRenderObject = function () {
  21279. THREE.Object3D.call( this );
  21280. this.render = function ( renderCallback ) { };
  21281. };
  21282. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  21283. /**
  21284. * @author mikael emtinger / http://gomo.se/
  21285. * @author alteredq / http://alteredqualia.com/
  21286. */
  21287. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  21288. THREE.Object3D.call( this );
  21289. this.lensFlares = [];
  21290. this.positionScreen = new THREE.Vector3();
  21291. this.customUpdateCallback = undefined;
  21292. if( texture !== undefined ) {
  21293. this.add( texture, size, distance, blending, color );
  21294. }
  21295. };
  21296. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  21297. /*
  21298. * Add: adds another flare
  21299. */
  21300. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  21301. if( size === undefined ) size = -1;
  21302. if( distance === undefined ) distance = 0;
  21303. if( opacity === undefined ) opacity = 1;
  21304. if( color === undefined ) color = new THREE.Color( 0xffffff );
  21305. if( blending === undefined ) blending = THREE.NormalBlending;
  21306. distance = Math.min( distance, Math.max( 0, distance ) );
  21307. this.lensFlares.push( { texture: texture, // THREE.Texture
  21308. size: size, // size in pixels (-1 = use texture.width)
  21309. distance: distance, // distance (0-1) from light source (0=at light source)
  21310. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  21311. scale: 1, // scale
  21312. rotation: 1, // rotation
  21313. opacity: opacity, // opacity
  21314. color: color, // color
  21315. blending: blending } ); // blending
  21316. };
  21317. /*
  21318. * Update lens flares update positions on all flares based on the screen position
  21319. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  21320. */
  21321. THREE.LensFlare.prototype.updateLensFlares = function () {
  21322. var f, fl = this.lensFlares.length;
  21323. var flare;
  21324. var vecX = -this.positionScreen.x * 2;
  21325. var vecY = -this.positionScreen.y * 2;
  21326. for( f = 0; f < fl; f ++ ) {
  21327. flare = this.lensFlares[ f ];
  21328. flare.x = this.positionScreen.x + vecX * flare.distance;
  21329. flare.y = this.positionScreen.y + vecY * flare.distance;
  21330. flare.wantedRotation = flare.x * Math.PI * 0.25;
  21331. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  21332. }
  21333. };
  21334. /**
  21335. * @author alteredq / http://alteredqualia.com/
  21336. */
  21337. THREE.MorphBlendMesh = function( geometry, material ) {
  21338. THREE.Mesh.call( this, geometry, material );
  21339. this.animationsMap = {};
  21340. this.animationsList = [];
  21341. // prepare default animation
  21342. // (all frames played together in 1 second)
  21343. var numFrames = this.geometry.morphTargets.length;
  21344. var name = "__default";
  21345. var startFrame = 0;
  21346. var endFrame = numFrames - 1;
  21347. var fps = numFrames / 1;
  21348. this.createAnimation( name, startFrame, endFrame, fps );
  21349. this.setAnimationWeight( name, 1 );
  21350. };
  21351. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  21352. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  21353. var animation = {
  21354. startFrame: start,
  21355. endFrame: end,
  21356. length: end - start + 1,
  21357. fps: fps,
  21358. duration: ( end - start ) / fps,
  21359. lastFrame: 0,
  21360. currentFrame: 0,
  21361. active: false,
  21362. time: 0,
  21363. direction: 1,
  21364. weight: 1,
  21365. directionBackwards: false,
  21366. mirroredLoop: false
  21367. };
  21368. this.animationsMap[ name ] = animation;
  21369. this.animationsList.push( animation );
  21370. };
  21371. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  21372. var pattern = /([a-z]+)(\d+)/;
  21373. var firstAnimation, frameRanges = {};
  21374. var geometry = this.geometry;
  21375. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  21376. var morph = geometry.morphTargets[ i ];
  21377. var chunks = morph.name.match( pattern );
  21378. if ( chunks && chunks.length > 1 ) {
  21379. var name = chunks[ 1 ];
  21380. var num = chunks[ 2 ];
  21381. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  21382. var range = frameRanges[ name ];
  21383. if ( i < range.start ) range.start = i;
  21384. if ( i > range.end ) range.end = i;
  21385. if ( ! firstAnimation ) firstAnimation = name;
  21386. }
  21387. }
  21388. for ( var name in frameRanges ) {
  21389. var range = frameRanges[ name ];
  21390. this.createAnimation( name, range.start, range.end, fps );
  21391. }
  21392. this.firstAnimation = firstAnimation;
  21393. };
  21394. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  21395. var animation = this.animationsMap[ name ];
  21396. if ( animation ) {
  21397. animation.direction = 1;
  21398. animation.directionBackwards = false;
  21399. }
  21400. };
  21401. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  21402. var animation = this.animationsMap[ name ];
  21403. if ( animation ) {
  21404. animation.direction = -1;
  21405. animation.directionBackwards = true;
  21406. }
  21407. };
  21408. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  21409. var animation = this.animationsMap[ name ];
  21410. if ( animation ) {
  21411. animation.fps = fps;
  21412. animation.duration = ( animation.end - animation.start ) / animation.fps;
  21413. }
  21414. };
  21415. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  21416. var animation = this.animationsMap[ name ];
  21417. if ( animation ) {
  21418. animation.duration = duration;
  21419. animation.fps = ( animation.end - animation.start ) / animation.duration;
  21420. }
  21421. };
  21422. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  21423. var animation = this.animationsMap[ name ];
  21424. if ( animation ) {
  21425. animation.weight = weight;
  21426. }
  21427. };
  21428. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  21429. var animation = this.animationsMap[ name ];
  21430. if ( animation ) {
  21431. animation.time = time;
  21432. }
  21433. };
  21434. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  21435. var time = 0;
  21436. var animation = this.animationsMap[ name ];
  21437. if ( animation ) {
  21438. time = animation.time;
  21439. }
  21440. return time;
  21441. };
  21442. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  21443. var duration = -1;
  21444. var animation = this.animationsMap[ name ];
  21445. if ( animation ) {
  21446. duration = animation.duration;
  21447. }
  21448. return duration;
  21449. };
  21450. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  21451. var animation = this.animationsMap[ name ];
  21452. if ( animation ) {
  21453. animation.time = 0;
  21454. animation.active = true;
  21455. } else {
  21456. console.warn( "animation[" + name + "] undefined" );
  21457. }
  21458. };
  21459. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  21460. var animation = this.animationsMap[ name ];
  21461. if ( animation ) {
  21462. animation.active = false;
  21463. }
  21464. };
  21465. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  21466. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  21467. var animation = this.animationsList[ i ];
  21468. if ( ! animation.active ) continue;
  21469. var frameTime = animation.duration / animation.length;
  21470. animation.time += animation.direction * delta;
  21471. if ( animation.mirroredLoop ) {
  21472. if ( animation.time > animation.duration || animation.time < 0 ) {
  21473. animation.direction *= -1;
  21474. if ( animation.time > animation.duration ) {
  21475. animation.time = animation.duration;
  21476. animation.directionBackwards = true;
  21477. }
  21478. if ( animation.time < 0 ) {
  21479. animation.time = 0;
  21480. animation.directionBackwards = false;
  21481. }
  21482. }
  21483. } else {
  21484. animation.time = animation.time % animation.duration;
  21485. if ( animation.time < 0 ) animation.time += animation.duration;
  21486. }
  21487. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  21488. var weight = animation.weight;
  21489. if ( keyframe !== animation.currentFrame ) {
  21490. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  21491. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  21492. this.morphTargetInfluences[ keyframe ] = 0;
  21493. animation.lastFrame = animation.currentFrame;
  21494. animation.currentFrame = keyframe;
  21495. }
  21496. var mix = ( animation.time % frameTime ) / frameTime;
  21497. if ( animation.directionBackwards ) mix = 1 - mix;
  21498. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  21499. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  21500. }
  21501. };
  21502. /**
  21503. * @author mikael emtinger / http://gomo.se/
  21504. * @author alteredq / http://alteredqualia.com/
  21505. */
  21506. THREE.LensFlarePlugin = function () {
  21507. var _gl, _renderer, _precision, _lensFlare = {};
  21508. this.init = function ( renderer ) {
  21509. _gl = renderer.context;
  21510. _renderer = renderer;
  21511. _precision = renderer.getPrecision();
  21512. _lensFlare.vertices = new Float32Array( 8 + 8 );
  21513. _lensFlare.faces = new Uint16Array( 6 );
  21514. var i = 0;
  21515. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  21516. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  21517. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  21518. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  21519. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21520. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21521. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  21522. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  21523. i = 0;
  21524. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  21525. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  21526. // buffers
  21527. _lensFlare.vertexBuffer = _gl.createBuffer();
  21528. _lensFlare.elementBuffer = _gl.createBuffer();
  21529. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21530. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  21531. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21532. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  21533. // textures
  21534. _lensFlare.tempTexture = _gl.createTexture();
  21535. _lensFlare.occlusionTexture = _gl.createTexture();
  21536. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21537. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  21538. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21539. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21540. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21541. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21542. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21543. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  21544. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21545. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21546. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21547. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21548. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  21549. _lensFlare.hasVertexTexture = false;
  21550. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  21551. } else {
  21552. _lensFlare.hasVertexTexture = true;
  21553. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  21554. }
  21555. _lensFlare.attributes = {};
  21556. _lensFlare.uniforms = {};
  21557. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  21558. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  21559. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  21560. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  21561. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  21562. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  21563. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  21564. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  21565. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  21566. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  21567. };
  21568. /*
  21569. * Render lens flares
  21570. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  21571. * reads these back and calculates occlusion.
  21572. * Then _lensFlare.update_lensFlares() is called to re-position and
  21573. * update transparency of flares. Then they are rendered.
  21574. *
  21575. */
  21576. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21577. var flares = scene.__webglFlares,
  21578. nFlares = flares.length;
  21579. if ( ! nFlares ) return;
  21580. var tempPosition = new THREE.Vector3();
  21581. var invAspect = viewportHeight / viewportWidth,
  21582. halfViewportWidth = viewportWidth * 0.5,
  21583. halfViewportHeight = viewportHeight * 0.5;
  21584. var size = 16 / viewportHeight,
  21585. scale = new THREE.Vector2( size * invAspect, size );
  21586. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  21587. screenPositionPixels = new THREE.Vector2( 1, 1 );
  21588. var uniforms = _lensFlare.uniforms,
  21589. attributes = _lensFlare.attributes;
  21590. // set _lensFlare program and reset blending
  21591. _gl.useProgram( _lensFlare.program );
  21592. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  21593. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  21594. // loop through all lens flares to update their occlusion and positions
  21595. // setup gl and common used attribs/unforms
  21596. _gl.uniform1i( uniforms.occlusionMap, 0 );
  21597. _gl.uniform1i( uniforms.map, 1 );
  21598. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21599. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21600. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21601. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21602. _gl.disable( _gl.CULL_FACE );
  21603. _gl.depthMask( false );
  21604. var i, j, jl, flare, sprite;
  21605. for ( i = 0; i < nFlares; i ++ ) {
  21606. size = 16 / viewportHeight;
  21607. scale.set( size * invAspect, size );
  21608. // calc object screen position
  21609. flare = flares[ i ];
  21610. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  21611. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  21612. tempPosition.applyProjection( camera.projectionMatrix );
  21613. // setup arrays for gl programs
  21614. screenPosition.copy( tempPosition )
  21615. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  21616. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  21617. // screen cull
  21618. if ( _lensFlare.hasVertexTexture || (
  21619. screenPositionPixels.x > 0 &&
  21620. screenPositionPixels.x < viewportWidth &&
  21621. screenPositionPixels.y > 0 &&
  21622. screenPositionPixels.y < viewportHeight ) ) {
  21623. // save current RGB to temp texture
  21624. _gl.activeTexture( _gl.TEXTURE1 );
  21625. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21626. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21627. // render pink quad
  21628. _gl.uniform1i( uniforms.renderType, 0 );
  21629. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21630. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21631. _gl.disable( _gl.BLEND );
  21632. _gl.enable( _gl.DEPTH_TEST );
  21633. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21634. // copy result to occlusionMap
  21635. _gl.activeTexture( _gl.TEXTURE0 );
  21636. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21637. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21638. // restore graphics
  21639. _gl.uniform1i( uniforms.renderType, 1 );
  21640. _gl.disable( _gl.DEPTH_TEST );
  21641. _gl.activeTexture( _gl.TEXTURE1 );
  21642. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21643. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21644. // update object positions
  21645. flare.positionScreen.copy( screenPosition )
  21646. if ( flare.customUpdateCallback ) {
  21647. flare.customUpdateCallback( flare );
  21648. } else {
  21649. flare.updateLensFlares();
  21650. }
  21651. // render flares
  21652. _gl.uniform1i( uniforms.renderType, 2 );
  21653. _gl.enable( _gl.BLEND );
  21654. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21655. sprite = flare.lensFlares[ j ];
  21656. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21657. screenPosition.x = sprite.x;
  21658. screenPosition.y = sprite.y;
  21659. screenPosition.z = sprite.z;
  21660. size = sprite.size * sprite.scale / viewportHeight;
  21661. scale.x = size * invAspect;
  21662. scale.y = size;
  21663. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21664. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21665. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21666. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21667. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21668. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21669. _renderer.setTexture( sprite.texture, 1 );
  21670. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21671. }
  21672. }
  21673. }
  21674. }
  21675. // restore gl
  21676. _gl.enable( _gl.CULL_FACE );
  21677. _gl.enable( _gl.DEPTH_TEST );
  21678. _gl.depthMask( true );
  21679. };
  21680. function createProgram ( shader, precision ) {
  21681. var program = _gl.createProgram();
  21682. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21683. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21684. var prefix = "precision " + precision + " float;\n";
  21685. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21686. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21687. _gl.compileShader( fragmentShader );
  21688. _gl.compileShader( vertexShader );
  21689. _gl.attachShader( program, fragmentShader );
  21690. _gl.attachShader( program, vertexShader );
  21691. _gl.linkProgram( program );
  21692. return program;
  21693. };
  21694. };
  21695. /**
  21696. * @author alteredq / http://alteredqualia.com/
  21697. */
  21698. THREE.ShadowMapPlugin = function () {
  21699. var _gl,
  21700. _renderer,
  21701. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21702. _frustum = new THREE.Frustum(),
  21703. _projScreenMatrix = new THREE.Matrix4(),
  21704. _min = new THREE.Vector3(),
  21705. _max = new THREE.Vector3(),
  21706. _matrixPosition = new THREE.Vector3();
  21707. this.init = function ( renderer ) {
  21708. _gl = renderer.context;
  21709. _renderer = renderer;
  21710. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21711. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21712. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21713. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21714. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21715. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21716. _depthMaterial._shadowPass = true;
  21717. _depthMaterialMorph._shadowPass = true;
  21718. _depthMaterialSkin._shadowPass = true;
  21719. _depthMaterialMorphSkin._shadowPass = true;
  21720. };
  21721. this.render = function ( scene, camera ) {
  21722. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21723. this.update( scene, camera );
  21724. };
  21725. this.update = function ( scene, camera ) {
  21726. var i, il, j, jl, n,
  21727. shadowMap, shadowMatrix, shadowCamera,
  21728. program, buffer, material,
  21729. webglObject, object, light,
  21730. renderList,
  21731. lights = [],
  21732. k = 0,
  21733. fog = null;
  21734. // set GL state for depth map
  21735. _gl.clearColor( 1, 1, 1, 1 );
  21736. _gl.disable( _gl.BLEND );
  21737. _gl.enable( _gl.CULL_FACE );
  21738. _gl.frontFace( _gl.CCW );
  21739. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21740. _gl.cullFace( _gl.FRONT );
  21741. } else {
  21742. _gl.cullFace( _gl.BACK );
  21743. }
  21744. _renderer.setDepthTest( true );
  21745. // preprocess lights
  21746. // - skip lights that are not casting shadows
  21747. // - create virtual lights for cascaded shadow maps
  21748. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21749. light = scene.__lights[ i ];
  21750. if ( ! light.castShadow ) continue;
  21751. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21752. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21753. var virtualLight;
  21754. if ( ! light.shadowCascadeArray[ n ] ) {
  21755. virtualLight = createVirtualLight( light, n );
  21756. virtualLight.originalCamera = camera;
  21757. var gyro = new THREE.Gyroscope();
  21758. gyro.position = light.shadowCascadeOffset;
  21759. gyro.add( virtualLight );
  21760. gyro.add( virtualLight.target );
  21761. camera.add( gyro );
  21762. light.shadowCascadeArray[ n ] = virtualLight;
  21763. console.log( "Created virtualLight", virtualLight );
  21764. } else {
  21765. virtualLight = light.shadowCascadeArray[ n ];
  21766. }
  21767. updateVirtualLight( light, n );
  21768. lights[ k ] = virtualLight;
  21769. k ++;
  21770. }
  21771. } else {
  21772. lights[ k ] = light;
  21773. k ++;
  21774. }
  21775. }
  21776. // render depth map
  21777. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21778. light = lights[ i ];
  21779. if ( ! light.shadowMap ) {
  21780. var shadowFilter = THREE.LinearFilter;
  21781. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  21782. shadowFilter = THREE.NearestFilter;
  21783. }
  21784. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  21785. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21786. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21787. light.shadowMatrix = new THREE.Matrix4();
  21788. }
  21789. if ( ! light.shadowCamera ) {
  21790. if ( light instanceof THREE.SpotLight ) {
  21791. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21792. } else if ( light instanceof THREE.DirectionalLight ) {
  21793. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21794. } else {
  21795. console.error( "Unsupported light type for shadow" );
  21796. continue;
  21797. }
  21798. scene.add( light.shadowCamera );
  21799. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21800. }
  21801. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21802. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21803. light.shadowCamera.add( light.cameraHelper );
  21804. }
  21805. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21806. updateShadowCamera( camera, light );
  21807. }
  21808. shadowMap = light.shadowMap;
  21809. shadowMatrix = light.shadowMatrix;
  21810. shadowCamera = light.shadowCamera;
  21811. shadowCamera.position.getPositionFromMatrix( light.matrixWorld );
  21812. _matrixPosition.getPositionFromMatrix( light.target.matrixWorld );
  21813. shadowCamera.lookAt( _matrixPosition );
  21814. shadowCamera.updateMatrixWorld();
  21815. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21816. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  21817. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21818. // compute shadow matrix
  21819. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21820. 0.0, 0.5, 0.0, 0.5,
  21821. 0.0, 0.0, 0.5, 0.5,
  21822. 0.0, 0.0, 0.0, 1.0 );
  21823. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  21824. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  21825. // update camera matrices and frustum
  21826. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21827. _frustum.setFromMatrix( _projScreenMatrix );
  21828. // render shadow map
  21829. _renderer.setRenderTarget( shadowMap );
  21830. _renderer.clear();
  21831. // set object matrices & frustum culling
  21832. renderList = scene.__webglObjects;
  21833. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21834. webglObject = renderList[ j ];
  21835. object = webglObject.object;
  21836. webglObject.render = false;
  21837. if ( object.visible && object.castShadow ) {
  21838. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21839. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21840. webglObject.render = true;
  21841. }
  21842. }
  21843. }
  21844. // render regular objects
  21845. var objectMaterial, useMorphing, useSkinning;
  21846. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21847. webglObject = renderList[ j ];
  21848. if ( webglObject.render ) {
  21849. object = webglObject.object;
  21850. buffer = webglObject.buffer;
  21851. // culling is overriden globally for all objects
  21852. // while rendering depth map
  21853. // need to deal with MeshFaceMaterial somehow
  21854. // in that case just use the first of material.materials for now
  21855. // (proper solution would require to break objects by materials
  21856. // similarly to regular rendering and then set corresponding
  21857. // depth materials per each chunk instead of just once per object)
  21858. objectMaterial = getObjectMaterial( object );
  21859. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21860. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21861. if ( object.customDepthMaterial ) {
  21862. material = object.customDepthMaterial;
  21863. } else if ( useSkinning ) {
  21864. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21865. } else if ( useMorphing ) {
  21866. material = _depthMaterialMorph;
  21867. } else {
  21868. material = _depthMaterial;
  21869. }
  21870. if ( buffer instanceof THREE.BufferGeometry ) {
  21871. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21872. } else {
  21873. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21874. }
  21875. }
  21876. }
  21877. // set matrices and render immediate objects
  21878. renderList = scene.__webglObjectsImmediate;
  21879. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21880. webglObject = renderList[ j ];
  21881. object = webglObject.object;
  21882. if ( object.visible && object.castShadow ) {
  21883. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21884. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21885. }
  21886. }
  21887. }
  21888. // restore GL state
  21889. var clearColor = _renderer.getClearColor(),
  21890. clearAlpha = _renderer.getClearAlpha();
  21891. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21892. _gl.enable( _gl.BLEND );
  21893. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21894. _gl.cullFace( _gl.BACK );
  21895. }
  21896. };
  21897. function createVirtualLight( light, cascade ) {
  21898. var virtualLight = new THREE.DirectionalLight();
  21899. virtualLight.isVirtual = true;
  21900. virtualLight.onlyShadow = true;
  21901. virtualLight.castShadow = true;
  21902. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21903. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21904. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21905. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21906. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21907. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21908. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21909. virtualLight.shadowDarkness = light.shadowDarkness;
  21910. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21911. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21912. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21913. virtualLight.pointsWorld = [];
  21914. virtualLight.pointsFrustum = [];
  21915. var pointsWorld = virtualLight.pointsWorld,
  21916. pointsFrustum = virtualLight.pointsFrustum;
  21917. for ( var i = 0; i < 8; i ++ ) {
  21918. pointsWorld[ i ] = new THREE.Vector3();
  21919. pointsFrustum[ i ] = new THREE.Vector3();
  21920. }
  21921. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21922. var farZ = light.shadowCascadeFarZ[ cascade ];
  21923. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21924. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21925. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21926. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21927. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21928. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21929. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21930. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21931. return virtualLight;
  21932. }
  21933. // Synchronize virtual light with the original light
  21934. function updateVirtualLight( light, cascade ) {
  21935. var virtualLight = light.shadowCascadeArray[ cascade ];
  21936. virtualLight.position.copy( light.position );
  21937. virtualLight.target.position.copy( light.target.position );
  21938. virtualLight.lookAt( virtualLight.target );
  21939. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21940. virtualLight.shadowDarkness = light.shadowDarkness;
  21941. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21942. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21943. var farZ = light.shadowCascadeFarZ[ cascade ];
  21944. var pointsFrustum = virtualLight.pointsFrustum;
  21945. pointsFrustum[ 0 ].z = nearZ;
  21946. pointsFrustum[ 1 ].z = nearZ;
  21947. pointsFrustum[ 2 ].z = nearZ;
  21948. pointsFrustum[ 3 ].z = nearZ;
  21949. pointsFrustum[ 4 ].z = farZ;
  21950. pointsFrustum[ 5 ].z = farZ;
  21951. pointsFrustum[ 6 ].z = farZ;
  21952. pointsFrustum[ 7 ].z = farZ;
  21953. }
  21954. // Fit shadow camera's ortho frustum to camera frustum
  21955. function updateShadowCamera( camera, light ) {
  21956. var shadowCamera = light.shadowCamera,
  21957. pointsFrustum = light.pointsFrustum,
  21958. pointsWorld = light.pointsWorld;
  21959. _min.set( Infinity, Infinity, Infinity );
  21960. _max.set( -Infinity, -Infinity, -Infinity );
  21961. for ( var i = 0; i < 8; i ++ ) {
  21962. var p = pointsWorld[ i ];
  21963. p.copy( pointsFrustum[ i ] );
  21964. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21965. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  21966. if ( p.x < _min.x ) _min.x = p.x;
  21967. if ( p.x > _max.x ) _max.x = p.x;
  21968. if ( p.y < _min.y ) _min.y = p.y;
  21969. if ( p.y > _max.y ) _max.y = p.y;
  21970. if ( p.z < _min.z ) _min.z = p.z;
  21971. if ( p.z > _max.z ) _max.z = p.z;
  21972. }
  21973. shadowCamera.left = _min.x;
  21974. shadowCamera.right = _max.x;
  21975. shadowCamera.top = _max.y;
  21976. shadowCamera.bottom = _min.y;
  21977. // can't really fit near/far
  21978. //shadowCamera.near = _min.z;
  21979. //shadowCamera.far = _max.z;
  21980. shadowCamera.updateProjectionMatrix();
  21981. }
  21982. // For the moment just ignore objects that have multiple materials with different animation methods
  21983. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  21984. function getObjectMaterial( object ) {
  21985. return object.material instanceof THREE.MeshFaceMaterial
  21986. ? object.material.materials[ 0 ]
  21987. : object.material;
  21988. };
  21989. };
  21990. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21991. /**
  21992. * @author mikael emtinger / http://gomo.se/
  21993. * @author alteredq / http://alteredqualia.com/
  21994. */
  21995. THREE.SpritePlugin = function () {
  21996. var _gl, _renderer, _precision, _sprite = {};
  21997. this.init = function ( renderer ) {
  21998. _gl = renderer.context;
  21999. _renderer = renderer;
  22000. _precision = renderer.getPrecision();
  22001. _sprite.vertices = new Float32Array( 8 + 8 );
  22002. _sprite.faces = new Uint16Array( 6 );
  22003. var i = 0;
  22004. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  22005. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  22006. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  22007. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  22008. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  22009. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  22010. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  22011. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  22012. i = 0;
  22013. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  22014. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  22015. _sprite.vertexBuffer = _gl.createBuffer();
  22016. _sprite.elementBuffer = _gl.createBuffer();
  22017. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  22018. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  22019. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  22020. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  22021. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ], _precision );
  22022. _sprite.attributes = {};
  22023. _sprite.uniforms = {};
  22024. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  22025. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  22026. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  22027. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  22028. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  22029. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  22030. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  22031. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  22032. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  22033. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  22034. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  22035. _sprite.uniforms.sizeAttenuation = _gl.getUniformLocation( _sprite.program, "sizeAttenuation" );
  22036. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  22037. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  22038. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  22039. _sprite.uniforms.fogType = _gl.getUniformLocation( _sprite.program, "fogType" );
  22040. _sprite.uniforms.fogDensity = _gl.getUniformLocation( _sprite.program, "fogDensity" );
  22041. _sprite.uniforms.fogNear = _gl.getUniformLocation( _sprite.program, "fogNear" );
  22042. _sprite.uniforms.fogFar = _gl.getUniformLocation( _sprite.program, "fogFar" );
  22043. _sprite.uniforms.fogColor = _gl.getUniformLocation( _sprite.program, "fogColor" );
  22044. _sprite.uniforms.alphaTest = _gl.getUniformLocation( _sprite.program, "alphaTest" );
  22045. };
  22046. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  22047. var sprites = scene.__webglSprites,
  22048. nSprites = sprites.length;
  22049. if ( ! nSprites ) return;
  22050. var attributes = _sprite.attributes,
  22051. uniforms = _sprite.uniforms;
  22052. var invAspect = viewportHeight / viewportWidth;
  22053. var halfViewportWidth = viewportWidth * 0.5,
  22054. halfViewportHeight = viewportHeight * 0.5;
  22055. // setup gl
  22056. _gl.useProgram( _sprite.program );
  22057. _gl.enableVertexAttribArray( attributes.position );
  22058. _gl.enableVertexAttribArray( attributes.uv );
  22059. _gl.disable( _gl.CULL_FACE );
  22060. _gl.enable( _gl.BLEND );
  22061. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  22062. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  22063. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  22064. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  22065. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  22066. _gl.activeTexture( _gl.TEXTURE0 );
  22067. _gl.uniform1i( uniforms.map, 0 );
  22068. var oldFogType = 0;
  22069. var sceneFogType = 0;
  22070. var fog = scene.fog;
  22071. if ( fog ) {
  22072. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  22073. if ( fog instanceof THREE.Fog ) {
  22074. _gl.uniform1f( uniforms.fogNear, fog.near );
  22075. _gl.uniform1f( uniforms.fogFar, fog.far );
  22076. _gl.uniform1i( uniforms.fogType, 1 );
  22077. oldFogType = 1;
  22078. sceneFogType = 1;
  22079. } else if ( fog instanceof THREE.FogExp2 ) {
  22080. _gl.uniform1f( uniforms.fogDensity, fog.density );
  22081. _gl.uniform1i( uniforms.fogType, 2 );
  22082. oldFogType = 2;
  22083. sceneFogType = 2;
  22084. }
  22085. } else {
  22086. _gl.uniform1i( uniforms.fogType, 0 );
  22087. oldFogType = 0;
  22088. sceneFogType = 0;
  22089. }
  22090. // update positions and sort
  22091. var i, sprite, material, screenPosition, size, fogType, scale = [];
  22092. for( i = 0; i < nSprites; i ++ ) {
  22093. sprite = sprites[ i ];
  22094. material = sprite.material;
  22095. if ( ! sprite.visible || material.opacity === 0 ) continue;
  22096. if ( ! material.useScreenCoordinates ) {
  22097. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  22098. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  22099. } else {
  22100. sprite.z = - sprite.position.z;
  22101. }
  22102. }
  22103. sprites.sort( painterSortStable );
  22104. // render all sprites
  22105. for( i = 0; i < nSprites; i ++ ) {
  22106. sprite = sprites[ i ];
  22107. material = sprite.material;
  22108. if ( ! sprite.visible || material.opacity === 0 ) continue;
  22109. if ( material.map && material.map.image && material.map.image.width ) {
  22110. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  22111. if ( material.useScreenCoordinates === true ) {
  22112. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  22113. _gl.uniform3f(
  22114. uniforms.screenPosition,
  22115. ( ( sprite.position.x * _renderer.devicePixelRatio ) - halfViewportWidth ) / halfViewportWidth,
  22116. ( halfViewportHeight - ( sprite.position.y * _renderer.devicePixelRatio ) ) / halfViewportHeight,
  22117. Math.max( 0, Math.min( 1, sprite.position.z ) )
  22118. );
  22119. scale[ 0 ] = _renderer.devicePixelRatio;
  22120. scale[ 1 ] = _renderer.devicePixelRatio;
  22121. } else {
  22122. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  22123. _gl.uniform1i( uniforms.sizeAttenuation, material.sizeAttenuation ? 1 : 0 );
  22124. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  22125. scale[ 0 ] = 1;
  22126. scale[ 1 ] = 1;
  22127. }
  22128. if ( scene.fog && material.fog ) {
  22129. fogType = sceneFogType;
  22130. } else {
  22131. fogType = 0;
  22132. }
  22133. if ( oldFogType !== fogType ) {
  22134. _gl.uniform1i( uniforms.fogType, fogType );
  22135. oldFogType = fogType;
  22136. }
  22137. size = 1 / ( material.scaleByViewport ? viewportHeight : 1 );
  22138. scale[ 0 ] *= size * invAspect * sprite.scale.x
  22139. scale[ 1 ] *= size * sprite.scale.y;
  22140. _gl.uniform2f( uniforms.uvScale, material.uvScale.x, material.uvScale.y );
  22141. _gl.uniform2f( uniforms.uvOffset, material.uvOffset.x, material.uvOffset.y );
  22142. _gl.uniform2f( uniforms.alignment, material.alignment.x, material.alignment.y );
  22143. _gl.uniform1f( uniforms.opacity, material.opacity );
  22144. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  22145. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  22146. _gl.uniform2fv( uniforms.scale, scale );
  22147. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  22148. _renderer.setDepthTest( material.depthTest );
  22149. _renderer.setDepthWrite( material.depthWrite );
  22150. _renderer.setTexture( material.map, 0 );
  22151. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  22152. }
  22153. }
  22154. // restore gl
  22155. _gl.enable( _gl.CULL_FACE );
  22156. };
  22157. function createProgram ( shader, precision ) {
  22158. var program = _gl.createProgram();
  22159. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  22160. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  22161. var prefix = "precision " + precision + " float;\n";
  22162. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  22163. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  22164. _gl.compileShader( fragmentShader );
  22165. _gl.compileShader( vertexShader );
  22166. _gl.attachShader( program, fragmentShader );
  22167. _gl.attachShader( program, vertexShader );
  22168. _gl.linkProgram( program );
  22169. return program;
  22170. };
  22171. function painterSortStable ( a, b ) {
  22172. if ( a.z !== b.z ) {
  22173. return b.z - a.z;
  22174. } else {
  22175. return b.id - a.id;
  22176. }
  22177. };
  22178. };
  22179. /**
  22180. * @author alteredq / http://alteredqualia.com/
  22181. */
  22182. THREE.DepthPassPlugin = function () {
  22183. this.enabled = false;
  22184. this.renderTarget = null;
  22185. var _gl,
  22186. _renderer,
  22187. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  22188. _frustum = new THREE.Frustum(),
  22189. _projScreenMatrix = new THREE.Matrix4();
  22190. this.init = function ( renderer ) {
  22191. _gl = renderer.context;
  22192. _renderer = renderer;
  22193. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  22194. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  22195. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  22196. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  22197. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  22198. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  22199. _depthMaterial._shadowPass = true;
  22200. _depthMaterialMorph._shadowPass = true;
  22201. _depthMaterialSkin._shadowPass = true;
  22202. _depthMaterialMorphSkin._shadowPass = true;
  22203. };
  22204. this.render = function ( scene, camera ) {
  22205. if ( ! this.enabled ) return;
  22206. this.update( scene, camera );
  22207. };
  22208. this.update = function ( scene, camera ) {
  22209. var i, il, j, jl, n,
  22210. program, buffer, material,
  22211. webglObject, object, light,
  22212. renderList,
  22213. fog = null;
  22214. // set GL state for depth map
  22215. _gl.clearColor( 1, 1, 1, 1 );
  22216. _gl.disable( _gl.BLEND );
  22217. _renderer.setDepthTest( true );
  22218. // update scene
  22219. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  22220. // update camera matrices and frustum
  22221. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  22222. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  22223. _frustum.setFromMatrix( _projScreenMatrix );
  22224. // render depth map
  22225. _renderer.setRenderTarget( this.renderTarget );
  22226. _renderer.clear();
  22227. // set object matrices & frustum culling
  22228. renderList = scene.__webglObjects;
  22229. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22230. webglObject = renderList[ j ];
  22231. object = webglObject.object;
  22232. webglObject.render = false;
  22233. if ( object.visible ) {
  22234. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  22235. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  22236. webglObject.render = true;
  22237. }
  22238. }
  22239. }
  22240. // render regular objects
  22241. var objectMaterial, useMorphing, useSkinning;
  22242. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22243. webglObject = renderList[ j ];
  22244. if ( webglObject.render ) {
  22245. object = webglObject.object;
  22246. buffer = webglObject.buffer;
  22247. // todo: create proper depth material for particles
  22248. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  22249. objectMaterial = getObjectMaterial( object );
  22250. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  22251. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  22252. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  22253. if ( object.customDepthMaterial ) {
  22254. material = object.customDepthMaterial;
  22255. } else if ( useSkinning ) {
  22256. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  22257. } else if ( useMorphing ) {
  22258. material = _depthMaterialMorph;
  22259. } else {
  22260. material = _depthMaterial;
  22261. }
  22262. if ( buffer instanceof THREE.BufferGeometry ) {
  22263. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  22264. } else {
  22265. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  22266. }
  22267. }
  22268. }
  22269. // set matrices and render immediate objects
  22270. renderList = scene.__webglObjectsImmediate;
  22271. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22272. webglObject = renderList[ j ];
  22273. object = webglObject.object;
  22274. if ( object.visible ) {
  22275. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  22276. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  22277. }
  22278. }
  22279. // restore GL state
  22280. var clearColor = _renderer.getClearColor(),
  22281. clearAlpha = _renderer.getClearAlpha();
  22282. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  22283. _gl.enable( _gl.BLEND );
  22284. };
  22285. // For the moment just ignore objects that have multiple materials with different animation methods
  22286. // Only the first material will be taken into account for deciding which depth material to use
  22287. function getObjectMaterial( object ) {
  22288. return object.material instanceof THREE.MeshFaceMaterial
  22289. ? object.material.materials[ 0 ]
  22290. : object.material;
  22291. };
  22292. };
  22293. /**
  22294. * @author mikael emtinger / http://gomo.se/
  22295. */
  22296. THREE.ShaderFlares = {
  22297. 'lensFlareVertexTexture': {
  22298. vertexShader: [
  22299. "uniform lowp int renderType;",
  22300. "uniform vec3 screenPosition;",
  22301. "uniform vec2 scale;",
  22302. "uniform float rotation;",
  22303. "uniform sampler2D occlusionMap;",
  22304. "attribute vec2 position;",
  22305. "attribute vec2 uv;",
  22306. "varying vec2 vUV;",
  22307. "varying float vVisibility;",
  22308. "void main() {",
  22309. "vUV = uv;",
  22310. "vec2 pos = position;",
  22311. "if( renderType == 2 ) {",
  22312. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  22313. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  22314. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  22315. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  22316. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  22317. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  22318. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  22319. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  22320. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  22321. "vVisibility = visibility.r / 9.0;",
  22322. "vVisibility *= 1.0 - visibility.g / 9.0;",
  22323. "vVisibility *= visibility.b / 9.0;",
  22324. "vVisibility *= 1.0 - visibility.a / 9.0;",
  22325. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22326. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22327. "}",
  22328. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22329. "}"
  22330. ].join( "\n" ),
  22331. fragmentShader: [
  22332. "uniform lowp int renderType;",
  22333. "uniform sampler2D map;",
  22334. "uniform float opacity;",
  22335. "uniform vec3 color;",
  22336. "varying vec2 vUV;",
  22337. "varying float vVisibility;",
  22338. "void main() {",
  22339. // pink square
  22340. "if( renderType == 0 ) {",
  22341. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  22342. // restore
  22343. "} else if( renderType == 1 ) {",
  22344. "gl_FragColor = texture2D( map, vUV );",
  22345. // flare
  22346. "} else {",
  22347. "vec4 texture = texture2D( map, vUV );",
  22348. "texture.a *= opacity * vVisibility;",
  22349. "gl_FragColor = texture;",
  22350. "gl_FragColor.rgb *= color;",
  22351. "}",
  22352. "}"
  22353. ].join( "\n" )
  22354. },
  22355. 'lensFlare': {
  22356. vertexShader: [
  22357. "uniform lowp int renderType;",
  22358. "uniform vec3 screenPosition;",
  22359. "uniform vec2 scale;",
  22360. "uniform float rotation;",
  22361. "attribute vec2 position;",
  22362. "attribute vec2 uv;",
  22363. "varying vec2 vUV;",
  22364. "void main() {",
  22365. "vUV = uv;",
  22366. "vec2 pos = position;",
  22367. "if( renderType == 2 ) {",
  22368. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22369. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22370. "}",
  22371. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22372. "}"
  22373. ].join( "\n" ),
  22374. fragmentShader: [
  22375. "precision mediump float;",
  22376. "uniform lowp int renderType;",
  22377. "uniform sampler2D map;",
  22378. "uniform sampler2D occlusionMap;",
  22379. "uniform float opacity;",
  22380. "uniform vec3 color;",
  22381. "varying vec2 vUV;",
  22382. "void main() {",
  22383. // pink square
  22384. "if( renderType == 0 ) {",
  22385. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  22386. // restore
  22387. "} else if( renderType == 1 ) {",
  22388. "gl_FragColor = texture2D( map, vUV );",
  22389. // flare
  22390. "} else {",
  22391. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  22392. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  22393. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  22394. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  22395. "visibility = ( 1.0 - visibility / 4.0 );",
  22396. "vec4 texture = texture2D( map, vUV );",
  22397. "texture.a *= opacity * visibility;",
  22398. "gl_FragColor = texture;",
  22399. "gl_FragColor.rgb *= color;",
  22400. "}",
  22401. "}"
  22402. ].join( "\n" )
  22403. }
  22404. };
  22405. /**
  22406. * @author mikael emtinger / http://gomo.se/
  22407. * @author alteredq / http://alteredqualia.com/
  22408. *
  22409. */
  22410. THREE.ShaderSprite = {
  22411. 'sprite': {
  22412. vertexShader: [
  22413. "uniform int useScreenCoordinates;",
  22414. "uniform int sizeAttenuation;",
  22415. "uniform vec3 screenPosition;",
  22416. "uniform mat4 modelViewMatrix;",
  22417. "uniform mat4 projectionMatrix;",
  22418. "uniform float rotation;",
  22419. "uniform vec2 scale;",
  22420. "uniform vec2 alignment;",
  22421. "uniform vec2 uvOffset;",
  22422. "uniform vec2 uvScale;",
  22423. "attribute vec2 position;",
  22424. "attribute vec2 uv;",
  22425. "varying vec2 vUV;",
  22426. "void main() {",
  22427. "vUV = uvOffset + uv * uvScale;",
  22428. "vec2 alignedPosition = position + alignment;",
  22429. "vec2 rotatedPosition;",
  22430. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  22431. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  22432. "vec4 finalPosition;",
  22433. "if( useScreenCoordinates != 0 ) {",
  22434. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  22435. "} else {",
  22436. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  22437. "finalPosition.xy += rotatedPosition * ( sizeAttenuation == 1 ? 1.0 : finalPosition.z );",
  22438. "}",
  22439. "gl_Position = finalPosition;",
  22440. "}"
  22441. ].join( "\n" ),
  22442. fragmentShader: [
  22443. "uniform vec3 color;",
  22444. "uniform sampler2D map;",
  22445. "uniform float opacity;",
  22446. "uniform int fogType;",
  22447. "uniform vec3 fogColor;",
  22448. "uniform float fogDensity;",
  22449. "uniform float fogNear;",
  22450. "uniform float fogFar;",
  22451. "uniform float alphaTest;",
  22452. "varying vec2 vUV;",
  22453. "void main() {",
  22454. "vec4 texture = texture2D( map, vUV );",
  22455. "if ( texture.a < alphaTest ) discard;",
  22456. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  22457. "if ( fogType > 0 ) {",
  22458. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  22459. "float fogFactor = 0.0;",
  22460. "if ( fogType == 1 ) {",
  22461. "fogFactor = smoothstep( fogNear, fogFar, depth );",
  22462. "} else {",
  22463. "const float LOG2 = 1.442695;",
  22464. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  22465. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  22466. "}",
  22467. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  22468. "}",
  22469. "}"
  22470. ].join( "\n" )
  22471. }
  22472. };