three.js 820 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734
  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. String.prototype.trim = String.prototype.trim || function () {
  15. return this.replace( /^\s+|\s+$/g, '' );
  16. };
  17. // based on https://github.com/documentcloud/underscore/blob/bf657be243a075b5e72acc8a83e6f12a564d8f55/underscore.js#L767
  18. THREE.extend = function ( obj, source ) {
  19. // ECMAScript5 compatibility based on: http://www.nczonline.net/blog/2012/12/11/are-your-mixins-ecmascript-5-compatible/
  20. if ( Object.keys ) {
  21. var keys = Object.keys( source );
  22. for (var i = 0, il = keys.length; i < il; i++) {
  23. var prop = keys[i];
  24. Object.defineProperty( obj, prop, Object.getOwnPropertyDescriptor( source, prop ) );
  25. }
  26. } else {
  27. var safeHasOwnProperty = {}.hasOwnProperty;
  28. for ( var prop in source ) {
  29. if ( safeHasOwnProperty.call( source, prop ) ) {
  30. obj[prop] = source[prop];
  31. }
  32. }
  33. }
  34. return obj;
  35. };
  36. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  37. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  38. // requestAnimationFrame polyfill by Erik Möller
  39. // fixes from Paul Irish and Tino Zijdel
  40. // using 'self' instead of 'window' for compatibility with both NodeJS and IE10.
  41. ( function () {
  42. var lastTime = 0;
  43. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  44. for ( var x = 0; x < vendors.length && !self.requestAnimationFrame; ++ x ) {
  45. self.requestAnimationFrame = self[ vendors[ x ] + 'RequestAnimationFrame' ];
  46. self.cancelAnimationFrame = self[ vendors[ x ] + 'CancelAnimationFrame' ] || self[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  47. }
  48. if ( self.requestAnimationFrame === undefined && self['setTimeout'] !== undefined ) {
  49. self.requestAnimationFrame = function ( callback ) {
  50. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  51. var id = self.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  52. lastTime = currTime + timeToCall;
  53. return id;
  54. };
  55. }
  56. if( self.cancelAnimationFrame === undefined && self['clearTimeout'] !== undefined ) {
  57. self.cancelAnimationFrame = function ( id ) { self.clearTimeout( id ) };
  58. }
  59. }() );
  60. // GL STATE CONSTANTS
  61. THREE.CullFaceNone = 0;
  62. THREE.CullFaceBack = 1;
  63. THREE.CullFaceFront = 2;
  64. THREE.CullFaceFrontBack = 3;
  65. THREE.FrontFaceDirectionCW = 0;
  66. THREE.FrontFaceDirectionCCW = 1;
  67. // SHADOWING TYPES
  68. THREE.BasicShadowMap = 0;
  69. THREE.PCFShadowMap = 1;
  70. THREE.PCFSoftShadowMap = 2;
  71. // MATERIAL CONSTANTS
  72. // side
  73. THREE.FrontSide = 0;
  74. THREE.BackSide = 1;
  75. THREE.DoubleSide = 2;
  76. // shading
  77. THREE.NoShading = 0;
  78. THREE.FlatShading = 1;
  79. THREE.SmoothShading = 2;
  80. // colors
  81. THREE.NoColors = 0;
  82. THREE.FaceColors = 1;
  83. THREE.VertexColors = 2;
  84. // blending modes
  85. THREE.NoBlending = 0;
  86. THREE.NormalBlending = 1;
  87. THREE.AdditiveBlending = 2;
  88. THREE.SubtractiveBlending = 3;
  89. THREE.MultiplyBlending = 4;
  90. THREE.CustomBlending = 5;
  91. // custom blending equations
  92. // (numbers start from 100 not to clash with other
  93. // mappings to OpenGL constants defined in Texture.js)
  94. THREE.AddEquation = 100;
  95. THREE.SubtractEquation = 101;
  96. THREE.ReverseSubtractEquation = 102;
  97. // custom blending destination factors
  98. THREE.ZeroFactor = 200;
  99. THREE.OneFactor = 201;
  100. THREE.SrcColorFactor = 202;
  101. THREE.OneMinusSrcColorFactor = 203;
  102. THREE.SrcAlphaFactor = 204;
  103. THREE.OneMinusSrcAlphaFactor = 205;
  104. THREE.DstAlphaFactor = 206;
  105. THREE.OneMinusDstAlphaFactor = 207;
  106. // custom blending source factors
  107. //THREE.ZeroFactor = 200;
  108. //THREE.OneFactor = 201;
  109. //THREE.SrcAlphaFactor = 204;
  110. //THREE.OneMinusSrcAlphaFactor = 205;
  111. //THREE.DstAlphaFactor = 206;
  112. //THREE.OneMinusDstAlphaFactor = 207;
  113. THREE.DstColorFactor = 208;
  114. THREE.OneMinusDstColorFactor = 209;
  115. THREE.SrcAlphaSaturateFactor = 210;
  116. // TEXTURE CONSTANTS
  117. THREE.MultiplyOperation = 0;
  118. THREE.MixOperation = 1;
  119. THREE.AddOperation = 2;
  120. // Mapping modes
  121. THREE.UVMapping = function () {};
  122. THREE.CubeReflectionMapping = function () {};
  123. THREE.CubeRefractionMapping = function () {};
  124. THREE.SphericalReflectionMapping = function () {};
  125. THREE.SphericalRefractionMapping = function () {};
  126. // Wrapping modes
  127. THREE.RepeatWrapping = 1000;
  128. THREE.ClampToEdgeWrapping = 1001;
  129. THREE.MirroredRepeatWrapping = 1002;
  130. // Filters
  131. THREE.NearestFilter = 1003;
  132. THREE.NearestMipMapNearestFilter = 1004;
  133. THREE.NearestMipMapLinearFilter = 1005;
  134. THREE.LinearFilter = 1006;
  135. THREE.LinearMipMapNearestFilter = 1007;
  136. THREE.LinearMipMapLinearFilter = 1008;
  137. // Data types
  138. THREE.UnsignedByteType = 1009;
  139. THREE.ByteType = 1010;
  140. THREE.ShortType = 1011;
  141. THREE.UnsignedShortType = 1012;
  142. THREE.IntType = 1013;
  143. THREE.UnsignedIntType = 1014;
  144. THREE.FloatType = 1015;
  145. // Pixel types
  146. //THREE.UnsignedByteType = 1009;
  147. THREE.UnsignedShort4444Type = 1016;
  148. THREE.UnsignedShort5551Type = 1017;
  149. THREE.UnsignedShort565Type = 1018;
  150. // Pixel formats
  151. THREE.AlphaFormat = 1019;
  152. THREE.RGBFormat = 1020;
  153. THREE.RGBAFormat = 1021;
  154. THREE.LuminanceFormat = 1022;
  155. THREE.LuminanceAlphaFormat = 1023;
  156. // Compressed texture formats
  157. THREE.RGB_S3TC_DXT1_Format = 2001;
  158. THREE.RGBA_S3TC_DXT1_Format = 2002;
  159. THREE.RGBA_S3TC_DXT3_Format = 2003;
  160. THREE.RGBA_S3TC_DXT5_Format = 2004;
  161. /*
  162. // Potential future PVRTC compressed texture formats
  163. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  164. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  165. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  166. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  167. */
  168. /**
  169. * @author mrdoob / http://mrdoob.com/
  170. */
  171. THREE.Color = function ( value ) {
  172. if ( value !== undefined ) this.set( value );
  173. return this;
  174. };
  175. THREE.Color.prototype = {
  176. constructor: THREE.Color,
  177. r: 1, g: 1, b: 1,
  178. set: function ( value ) {
  179. if ( value instanceof THREE.Color ) {
  180. this.copy( value );
  181. } else if ( typeof value === 'number' ) {
  182. this.setHex( value );
  183. } else if ( typeof value === 'string' ) {
  184. this.setStyle( value );
  185. }
  186. return this;
  187. },
  188. setHex: function ( hex ) {
  189. hex = Math.floor( hex );
  190. this.r = ( hex >> 16 & 255 ) / 255;
  191. this.g = ( hex >> 8 & 255 ) / 255;
  192. this.b = ( hex & 255 ) / 255;
  193. return this;
  194. },
  195. setRGB: function ( r, g, b ) {
  196. this.r = r;
  197. this.g = g;
  198. this.b = b;
  199. return this;
  200. },
  201. setHSL: function ( h, s, l ) {
  202. // h,s,l ranges are in 0.0 - 1.0
  203. if ( s === 0 ) {
  204. this.r = this.g = this.b = l;
  205. } else {
  206. var hue2rgb = function ( p, q, t ) {
  207. if ( t < 0 ) t += 1;
  208. if ( t > 1 ) t -= 1;
  209. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  210. if ( t < 1 / 2 ) return q;
  211. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  212. return p;
  213. };
  214. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  215. var q = ( 2 * l ) - p;
  216. this.r = hue2rgb( q, p, h + 1 / 3 );
  217. this.g = hue2rgb( q, p, h );
  218. this.b = hue2rgb( q, p, h - 1 / 3 );
  219. }
  220. return this;
  221. },
  222. setStyle: function ( style ) {
  223. // rgb(255,0,0)
  224. if ( /^rgb\((\d+),(\d+),(\d+)\)$/i.test( style ) ) {
  225. var color = /^rgb\((\d+),(\d+),(\d+)\)$/i.exec( style );
  226. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  227. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  228. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  229. return this;
  230. }
  231. // rgb(100%,0%,0%)
  232. if ( /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.test( style ) ) {
  233. var color = /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.exec( style );
  234. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  235. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  236. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  237. return this;
  238. }
  239. // #ff0000
  240. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  241. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  242. this.setHex( parseInt( color[ 1 ], 16 ) );
  243. return this;
  244. }
  245. // #f00
  246. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  247. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  248. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  249. return this;
  250. }
  251. // red
  252. if ( /^(\w+)$/i.test( style ) ) {
  253. this.setHex( THREE.ColorKeywords[ style ] );
  254. return this;
  255. }
  256. },
  257. copy: function ( color ) {
  258. this.r = color.r;
  259. this.g = color.g;
  260. this.b = color.b;
  261. return this;
  262. },
  263. copyGammaToLinear: function ( color ) {
  264. this.r = color.r * color.r;
  265. this.g = color.g * color.g;
  266. this.b = color.b * color.b;
  267. return this;
  268. },
  269. copyLinearToGamma: function ( color ) {
  270. this.r = Math.sqrt( color.r );
  271. this.g = Math.sqrt( color.g );
  272. this.b = Math.sqrt( color.b );
  273. return this;
  274. },
  275. convertGammaToLinear: function () {
  276. var r = this.r, g = this.g, b = this.b;
  277. this.r = r * r;
  278. this.g = g * g;
  279. this.b = b * b;
  280. return this;
  281. },
  282. convertLinearToGamma: function () {
  283. this.r = Math.sqrt( this.r );
  284. this.g = Math.sqrt( this.g );
  285. this.b = Math.sqrt( this.b );
  286. return this;
  287. },
  288. getHex: function () {
  289. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  290. },
  291. getHexString: function () {
  292. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  293. },
  294. getHSL: function () {
  295. var hsl = { h: 0, s: 0, l: 0 };
  296. return function () {
  297. // h,s,l ranges are in 0.0 - 1.0
  298. var r = this.r, g = this.g, b = this.b;
  299. var max = Math.max( r, g, b );
  300. var min = Math.min( r, g, b );
  301. var hue, saturation;
  302. var lightness = ( min + max ) / 2.0;
  303. if ( min === max ) {
  304. hue = 0;
  305. saturation = 0;
  306. } else {
  307. var delta = max - min;
  308. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  309. switch ( max ) {
  310. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  311. case g: hue = ( b - r ) / delta + 2; break;
  312. case b: hue = ( r - g ) / delta + 4; break;
  313. }
  314. hue /= 6;
  315. }
  316. hsl.h = hue;
  317. hsl.s = saturation;
  318. hsl.l = lightness;
  319. return hsl;
  320. };
  321. }(),
  322. getStyle: function () {
  323. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  324. },
  325. offsetHSL: function ( h, s, l ) {
  326. var hsl = this.getHSL();
  327. hsl.h += h; hsl.s += s; hsl.l += l;
  328. this.setHSL( hsl.h, hsl.s, hsl.l );
  329. return this;
  330. },
  331. add: function ( color ) {
  332. this.r += color.r;
  333. this.g += color.g;
  334. this.b += color.b;
  335. return this;
  336. },
  337. addColors: function ( color1, color2 ) {
  338. this.r = color1.r + color2.r;
  339. this.g = color1.g + color2.g;
  340. this.b = color1.b + color2.b;
  341. return this;
  342. },
  343. addScalar: function ( s ) {
  344. this.r += s;
  345. this.g += s;
  346. this.b += s;
  347. return this;
  348. },
  349. multiply: function ( color ) {
  350. this.r *= color.r;
  351. this.g *= color.g;
  352. this.b *= color.b;
  353. return this;
  354. },
  355. multiplyScalar: function ( s ) {
  356. this.r *= s;
  357. this.g *= s;
  358. this.b *= s;
  359. return this;
  360. },
  361. lerp: function ( color, alpha ) {
  362. this.r += ( color.r - this.r ) * alpha;
  363. this.g += ( color.g - this.g ) * alpha;
  364. this.b += ( color.b - this.b ) * alpha;
  365. return this;
  366. },
  367. equals: function ( c ) {
  368. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  369. },
  370. clone: function () {
  371. return new THREE.Color().setRGB( this.r, this.g, this.b );
  372. }
  373. };
  374. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF,
  375. "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2,
  376. "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50,
  377. "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B,
  378. "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B,
  379. "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F,
  380. "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3,
  381. "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222,
  382. "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700,
  383. "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4,
  384. "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00,
  385. "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3,
  386. "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA,
  387. "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32,
  388. "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3,
  389. "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC,
  390. "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD,
  391. "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6,
  392. "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9,
  393. "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F,
  394. "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE,
  395. "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA,
  396. "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0,
  397. "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  398. /**
  399. * @author mikael emtinger / http://gomo.se/
  400. * @author alteredq / http://alteredqualia.com/
  401. * @author WestLangley / http://github.com/WestLangley
  402. * @author bhouston / http://exocortex.com
  403. */
  404. THREE.Quaternion = function ( x, y, z, w ) {
  405. this._x = x || 0;
  406. this._y = y || 0;
  407. this._z = z || 0;
  408. this._w = ( w !== undefined ) ? w : 1;
  409. };
  410. THREE.Quaternion.prototype = {
  411. constructor: THREE.Quaternion,
  412. _x: 0,_y: 0, _z: 0, _w: 0,
  413. _euler: undefined,
  414. _updateEuler: function ( callback ) {
  415. if ( this._euler !== undefined ) {
  416. this._euler.setFromQuaternion( this, undefined, false );
  417. }
  418. },
  419. get x () {
  420. return this._x;
  421. },
  422. set x ( value ) {
  423. this._x = value;
  424. this._updateEuler();
  425. },
  426. get y () {
  427. return this._y;
  428. },
  429. set y ( value ) {
  430. this._y = value;
  431. this._updateEuler();
  432. },
  433. get z () {
  434. return this._z;
  435. },
  436. set z ( value ) {
  437. this._z = value;
  438. this._updateEuler();
  439. },
  440. get w () {
  441. return this._w;
  442. },
  443. set w ( value ) {
  444. this._w = value;
  445. this._updateEuler();
  446. },
  447. set: function ( x, y, z, w ) {
  448. this._x = x;
  449. this._y = y;
  450. this._z = z;
  451. this._w = w;
  452. this._updateEuler();
  453. return this;
  454. },
  455. copy: function ( quaternion ) {
  456. this._x = quaternion._x;
  457. this._y = quaternion._y;
  458. this._z = quaternion._z;
  459. this._w = quaternion._w;
  460. this._updateEuler();
  461. return this;
  462. },
  463. setFromEuler: function ( euler, update ) {
  464. if ( typeof euler['order'] === undefined ) {
  465. console.error( 'ERROR: Quaternion\'s .setFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  466. }
  467. // http://www.mathworks.com/matlabcentral/fileexchange/
  468. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  469. // content/SpinCalc.m
  470. var c1 = Math.cos( euler._x / 2 );
  471. var c2 = Math.cos( euler._y / 2 );
  472. var c3 = Math.cos( euler._z / 2 );
  473. var s1 = Math.sin( euler._x / 2 );
  474. var s2 = Math.sin( euler._y / 2 );
  475. var s3 = Math.sin( euler._z / 2 );
  476. if ( euler.order === undefined || euler.order === 'XYZ' ) {
  477. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  478. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  479. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  480. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  481. } else if ( euler.order === 'YXZ' ) {
  482. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  483. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  484. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  485. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  486. } else if ( euler.order === 'ZXY' ) {
  487. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  488. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  489. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  490. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  491. } else if ( euler.order === 'ZYX' ) {
  492. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  493. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  494. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  495. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  496. } else if ( euler.order === 'YZX' ) {
  497. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  498. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  499. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  500. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  501. } else if ( euler.order === 'XZY' ) {
  502. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  503. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  504. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  505. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  506. }
  507. if ( update !== false ) this._updateEuler();
  508. return this;
  509. },
  510. setFromAxisAngle: function ( axis, angle ) {
  511. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  512. // axis have to be normalized
  513. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  514. this._x = axis.x * s;
  515. this._y = axis.y * s;
  516. this._z = axis.z * s;
  517. this._w = Math.cos( halfAngle );
  518. this._updateEuler();
  519. return this;
  520. },
  521. setFromRotationMatrix: function ( m ) {
  522. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  523. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  524. var te = m.elements,
  525. m11 = te[0], m12 = te[4], m13 = te[8],
  526. m21 = te[1], m22 = te[5], m23 = te[9],
  527. m31 = te[2], m32 = te[6], m33 = te[10],
  528. trace = m11 + m22 + m33,
  529. s;
  530. if ( trace > 0 ) {
  531. s = 0.5 / Math.sqrt( trace + 1.0 );
  532. this._w = 0.25 / s;
  533. this._x = ( m32 - m23 ) * s;
  534. this._y = ( m13 - m31 ) * s;
  535. this._z = ( m21 - m12 ) * s;
  536. } else if ( m11 > m22 && m11 > m33 ) {
  537. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  538. this._w = (m32 - m23 ) / s;
  539. this._x = 0.25 * s;
  540. this._y = (m12 + m21 ) / s;
  541. this._z = (m13 + m31 ) / s;
  542. } else if ( m22 > m33 ) {
  543. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  544. this._w = (m13 - m31 ) / s;
  545. this._x = (m12 + m21 ) / s;
  546. this._y = 0.25 * s;
  547. this._z = (m23 + m32 ) / s;
  548. } else {
  549. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  550. this._w = ( m21 - m12 ) / s;
  551. this._x = ( m13 + m31 ) / s;
  552. this._y = ( m23 + m32 ) / s;
  553. this._z = 0.25 * s;
  554. }
  555. this._updateEuler();
  556. return this;
  557. },
  558. inverse: function () {
  559. this.conjugate().normalize();
  560. return this;
  561. },
  562. conjugate: function () {
  563. this._x *= -1;
  564. this._y *= -1;
  565. this._z *= -1;
  566. this._updateEuler();
  567. return this;
  568. },
  569. lengthSq: function () {
  570. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  571. },
  572. length: function () {
  573. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  574. },
  575. normalize: function () {
  576. var l = this.length();
  577. if ( l === 0 ) {
  578. this._x = 0;
  579. this._y = 0;
  580. this._z = 0;
  581. this._w = 1;
  582. } else {
  583. l = 1 / l;
  584. this._x = this._x * l;
  585. this._y = this._y * l;
  586. this._z = this._z * l;
  587. this._w = this._w * l;
  588. }
  589. return this;
  590. },
  591. multiply: function ( q, p ) {
  592. if ( p !== undefined ) {
  593. console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  594. return this.multiplyQuaternions( q, p );
  595. }
  596. return this.multiplyQuaternions( this, q );
  597. },
  598. multiplyQuaternions: function ( a, b ) {
  599. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  600. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  601. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  602. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  603. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  604. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  605. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  606. this._updateEuler();
  607. return this;
  608. },
  609. multiplyVector3: function ( vector ) {
  610. console.warn( 'DEPRECATED: Quaternion\'s .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  611. return vector.applyQuaternion( this );
  612. },
  613. slerp: function ( qb, t ) {
  614. var x = this._x, y = this._y, z = this._z, w = this._w;
  615. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  616. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  617. if ( cosHalfTheta < 0 ) {
  618. this._w = -qb._w;
  619. this._x = -qb._x;
  620. this._y = -qb._y;
  621. this._z = -qb._z;
  622. cosHalfTheta = -cosHalfTheta;
  623. } else {
  624. this.copy( qb );
  625. }
  626. if ( cosHalfTheta >= 1.0 ) {
  627. this._w = w;
  628. this._x = x;
  629. this._y = y;
  630. this._z = z;
  631. return this;
  632. }
  633. var halfTheta = Math.acos( cosHalfTheta );
  634. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  635. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  636. this._w = 0.5 * ( w + this._w );
  637. this._x = 0.5 * ( x + this._x );
  638. this._y = 0.5 * ( y + this._y );
  639. this._z = 0.5 * ( z + this._z );
  640. return this;
  641. }
  642. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  643. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  644. this._w = ( w * ratioA + this._w * ratioB );
  645. this._x = ( x * ratioA + this._x * ratioB );
  646. this._y = ( y * ratioA + this._y * ratioB );
  647. this._z = ( z * ratioA + this._z * ratioB );
  648. this._updateEuler();
  649. return this;
  650. },
  651. equals: function ( quaternion ) {
  652. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  653. },
  654. fromArray: function ( array ) {
  655. this._x = array[ 0 ];
  656. this._y = array[ 1 ];
  657. this._z = array[ 2 ];
  658. this._w = array[ 3 ];
  659. this._updateEuler();
  660. return this;
  661. },
  662. toArray: function () {
  663. return [ this._x, this._y, this._z, this._w ];
  664. },
  665. clone: function () {
  666. return new THREE.Quaternion( this._x, this._y, this._z, this._w );
  667. }
  668. };
  669. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  670. return qm.copy( qa ).slerp( qb, t );
  671. }
  672. /**
  673. * @author mrdoob / http://mrdoob.com/
  674. * @author philogb / http://blog.thejit.org/
  675. * @author egraether / http://egraether.com/
  676. * @author zz85 / http://www.lab4games.net/zz85/blog
  677. */
  678. THREE.Vector2 = function ( x, y ) {
  679. this.x = x || 0;
  680. this.y = y || 0;
  681. };
  682. THREE.Vector2.prototype = {
  683. constructor: THREE.Vector2,
  684. set: function ( x, y ) {
  685. this.x = x;
  686. this.y = y;
  687. return this;
  688. },
  689. setX: function ( x ) {
  690. this.x = x;
  691. return this;
  692. },
  693. setY: function ( y ) {
  694. this.y = y;
  695. return this;
  696. },
  697. setComponent: function ( index, value ) {
  698. switch ( index ) {
  699. case 0: this.x = value; break;
  700. case 1: this.y = value; break;
  701. default: throw new Error( "index is out of range: " + index );
  702. }
  703. },
  704. getComponent: function ( index ) {
  705. switch ( index ) {
  706. case 0: return this.x;
  707. case 1: return this.y;
  708. default: throw new Error( "index is out of range: " + index );
  709. }
  710. },
  711. copy: function ( v ) {
  712. this.x = v.x;
  713. this.y = v.y;
  714. return this;
  715. },
  716. add: function ( v, w ) {
  717. if ( w !== undefined ) {
  718. console.warn( 'DEPRECATED: Vector2\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  719. return this.addVectors( v, w );
  720. }
  721. this.x += v.x;
  722. this.y += v.y;
  723. return this;
  724. },
  725. addVectors: function ( a, b ) {
  726. this.x = a.x + b.x;
  727. this.y = a.y + b.y;
  728. return this;
  729. },
  730. addScalar: function ( s ) {
  731. this.x += s;
  732. this.y += s;
  733. return this;
  734. },
  735. sub: function ( v, w ) {
  736. if ( w !== undefined ) {
  737. console.warn( 'DEPRECATED: Vector2\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  738. return this.subVectors( v, w );
  739. }
  740. this.x -= v.x;
  741. this.y -= v.y;
  742. return this;
  743. },
  744. subVectors: function ( a, b ) {
  745. this.x = a.x - b.x;
  746. this.y = a.y - b.y;
  747. return this;
  748. },
  749. multiplyScalar: function ( s ) {
  750. this.x *= s;
  751. this.y *= s;
  752. return this;
  753. },
  754. divideScalar: function ( s ) {
  755. if ( s !== 0 ) {
  756. this.x /= s;
  757. this.y /= s;
  758. } else {
  759. this.set( 0, 0 );
  760. }
  761. return this;
  762. },
  763. min: function ( v ) {
  764. if ( this.x > v.x ) {
  765. this.x = v.x;
  766. }
  767. if ( this.y > v.y ) {
  768. this.y = v.y;
  769. }
  770. return this;
  771. },
  772. max: function ( v ) {
  773. if ( this.x < v.x ) {
  774. this.x = v.x;
  775. }
  776. if ( this.y < v.y ) {
  777. this.y = v.y;
  778. }
  779. return this;
  780. },
  781. clamp: function ( min, max ) {
  782. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  783. if ( this.x < min.x ) {
  784. this.x = min.x;
  785. } else if ( this.x > max.x ) {
  786. this.x = max.x;
  787. }
  788. if ( this.y < min.y ) {
  789. this.y = min.y;
  790. } else if ( this.y > max.y ) {
  791. this.y = max.y;
  792. }
  793. return this;
  794. },
  795. negate: function() {
  796. return this.multiplyScalar( - 1 );
  797. },
  798. dot: function ( v ) {
  799. return this.x * v.x + this.y * v.y;
  800. },
  801. lengthSq: function () {
  802. return this.x * this.x + this.y * this.y;
  803. },
  804. length: function () {
  805. return Math.sqrt( this.x * this.x + this.y * this.y );
  806. },
  807. normalize: function () {
  808. return this.divideScalar( this.length() );
  809. },
  810. distanceTo: function ( v ) {
  811. return Math.sqrt( this.distanceToSquared( v ) );
  812. },
  813. distanceToSquared: function ( v ) {
  814. var dx = this.x - v.x, dy = this.y - v.y;
  815. return dx * dx + dy * dy;
  816. },
  817. setLength: function ( l ) {
  818. var oldLength = this.length();
  819. if ( oldLength !== 0 && l !== oldLength ) {
  820. this.multiplyScalar( l / oldLength );
  821. }
  822. return this;
  823. },
  824. lerp: function ( v, alpha ) {
  825. this.x += ( v.x - this.x ) * alpha;
  826. this.y += ( v.y - this.y ) * alpha;
  827. return this;
  828. },
  829. equals: function( v ) {
  830. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  831. },
  832. fromArray: function ( array ) {
  833. this.x = array[ 0 ];
  834. this.y = array[ 1 ];
  835. return this;
  836. },
  837. toArray: function () {
  838. return [ this.x, this.y ];
  839. },
  840. clone: function () {
  841. return new THREE.Vector2( this.x, this.y );
  842. }
  843. };
  844. /**
  845. * @author mrdoob / http://mrdoob.com/
  846. * @author *kile / http://kile.stravaganza.org/
  847. * @author philogb / http://blog.thejit.org/
  848. * @author mikael emtinger / http://gomo.se/
  849. * @author egraether / http://egraether.com/
  850. * @author WestLangley / http://github.com/WestLangley
  851. */
  852. THREE.Vector3 = function ( x, y, z ) {
  853. this.x = x || 0;
  854. this.y = y || 0;
  855. this.z = z || 0;
  856. };
  857. THREE.Vector3.prototype = {
  858. constructor: THREE.Vector3,
  859. set: function ( x, y, z ) {
  860. this.x = x;
  861. this.y = y;
  862. this.z = z;
  863. return this;
  864. },
  865. setX: function ( x ) {
  866. this.x = x;
  867. return this;
  868. },
  869. setY: function ( y ) {
  870. this.y = y;
  871. return this;
  872. },
  873. setZ: function ( z ) {
  874. this.z = z;
  875. return this;
  876. },
  877. setComponent: function ( index, value ) {
  878. switch ( index ) {
  879. case 0: this.x = value; break;
  880. case 1: this.y = value; break;
  881. case 2: this.z = value; break;
  882. default: throw new Error( "index is out of range: " + index );
  883. }
  884. },
  885. getComponent: function ( index ) {
  886. switch ( index ) {
  887. case 0: return this.x;
  888. case 1: return this.y;
  889. case 2: return this.z;
  890. default: throw new Error( "index is out of range: " + index );
  891. }
  892. },
  893. copy: function ( v ) {
  894. this.x = v.x;
  895. this.y = v.y;
  896. this.z = v.z;
  897. return this;
  898. },
  899. add: function ( v, w ) {
  900. if ( w !== undefined ) {
  901. console.warn( 'DEPRECATED: Vector3\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  902. return this.addVectors( v, w );
  903. }
  904. this.x += v.x;
  905. this.y += v.y;
  906. this.z += v.z;
  907. return this;
  908. },
  909. addScalar: function ( s ) {
  910. this.x += s;
  911. this.y += s;
  912. this.z += s;
  913. return this;
  914. },
  915. addVectors: function ( a, b ) {
  916. this.x = a.x + b.x;
  917. this.y = a.y + b.y;
  918. this.z = a.z + b.z;
  919. return this;
  920. },
  921. sub: function ( v, w ) {
  922. if ( w !== undefined ) {
  923. console.warn( 'DEPRECATED: Vector3\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  924. return this.subVectors( v, w );
  925. }
  926. this.x -= v.x;
  927. this.y -= v.y;
  928. this.z -= v.z;
  929. return this;
  930. },
  931. subVectors: function ( a, b ) {
  932. this.x = a.x - b.x;
  933. this.y = a.y - b.y;
  934. this.z = a.z - b.z;
  935. return this;
  936. },
  937. multiply: function ( v, w ) {
  938. if ( w !== undefined ) {
  939. console.warn( 'DEPRECATED: Vector3\'s .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  940. return this.multiplyVectors( v, w );
  941. }
  942. this.x *= v.x;
  943. this.y *= v.y;
  944. this.z *= v.z;
  945. return this;
  946. },
  947. multiplyScalar: function ( s ) {
  948. this.x *= s;
  949. this.y *= s;
  950. this.z *= s;
  951. return this;
  952. },
  953. multiplyVectors: function ( a, b ) {
  954. this.x = a.x * b.x;
  955. this.y = a.y * b.y;
  956. this.z = a.z * b.z;
  957. return this;
  958. },
  959. applyMatrix3: function ( m ) {
  960. var x = this.x;
  961. var y = this.y;
  962. var z = this.z;
  963. var e = m.elements;
  964. this.x = e[0] * x + e[3] * y + e[6] * z;
  965. this.y = e[1] * x + e[4] * y + e[7] * z;
  966. this.z = e[2] * x + e[5] * y + e[8] * z;
  967. return this;
  968. },
  969. applyMatrix4: function ( m ) {
  970. // input: THREE.Matrix4 affine matrix
  971. var x = this.x, y = this.y, z = this.z;
  972. var e = m.elements;
  973. this.x = e[0] * x + e[4] * y + e[8] * z + e[12];
  974. this.y = e[1] * x + e[5] * y + e[9] * z + e[13];
  975. this.z = e[2] * x + e[6] * y + e[10] * z + e[14];
  976. return this;
  977. },
  978. applyProjection: function ( m ) {
  979. // input: THREE.Matrix4 projection matrix
  980. var x = this.x, y = this.y, z = this.z;
  981. var e = m.elements;
  982. var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] ); // perspective divide
  983. this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
  984. this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
  985. this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
  986. return this;
  987. },
  988. applyQuaternion: function ( q ) {
  989. var x = this.x;
  990. var y = this.y;
  991. var z = this.z;
  992. var qx = q.x;
  993. var qy = q.y;
  994. var qz = q.z;
  995. var qw = q.w;
  996. // calculate quat * vector
  997. var ix = qw * x + qy * z - qz * y;
  998. var iy = qw * y + qz * x - qx * z;
  999. var iz = qw * z + qx * y - qy * x;
  1000. var iw = -qx * x - qy * y - qz * z;
  1001. // calculate result * inverse quat
  1002. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  1003. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  1004. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  1005. return this;
  1006. },
  1007. transformDirection: function ( m ) {
  1008. // input: THREE.Matrix4 affine matrix
  1009. // vector interpreted as a direction
  1010. var x = this.x, y = this.y, z = this.z;
  1011. var e = m.elements;
  1012. this.x = e[0] * x + e[4] * y + e[8] * z;
  1013. this.y = e[1] * x + e[5] * y + e[9] * z;
  1014. this.z = e[2] * x + e[6] * y + e[10] * z;
  1015. this.normalize();
  1016. return this;
  1017. },
  1018. divide: function ( v ) {
  1019. this.x /= v.x;
  1020. this.y /= v.y;
  1021. this.z /= v.z;
  1022. return this;
  1023. },
  1024. divideScalar: function ( s ) {
  1025. if ( s !== 0 ) {
  1026. this.x /= s;
  1027. this.y /= s;
  1028. this.z /= s;
  1029. } else {
  1030. this.x = 0;
  1031. this.y = 0;
  1032. this.z = 0;
  1033. }
  1034. return this;
  1035. },
  1036. min: function ( v ) {
  1037. if ( this.x > v.x ) {
  1038. this.x = v.x;
  1039. }
  1040. if ( this.y > v.y ) {
  1041. this.y = v.y;
  1042. }
  1043. if ( this.z > v.z ) {
  1044. this.z = v.z;
  1045. }
  1046. return this;
  1047. },
  1048. max: function ( v ) {
  1049. if ( this.x < v.x ) {
  1050. this.x = v.x;
  1051. }
  1052. if ( this.y < v.y ) {
  1053. this.y = v.y;
  1054. }
  1055. if ( this.z < v.z ) {
  1056. this.z = v.z;
  1057. }
  1058. return this;
  1059. },
  1060. clamp: function ( min, max ) {
  1061. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1062. if ( this.x < min.x ) {
  1063. this.x = min.x;
  1064. } else if ( this.x > max.x ) {
  1065. this.x = max.x;
  1066. }
  1067. if ( this.y < min.y ) {
  1068. this.y = min.y;
  1069. } else if ( this.y > max.y ) {
  1070. this.y = max.y;
  1071. }
  1072. if ( this.z < min.z ) {
  1073. this.z = min.z;
  1074. } else if ( this.z > max.z ) {
  1075. this.z = max.z;
  1076. }
  1077. return this;
  1078. },
  1079. negate: function () {
  1080. return this.multiplyScalar( - 1 );
  1081. },
  1082. dot: function ( v ) {
  1083. return this.x * v.x + this.y * v.y + this.z * v.z;
  1084. },
  1085. lengthSq: function () {
  1086. return this.x * this.x + this.y * this.y + this.z * this.z;
  1087. },
  1088. length: function () {
  1089. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1090. },
  1091. lengthManhattan: function () {
  1092. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1093. },
  1094. normalize: function () {
  1095. return this.divideScalar( this.length() );
  1096. },
  1097. setLength: function ( l ) {
  1098. var oldLength = this.length();
  1099. if ( oldLength !== 0 && l !== oldLength ) {
  1100. this.multiplyScalar( l / oldLength );
  1101. }
  1102. return this;
  1103. },
  1104. lerp: function ( v, alpha ) {
  1105. this.x += ( v.x - this.x ) * alpha;
  1106. this.y += ( v.y - this.y ) * alpha;
  1107. this.z += ( v.z - this.z ) * alpha;
  1108. return this;
  1109. },
  1110. cross: function ( v, w ) {
  1111. if ( w !== undefined ) {
  1112. console.warn( 'DEPRECATED: Vector3\'s .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1113. return this.crossVectors( v, w );
  1114. }
  1115. var x = this.x, y = this.y, z = this.z;
  1116. this.x = y * v.z - z * v.y;
  1117. this.y = z * v.x - x * v.z;
  1118. this.z = x * v.y - y * v.x;
  1119. return this;
  1120. },
  1121. crossVectors: function ( a, b ) {
  1122. this.x = a.y * b.z - a.z * b.y;
  1123. this.y = a.z * b.x - a.x * b.z;
  1124. this.z = a.x * b.y - a.y * b.x;
  1125. return this;
  1126. },
  1127. angleTo: function ( v ) {
  1128. var theta = this.dot( v ) / ( this.length() * v.length() );
  1129. // clamp, to handle numerical problems
  1130. return Math.acos( THREE.Math.clamp( theta, -1, 1 ) );
  1131. },
  1132. distanceTo: function ( v ) {
  1133. return Math.sqrt( this.distanceToSquared( v ) );
  1134. },
  1135. distanceToSquared: function ( v ) {
  1136. var dx = this.x - v.x;
  1137. var dy = this.y - v.y;
  1138. var dz = this.z - v.z;
  1139. return dx * dx + dy * dy + dz * dz;
  1140. },
  1141. setEulerFromRotationMatrix: function ( m, order ) {
  1142. console.error( "REMOVED: Vector3\'s setEulerFromRotationMatrix has been removed in favor of Euler.setFromRotationMatrix(), please update your code.");
  1143. },
  1144. setEulerFromQuaternion: function ( q, order ) {
  1145. console.error( "REMOVED: Vector3\'s setEulerFromQuaternion: has been removed in favor of Euler.setFromQuaternion(), please update your code.");
  1146. },
  1147. getPositionFromMatrix: function ( m ) {
  1148. this.x = m.elements[12];
  1149. this.y = m.elements[13];
  1150. this.z = m.elements[14];
  1151. return this;
  1152. },
  1153. getScaleFromMatrix: function ( m ) {
  1154. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  1155. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  1156. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  1157. this.x = sx;
  1158. this.y = sy;
  1159. this.z = sz;
  1160. return this;
  1161. },
  1162. getColumnFromMatrix: function ( index, matrix ) {
  1163. var offset = index * 4;
  1164. var me = matrix.elements;
  1165. this.x = me[ offset ];
  1166. this.y = me[ offset + 1 ];
  1167. this.z = me[ offset + 2 ];
  1168. return this;
  1169. },
  1170. equals: function ( v ) {
  1171. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1172. },
  1173. fromArray: function ( array ) {
  1174. this.x = array[ 0 ];
  1175. this.y = array[ 1 ];
  1176. this.z = array[ 2 ];
  1177. return this;
  1178. },
  1179. toArray: function () {
  1180. return [ this.x, this.y, this.z ];
  1181. },
  1182. clone: function () {
  1183. return new THREE.Vector3( this.x, this.y, this.z );
  1184. }
  1185. };
  1186. THREE.extend( THREE.Vector3.prototype, {
  1187. applyEuler: function () {
  1188. var q1 = new THREE.Quaternion();
  1189. return function ( rotation ) {
  1190. if( typeof rotation['order'] === undefined ) {
  1191. console.error( 'ERROR: Vector3\'s .applyEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  1192. }
  1193. var quaternion = q1.setFromEuler( rotation );
  1194. this.applyQuaternion( quaternion );
  1195. return this;
  1196. };
  1197. }(),
  1198. applyAxisAngle: function () {
  1199. var q1 = new THREE.Quaternion();
  1200. return function ( axis, angle ) {
  1201. var quaternion = q1.setFromAxisAngle( axis, angle );
  1202. this.applyQuaternion( quaternion );
  1203. return this;
  1204. };
  1205. }(),
  1206. projectOnVector: function () {
  1207. var v1 = new THREE.Vector3();
  1208. return function ( vector ) {
  1209. v1.copy( vector ).normalize();
  1210. var d = this.dot( v1 );
  1211. return this.copy( v1 ).multiplyScalar( d );
  1212. };
  1213. }(),
  1214. projectOnPlane: function () {
  1215. var v1 = new THREE.Vector3();
  1216. return function ( planeNormal ) {
  1217. v1.copy( this ).projectOnVector( planeNormal );
  1218. return this.sub( v1 );
  1219. }
  1220. }(),
  1221. reflect: function () {
  1222. var v1 = new THREE.Vector3();
  1223. return function ( vector ) {
  1224. v1.copy( this ).projectOnVector( vector ).multiplyScalar( 2 );
  1225. return this.subVectors( v1, this );
  1226. }
  1227. }()
  1228. } );
  1229. /**
  1230. * @author supereggbert / http://www.paulbrunt.co.uk/
  1231. * @author philogb / http://blog.thejit.org/
  1232. * @author mikael emtinger / http://gomo.se/
  1233. * @author egraether / http://egraether.com/
  1234. * @author WestLangley / http://github.com/WestLangley
  1235. */
  1236. THREE.Vector4 = function ( x, y, z, w ) {
  1237. this.x = x || 0;
  1238. this.y = y || 0;
  1239. this.z = z || 0;
  1240. this.w = ( w !== undefined ) ? w : 1;
  1241. };
  1242. THREE.Vector4.prototype = {
  1243. constructor: THREE.Vector4,
  1244. set: function ( x, y, z, w ) {
  1245. this.x = x;
  1246. this.y = y;
  1247. this.z = z;
  1248. this.w = w;
  1249. return this;
  1250. },
  1251. setX: function ( x ) {
  1252. this.x = x;
  1253. return this;
  1254. },
  1255. setY: function ( y ) {
  1256. this.y = y;
  1257. return this;
  1258. },
  1259. setZ: function ( z ) {
  1260. this.z = z;
  1261. return this;
  1262. },
  1263. setW: function ( w ) {
  1264. this.w = w;
  1265. return this;
  1266. },
  1267. setComponent: function ( index, value ) {
  1268. switch ( index ) {
  1269. case 0: this.x = value; break;
  1270. case 1: this.y = value; break;
  1271. case 2: this.z = value; break;
  1272. case 3: this.w = value; break;
  1273. default: throw new Error( "index is out of range: " + index );
  1274. }
  1275. },
  1276. getComponent: function ( index ) {
  1277. switch ( index ) {
  1278. case 0: return this.x;
  1279. case 1: return this.y;
  1280. case 2: return this.z;
  1281. case 3: return this.w;
  1282. default: throw new Error( "index is out of range: " + index );
  1283. }
  1284. },
  1285. copy: function ( v ) {
  1286. this.x = v.x;
  1287. this.y = v.y;
  1288. this.z = v.z;
  1289. this.w = ( v.w !== undefined ) ? v.w : 1;
  1290. return this;
  1291. },
  1292. add: function ( v, w ) {
  1293. if ( w !== undefined ) {
  1294. console.warn( 'DEPRECATED: Vector4\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1295. return this.addVectors( v, w );
  1296. }
  1297. this.x += v.x;
  1298. this.y += v.y;
  1299. this.z += v.z;
  1300. this.w += v.w;
  1301. return this;
  1302. },
  1303. addScalar: function ( s ) {
  1304. this.x += s;
  1305. this.y += s;
  1306. this.z += s;
  1307. this.w += s;
  1308. return this;
  1309. },
  1310. addVectors: function ( a, b ) {
  1311. this.x = a.x + b.x;
  1312. this.y = a.y + b.y;
  1313. this.z = a.z + b.z;
  1314. this.w = a.w + b.w;
  1315. return this;
  1316. },
  1317. sub: function ( v, w ) {
  1318. if ( w !== undefined ) {
  1319. console.warn( 'DEPRECATED: Vector4\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1320. return this.subVectors( v, w );
  1321. }
  1322. this.x -= v.x;
  1323. this.y -= v.y;
  1324. this.z -= v.z;
  1325. this.w -= v.w;
  1326. return this;
  1327. },
  1328. subVectors: function ( a, b ) {
  1329. this.x = a.x - b.x;
  1330. this.y = a.y - b.y;
  1331. this.z = a.z - b.z;
  1332. this.w = a.w - b.w;
  1333. return this;
  1334. },
  1335. multiplyScalar: function ( s ) {
  1336. this.x *= s;
  1337. this.y *= s;
  1338. this.z *= s;
  1339. this.w *= s;
  1340. return this;
  1341. },
  1342. applyMatrix4: function ( m ) {
  1343. var x = this.x;
  1344. var y = this.y;
  1345. var z = this.z;
  1346. var w = this.w;
  1347. var e = m.elements;
  1348. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1349. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1350. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1351. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1352. return this;
  1353. },
  1354. divideScalar: function ( s ) {
  1355. if ( s !== 0 ) {
  1356. this.x /= s;
  1357. this.y /= s;
  1358. this.z /= s;
  1359. this.w /= s;
  1360. } else {
  1361. this.x = 0;
  1362. this.y = 0;
  1363. this.z = 0;
  1364. this.w = 1;
  1365. }
  1366. return this;
  1367. },
  1368. setAxisAngleFromQuaternion: function ( q ) {
  1369. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1370. // q is assumed to be normalized
  1371. this.w = 2 * Math.acos( q.w );
  1372. var s = Math.sqrt( 1 - q.w * q.w );
  1373. if ( s < 0.0001 ) {
  1374. this.x = 1;
  1375. this.y = 0;
  1376. this.z = 0;
  1377. } else {
  1378. this.x = q.x / s;
  1379. this.y = q.y / s;
  1380. this.z = q.z / s;
  1381. }
  1382. return this;
  1383. },
  1384. setAxisAngleFromRotationMatrix: function ( m ) {
  1385. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1386. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1387. var angle, x, y, z, // variables for result
  1388. epsilon = 0.01, // margin to allow for rounding errors
  1389. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1390. te = m.elements,
  1391. m11 = te[0], m12 = te[4], m13 = te[8],
  1392. m21 = te[1], m22 = te[5], m23 = te[9],
  1393. m31 = te[2], m32 = te[6], m33 = te[10];
  1394. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1395. && ( Math.abs( m13 - m31 ) < epsilon )
  1396. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1397. // singularity found
  1398. // first check for identity matrix which must have +1 for all terms
  1399. // in leading diagonal and zero in other terms
  1400. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1401. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1402. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1403. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1404. // this singularity is identity matrix so angle = 0
  1405. this.set( 1, 0, 0, 0 );
  1406. return this; // zero angle, arbitrary axis
  1407. }
  1408. // otherwise this singularity is angle = 180
  1409. angle = Math.PI;
  1410. var xx = ( m11 + 1 ) / 2;
  1411. var yy = ( m22 + 1 ) / 2;
  1412. var zz = ( m33 + 1 ) / 2;
  1413. var xy = ( m12 + m21 ) / 4;
  1414. var xz = ( m13 + m31 ) / 4;
  1415. var yz = ( m23 + m32 ) / 4;
  1416. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1417. if ( xx < epsilon ) {
  1418. x = 0;
  1419. y = 0.707106781;
  1420. z = 0.707106781;
  1421. } else {
  1422. x = Math.sqrt( xx );
  1423. y = xy / x;
  1424. z = xz / x;
  1425. }
  1426. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1427. if ( yy < epsilon ) {
  1428. x = 0.707106781;
  1429. y = 0;
  1430. z = 0.707106781;
  1431. } else {
  1432. y = Math.sqrt( yy );
  1433. x = xy / y;
  1434. z = yz / y;
  1435. }
  1436. } else { // m33 is the largest diagonal term so base result on this
  1437. if ( zz < epsilon ) {
  1438. x = 0.707106781;
  1439. y = 0.707106781;
  1440. z = 0;
  1441. } else {
  1442. z = Math.sqrt( zz );
  1443. x = xz / z;
  1444. y = yz / z;
  1445. }
  1446. }
  1447. this.set( x, y, z, angle );
  1448. return this; // return 180 deg rotation
  1449. }
  1450. // as we have reached here there are no singularities so we can handle normally
  1451. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1452. + ( m13 - m31 ) * ( m13 - m31 )
  1453. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1454. if ( Math.abs( s ) < 0.001 ) s = 1;
  1455. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1456. // caught by singularity test above, but I've left it in just in case
  1457. this.x = ( m32 - m23 ) / s;
  1458. this.y = ( m13 - m31 ) / s;
  1459. this.z = ( m21 - m12 ) / s;
  1460. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1461. return this;
  1462. },
  1463. min: function ( v ) {
  1464. if ( this.x > v.x ) {
  1465. this.x = v.x;
  1466. }
  1467. if ( this.y > v.y ) {
  1468. this.y = v.y;
  1469. }
  1470. if ( this.z > v.z ) {
  1471. this.z = v.z;
  1472. }
  1473. if ( this.w > v.w ) {
  1474. this.w = v.w;
  1475. }
  1476. return this;
  1477. },
  1478. max: function ( v ) {
  1479. if ( this.x < v.x ) {
  1480. this.x = v.x;
  1481. }
  1482. if ( this.y < v.y ) {
  1483. this.y = v.y;
  1484. }
  1485. if ( this.z < v.z ) {
  1486. this.z = v.z;
  1487. }
  1488. if ( this.w < v.w ) {
  1489. this.w = v.w;
  1490. }
  1491. return this;
  1492. },
  1493. clamp: function ( min, max ) {
  1494. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1495. if ( this.x < min.x ) {
  1496. this.x = min.x;
  1497. } else if ( this.x > max.x ) {
  1498. this.x = max.x;
  1499. }
  1500. if ( this.y < min.y ) {
  1501. this.y = min.y;
  1502. } else if ( this.y > max.y ) {
  1503. this.y = max.y;
  1504. }
  1505. if ( this.z < min.z ) {
  1506. this.z = min.z;
  1507. } else if ( this.z > max.z ) {
  1508. this.z = max.z;
  1509. }
  1510. if ( this.w < min.w ) {
  1511. this.w = min.w;
  1512. } else if ( this.w > max.w ) {
  1513. this.w = max.w;
  1514. }
  1515. return this;
  1516. },
  1517. negate: function() {
  1518. return this.multiplyScalar( -1 );
  1519. },
  1520. dot: function ( v ) {
  1521. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1522. },
  1523. lengthSq: function () {
  1524. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1525. },
  1526. length: function () {
  1527. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1528. },
  1529. lengthManhattan: function () {
  1530. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1531. },
  1532. normalize: function () {
  1533. return this.divideScalar( this.length() );
  1534. },
  1535. setLength: function ( l ) {
  1536. var oldLength = this.length();
  1537. if ( oldLength !== 0 && l !== oldLength ) {
  1538. this.multiplyScalar( l / oldLength );
  1539. }
  1540. return this;
  1541. },
  1542. lerp: function ( v, alpha ) {
  1543. this.x += ( v.x - this.x ) * alpha;
  1544. this.y += ( v.y - this.y ) * alpha;
  1545. this.z += ( v.z - this.z ) * alpha;
  1546. this.w += ( v.w - this.w ) * alpha;
  1547. return this;
  1548. },
  1549. equals: function ( v ) {
  1550. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1551. },
  1552. fromArray: function ( array ) {
  1553. this.x = array[ 0 ];
  1554. this.y = array[ 1 ];
  1555. this.z = array[ 2 ];
  1556. this.w = array[ 3 ];
  1557. return this;
  1558. },
  1559. toArray: function () {
  1560. return [ this.x, this.y, this.z, this.w ];
  1561. },
  1562. clone: function () {
  1563. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1564. }
  1565. };
  1566. /**
  1567. * @author mrdoob / http://mrdoob.com/
  1568. * @author WestLangley / http://github.com/WestLangley
  1569. * @author bhouston / http://exocortex.com
  1570. */
  1571. THREE.Euler = function ( x, y, z, order ) {
  1572. this._x = x || 0;
  1573. this._y = y || 0;
  1574. this._z = z || 0;
  1575. this._order = order || THREE.Euler.DefaultOrder;
  1576. };
  1577. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1578. THREE.Euler.DefaultOrder = 'XYZ';
  1579. THREE.Euler.prototype = {
  1580. constructor: THREE.Euler,
  1581. _x: 0, _y: 0, _z: 0, _order: THREE.Euler.DefaultOrder,
  1582. _quaternion: undefined,
  1583. _updateQuaternion: function () {
  1584. if ( this._quaternion !== undefined ) {
  1585. this._quaternion.setFromEuler( this, false );
  1586. }
  1587. },
  1588. get x () {
  1589. return this._x;
  1590. },
  1591. set x ( value ) {
  1592. this._x = value;
  1593. this._updateQuaternion();
  1594. },
  1595. get y () {
  1596. return this._y;
  1597. },
  1598. set y ( value ) {
  1599. this._y = value;
  1600. this._updateQuaternion();
  1601. },
  1602. get z () {
  1603. return this._z;
  1604. },
  1605. set z ( value ) {
  1606. this._z = value;
  1607. this._updateQuaternion();
  1608. },
  1609. get order () {
  1610. return this._order;
  1611. },
  1612. set order ( value ) {
  1613. this._order = value;
  1614. this._updateQuaternion();
  1615. },
  1616. set: function ( x, y, z, order ) {
  1617. this._x = x;
  1618. this._y = y;
  1619. this._z = z;
  1620. this._order = order || this._order;
  1621. this._updateQuaternion();
  1622. return this;
  1623. },
  1624. copy: function ( euler ) {
  1625. this._x = euler._x;
  1626. this._y = euler._y;
  1627. this._z = euler._z;
  1628. this._order = euler._order;
  1629. this._updateQuaternion();
  1630. return this;
  1631. },
  1632. setFromRotationMatrix: function ( m, order ) {
  1633. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1634. // clamp, to handle numerical problems
  1635. function clamp( x ) {
  1636. return Math.min( Math.max( x, -1 ), 1 );
  1637. }
  1638. var te = m.elements;
  1639. var m11 = te[0], m12 = te[4], m13 = te[8];
  1640. var m21 = te[1], m22 = te[5], m23 = te[9];
  1641. var m31 = te[2], m32 = te[6], m33 = te[10];
  1642. order = order || this._order;
  1643. if ( order === 'XYZ' ) {
  1644. this._y = Math.asin( clamp( m13 ) );
  1645. if ( Math.abs( m13 ) < 0.99999 ) {
  1646. this._x = Math.atan2( - m23, m33 );
  1647. this._z = Math.atan2( - m12, m11 );
  1648. } else {
  1649. this._x = Math.atan2( m32, m22 );
  1650. this._z = 0;
  1651. }
  1652. } else if ( order === 'YXZ' ) {
  1653. this._x = Math.asin( - clamp( m23 ) );
  1654. if ( Math.abs( m23 ) < 0.99999 ) {
  1655. this._y = Math.atan2( m13, m33 );
  1656. this._z = Math.atan2( m21, m22 );
  1657. } else {
  1658. this._y = Math.atan2( - m31, m11 );
  1659. this._z = 0;
  1660. }
  1661. } else if ( order === 'ZXY' ) {
  1662. this._x = Math.asin( clamp( m32 ) );
  1663. if ( Math.abs( m32 ) < 0.99999 ) {
  1664. this._y = Math.atan2( - m31, m33 );
  1665. this._z = Math.atan2( - m12, m22 );
  1666. } else {
  1667. this._y = 0;
  1668. this._z = Math.atan2( m21, m11 );
  1669. }
  1670. } else if ( order === 'ZYX' ) {
  1671. this._y = Math.asin( - clamp( m31 ) );
  1672. if ( Math.abs( m31 ) < 0.99999 ) {
  1673. this._x = Math.atan2( m32, m33 );
  1674. this._z = Math.atan2( m21, m11 );
  1675. } else {
  1676. this._x = 0;
  1677. this._z = Math.atan2( - m12, m22 );
  1678. }
  1679. } else if ( order === 'YZX' ) {
  1680. this._z = Math.asin( clamp( m21 ) );
  1681. if ( Math.abs( m21 ) < 0.99999 ) {
  1682. this._x = Math.atan2( - m23, m22 );
  1683. this._y = Math.atan2( - m31, m11 );
  1684. } else {
  1685. this._x = 0;
  1686. this._y = Math.atan2( m13, m33 );
  1687. }
  1688. } else if ( order === 'XZY' ) {
  1689. this._z = Math.asin( - clamp( m12 ) );
  1690. if ( Math.abs( m12 ) < 0.99999 ) {
  1691. this._x = Math.atan2( m32, m22 );
  1692. this._y = Math.atan2( m13, m11 );
  1693. } else {
  1694. this._x = Math.atan2( - m23, m33 );
  1695. this._y = 0;
  1696. }
  1697. } else {
  1698. console.warn( 'WARNING: Euler.setFromRotationMatrix() given unsupported order: ' + order )
  1699. }
  1700. this._order = order;
  1701. this._updateQuaternion();
  1702. return this;
  1703. },
  1704. setFromQuaternion: function ( q, order, update ) {
  1705. // q is assumed to be normalized
  1706. // clamp, to handle numerical problems
  1707. function clamp( x ) {
  1708. return Math.min( Math.max( x, -1 ), 1 );
  1709. }
  1710. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  1711. var sqx = q.x * q.x;
  1712. var sqy = q.y * q.y;
  1713. var sqz = q.z * q.z;
  1714. var sqw = q.w * q.w;
  1715. order = order || this._order;
  1716. if ( order === 'XYZ' ) {
  1717. this._x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  1718. this._y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  1719. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  1720. } else if ( order === 'YXZ' ) {
  1721. this._x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  1722. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  1723. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  1724. } else if ( order === 'ZXY' ) {
  1725. this._x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  1726. this._y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  1727. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  1728. } else if ( order === 'ZYX' ) {
  1729. this._x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  1730. this._y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  1731. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  1732. } else if ( order === 'YZX' ) {
  1733. this._x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  1734. this._y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  1735. this._z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  1736. } else if ( order === 'XZY' ) {
  1737. this._x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  1738. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  1739. this._z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  1740. } else {
  1741. console.warn( 'WARNING: Euler.setFromQuaternion() given unsupported order: ' + order )
  1742. }
  1743. this._order = order;
  1744. if ( update !== false ) this._updateQuaternion();
  1745. return this;
  1746. },
  1747. reorder: function () {
  1748. // WARNING: this discards revolution information -bhouston
  1749. var q = new THREE.Quaternion();
  1750. return function ( newOrder ) {
  1751. q.setFromEuler( this );
  1752. this.setFromQuaternion( q, newOrder );
  1753. };
  1754. }(),
  1755. fromArray: function ( array ) {
  1756. this._x = array[ 0 ];
  1757. this._y = array[ 1 ];
  1758. this._z = array[ 2 ];
  1759. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  1760. this._updateQuaternion();
  1761. return this;
  1762. },
  1763. toArray: function () {
  1764. return [ this._x, this._y, this._z, this._order ];
  1765. },
  1766. equals: function ( euler ) {
  1767. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  1768. },
  1769. clone: function () {
  1770. return new THREE.Euler( this._x, this._y, this._z, this._order );
  1771. }
  1772. };
  1773. /**
  1774. * @author bhouston / http://exocortex.com
  1775. */
  1776. THREE.Line3 = function ( start, end ) {
  1777. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  1778. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  1779. };
  1780. THREE.Line3.prototype = {
  1781. constructor: THREE.Line3,
  1782. set: function ( start, end ) {
  1783. this.start.copy( start );
  1784. this.end.copy( end );
  1785. return this;
  1786. },
  1787. copy: function ( line ) {
  1788. this.start.copy( line.start );
  1789. this.end.copy( line.end );
  1790. return this;
  1791. },
  1792. center: function ( optionalTarget ) {
  1793. var result = optionalTarget || new THREE.Vector3();
  1794. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  1795. },
  1796. delta: function ( optionalTarget ) {
  1797. var result = optionalTarget || new THREE.Vector3();
  1798. return result.subVectors( this.end, this.start );
  1799. },
  1800. distanceSq: function () {
  1801. return this.start.distanceToSquared( this.end );
  1802. },
  1803. distance: function () {
  1804. return this.start.distanceTo( this.end );
  1805. },
  1806. at: function ( t, optionalTarget ) {
  1807. var result = optionalTarget || new THREE.Vector3();
  1808. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1809. },
  1810. closestPointToPointParameter: function() {
  1811. var startP = new THREE.Vector3();
  1812. var startEnd = new THREE.Vector3();
  1813. return function ( point, clampToLine ) {
  1814. startP.subVectors( point, this.start );
  1815. startEnd.subVectors( this.end, this.start );
  1816. var startEnd2 = startEnd.dot( startEnd );
  1817. var startEnd_startP = startEnd.dot( startP );
  1818. var t = startEnd_startP / startEnd2;
  1819. if ( clampToLine ) {
  1820. t = THREE.Math.clamp( t, 0, 1 );
  1821. }
  1822. return t;
  1823. };
  1824. }(),
  1825. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  1826. var t = this.closestPointToPointParameter( point, clampToLine );
  1827. var result = optionalTarget || new THREE.Vector3();
  1828. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1829. },
  1830. applyMatrix4: function ( matrix ) {
  1831. this.start.applyMatrix4( matrix );
  1832. this.end.applyMatrix4( matrix );
  1833. return this;
  1834. },
  1835. equals: function ( line ) {
  1836. return line.start.equals( this.start ) && line.end.equals( this.end );
  1837. },
  1838. clone: function () {
  1839. return new THREE.Line3().copy( this );
  1840. }
  1841. };
  1842. /**
  1843. * @author bhouston / http://exocortex.com
  1844. */
  1845. THREE.Box2 = function ( min, max ) {
  1846. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  1847. this.max = ( max !== undefined ) ? max : new THREE.Vector2( -Infinity, -Infinity );
  1848. };
  1849. THREE.Box2.prototype = {
  1850. constructor: THREE.Box2,
  1851. set: function ( min, max ) {
  1852. this.min.copy( min );
  1853. this.max.copy( max );
  1854. return this;
  1855. },
  1856. setFromPoints: function ( points ) {
  1857. if ( points.length > 0 ) {
  1858. var point = points[ 0 ];
  1859. this.min.copy( point );
  1860. this.max.copy( point );
  1861. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1862. point = points[ i ];
  1863. if ( point.x < this.min.x ) {
  1864. this.min.x = point.x;
  1865. } else if ( point.x > this.max.x ) {
  1866. this.max.x = point.x;
  1867. }
  1868. if ( point.y < this.min.y ) {
  1869. this.min.y = point.y;
  1870. } else if ( point.y > this.max.y ) {
  1871. this.max.y = point.y;
  1872. }
  1873. }
  1874. } else {
  1875. this.makeEmpty();
  1876. }
  1877. return this;
  1878. },
  1879. setFromCenterAndSize: function () {
  1880. var v1 = new THREE.Vector2();
  1881. return function ( center, size ) {
  1882. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1883. this.min.copy( center ).sub( halfSize );
  1884. this.max.copy( center ).add( halfSize );
  1885. return this;
  1886. };
  1887. }(),
  1888. copy: function ( box ) {
  1889. this.min.copy( box.min );
  1890. this.max.copy( box.max );
  1891. return this;
  1892. },
  1893. makeEmpty: function () {
  1894. this.min.x = this.min.y = Infinity;
  1895. this.max.x = this.max.y = -Infinity;
  1896. return this;
  1897. },
  1898. empty: function () {
  1899. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1900. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  1901. },
  1902. center: function ( optionalTarget ) {
  1903. var result = optionalTarget || new THREE.Vector2();
  1904. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1905. },
  1906. size: function ( optionalTarget ) {
  1907. var result = optionalTarget || new THREE.Vector2();
  1908. return result.subVectors( this.max, this.min );
  1909. },
  1910. expandByPoint: function ( point ) {
  1911. this.min.min( point );
  1912. this.max.max( point );
  1913. return this;
  1914. },
  1915. expandByVector: function ( vector ) {
  1916. this.min.sub( vector );
  1917. this.max.add( vector );
  1918. return this;
  1919. },
  1920. expandByScalar: function ( scalar ) {
  1921. this.min.addScalar( -scalar );
  1922. this.max.addScalar( scalar );
  1923. return this;
  1924. },
  1925. containsPoint: function ( point ) {
  1926. if ( point.x < this.min.x || point.x > this.max.x ||
  1927. point.y < this.min.y || point.y > this.max.y ) {
  1928. return false;
  1929. }
  1930. return true;
  1931. },
  1932. containsBox: function ( box ) {
  1933. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1934. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  1935. return true;
  1936. }
  1937. return false;
  1938. },
  1939. getParameter: function ( point ) {
  1940. // This can potentially have a divide by zero if the box
  1941. // has a size dimension of 0.
  1942. return new THREE.Vector2(
  1943. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1944. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  1945. );
  1946. },
  1947. isIntersectionBox: function ( box ) {
  1948. // using 6 splitting planes to rule out intersections.
  1949. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  1950. box.max.y < this.min.y || box.min.y > this.max.y ) {
  1951. return false;
  1952. }
  1953. return true;
  1954. },
  1955. clampPoint: function ( point, optionalTarget ) {
  1956. var result = optionalTarget || new THREE.Vector2();
  1957. return result.copy( point ).clamp( this.min, this.max );
  1958. },
  1959. distanceToPoint: function () {
  1960. var v1 = new THREE.Vector2();
  1961. return function ( point ) {
  1962. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  1963. return clampedPoint.sub( point ).length();
  1964. };
  1965. }(),
  1966. intersect: function ( box ) {
  1967. this.min.max( box.min );
  1968. this.max.min( box.max );
  1969. return this;
  1970. },
  1971. union: function ( box ) {
  1972. this.min.min( box.min );
  1973. this.max.max( box.max );
  1974. return this;
  1975. },
  1976. translate: function ( offset ) {
  1977. this.min.add( offset );
  1978. this.max.add( offset );
  1979. return this;
  1980. },
  1981. equals: function ( box ) {
  1982. return box.min.equals( this.min ) && box.max.equals( this.max );
  1983. },
  1984. clone: function () {
  1985. return new THREE.Box2().copy( this );
  1986. }
  1987. };
  1988. /**
  1989. * @author bhouston / http://exocortex.com
  1990. * @author WestLangley / http://github.com/WestLangley
  1991. */
  1992. THREE.Box3 = function ( min, max ) {
  1993. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  1994. this.max = ( max !== undefined ) ? max : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  1995. };
  1996. THREE.Box3.prototype = {
  1997. constructor: THREE.Box3,
  1998. set: function ( min, max ) {
  1999. this.min.copy( min );
  2000. this.max.copy( max );
  2001. return this;
  2002. },
  2003. setFromPoints: function ( points ) {
  2004. if ( points.length > 0 ) {
  2005. var point = points[ 0 ];
  2006. this.min.copy( point );
  2007. this.max.copy( point );
  2008. for ( var i = 1, il = points.length; i < il; i ++ ) {
  2009. point = points[ i ];
  2010. if ( point.x < this.min.x ) {
  2011. this.min.x = point.x;
  2012. } else if ( point.x > this.max.x ) {
  2013. this.max.x = point.x;
  2014. }
  2015. if ( point.y < this.min.y ) {
  2016. this.min.y = point.y;
  2017. } else if ( point.y > this.max.y ) {
  2018. this.max.y = point.y;
  2019. }
  2020. if ( point.z < this.min.z ) {
  2021. this.min.z = point.z;
  2022. } else if ( point.z > this.max.z ) {
  2023. this.max.z = point.z;
  2024. }
  2025. }
  2026. } else {
  2027. this.makeEmpty();
  2028. }
  2029. return this;
  2030. },
  2031. setFromCenterAndSize: function() {
  2032. var v1 = new THREE.Vector3();
  2033. return function ( center, size ) {
  2034. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2035. this.min.copy( center ).sub( halfSize );
  2036. this.max.copy( center ).add( halfSize );
  2037. return this;
  2038. };
  2039. }(),
  2040. setFromObject: function() {
  2041. // Computes the world-axis-aligned bounding box of an object (including its children),
  2042. // accounting for both the object's, and childrens', world transforms
  2043. var v1 = new THREE.Vector3();
  2044. return function( object ) {
  2045. var scope = this;
  2046. object.updateMatrixWorld( true );
  2047. this.makeEmpty();
  2048. object.traverse( function ( node ) {
  2049. if ( node.geometry !== undefined && node.geometry.vertices !== undefined ) {
  2050. var vertices = node.geometry.vertices;
  2051. for ( var i = 0, il = vertices.length; i < il; i++ ) {
  2052. v1.copy( vertices[ i ] );
  2053. v1.applyMatrix4( node.matrixWorld );
  2054. scope.expandByPoint( v1 );
  2055. }
  2056. }
  2057. } );
  2058. return this;
  2059. };
  2060. }(),
  2061. copy: function ( box ) {
  2062. this.min.copy( box.min );
  2063. this.max.copy( box.max );
  2064. return this;
  2065. },
  2066. makeEmpty: function () {
  2067. this.min.x = this.min.y = this.min.z = Infinity;
  2068. this.max.x = this.max.y = this.max.z = -Infinity;
  2069. return this;
  2070. },
  2071. empty: function () {
  2072. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2073. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2074. },
  2075. center: function ( optionalTarget ) {
  2076. var result = optionalTarget || new THREE.Vector3();
  2077. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2078. },
  2079. size: function ( optionalTarget ) {
  2080. var result = optionalTarget || new THREE.Vector3();
  2081. return result.subVectors( this.max, this.min );
  2082. },
  2083. expandByPoint: function ( point ) {
  2084. this.min.min( point );
  2085. this.max.max( point );
  2086. return this;
  2087. },
  2088. expandByVector: function ( vector ) {
  2089. this.min.sub( vector );
  2090. this.max.add( vector );
  2091. return this;
  2092. },
  2093. expandByScalar: function ( scalar ) {
  2094. this.min.addScalar( -scalar );
  2095. this.max.addScalar( scalar );
  2096. return this;
  2097. },
  2098. containsPoint: function ( point ) {
  2099. if ( point.x < this.min.x || point.x > this.max.x ||
  2100. point.y < this.min.y || point.y > this.max.y ||
  2101. point.z < this.min.z || point.z > this.max.z ) {
  2102. return false;
  2103. }
  2104. return true;
  2105. },
  2106. containsBox: function ( box ) {
  2107. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2108. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2109. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2110. return true;
  2111. }
  2112. return false;
  2113. },
  2114. getParameter: function ( point ) {
  2115. // This can potentially have a divide by zero if the box
  2116. // has a size dimension of 0.
  2117. return new THREE.Vector3(
  2118. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2119. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2120. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2121. );
  2122. },
  2123. isIntersectionBox: function ( box ) {
  2124. // using 6 splitting planes to rule out intersections.
  2125. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2126. box.max.y < this.min.y || box.min.y > this.max.y ||
  2127. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2128. return false;
  2129. }
  2130. return true;
  2131. },
  2132. clampPoint: function ( point, optionalTarget ) {
  2133. var result = optionalTarget || new THREE.Vector3();
  2134. return result.copy( point ).clamp( this.min, this.max );
  2135. },
  2136. distanceToPoint: function() {
  2137. var v1 = new THREE.Vector3();
  2138. return function ( point ) {
  2139. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2140. return clampedPoint.sub( point ).length();
  2141. };
  2142. }(),
  2143. getBoundingSphere: function() {
  2144. var v1 = new THREE.Vector3();
  2145. return function ( optionalTarget ) {
  2146. var result = optionalTarget || new THREE.Sphere();
  2147. result.center = this.center();
  2148. result.radius = this.size( v1 ).length() * 0.5;
  2149. return result;
  2150. };
  2151. }(),
  2152. intersect: function ( box ) {
  2153. this.min.max( box.min );
  2154. this.max.min( box.max );
  2155. return this;
  2156. },
  2157. union: function ( box ) {
  2158. this.min.min( box.min );
  2159. this.max.max( box.max );
  2160. return this;
  2161. },
  2162. applyMatrix4: function() {
  2163. var points = [
  2164. new THREE.Vector3(),
  2165. new THREE.Vector3(),
  2166. new THREE.Vector3(),
  2167. new THREE.Vector3(),
  2168. new THREE.Vector3(),
  2169. new THREE.Vector3(),
  2170. new THREE.Vector3(),
  2171. new THREE.Vector3()
  2172. ];
  2173. return function ( matrix ) {
  2174. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2175. points[0].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2176. points[1].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2177. points[2].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2178. points[3].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2179. points[4].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2180. points[5].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2181. points[6].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2182. points[7].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2183. this.makeEmpty();
  2184. this.setFromPoints( points );
  2185. return this;
  2186. };
  2187. }(),
  2188. translate: function ( offset ) {
  2189. this.min.add( offset );
  2190. this.max.add( offset );
  2191. return this;
  2192. },
  2193. equals: function ( box ) {
  2194. return box.min.equals( this.min ) && box.max.equals( this.max );
  2195. },
  2196. clone: function () {
  2197. return new THREE.Box3().copy( this );
  2198. }
  2199. };
  2200. /**
  2201. * @author alteredq / http://alteredqualia.com/
  2202. * @author WestLangley / http://github.com/WestLangley
  2203. * @author bhouston / http://exocortex.com
  2204. */
  2205. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2206. this.elements = new Float32Array(9);
  2207. this.set(
  2208. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0,
  2209. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0,
  2210. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1
  2211. );
  2212. };
  2213. THREE.Matrix3.prototype = {
  2214. constructor: THREE.Matrix3,
  2215. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2216. var te = this.elements;
  2217. te[0] = n11; te[3] = n12; te[6] = n13;
  2218. te[1] = n21; te[4] = n22; te[7] = n23;
  2219. te[2] = n31; te[5] = n32; te[8] = n33;
  2220. return this;
  2221. },
  2222. identity: function () {
  2223. this.set(
  2224. 1, 0, 0,
  2225. 0, 1, 0,
  2226. 0, 0, 1
  2227. );
  2228. return this;
  2229. },
  2230. copy: function ( m ) {
  2231. var me = m.elements;
  2232. this.set(
  2233. me[0], me[3], me[6],
  2234. me[1], me[4], me[7],
  2235. me[2], me[5], me[8]
  2236. );
  2237. return this;
  2238. },
  2239. multiplyVector3: function ( vector ) {
  2240. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2241. return vector.applyMatrix3( this );
  2242. },
  2243. multiplyVector3Array: function() {
  2244. var v1 = new THREE.Vector3();
  2245. return function ( a ) {
  2246. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2247. v1.x = a[ i ];
  2248. v1.y = a[ i + 1 ];
  2249. v1.z = a[ i + 2 ];
  2250. v1.applyMatrix3(this);
  2251. a[ i ] = v1.x;
  2252. a[ i + 1 ] = v1.y;
  2253. a[ i + 2 ] = v1.z;
  2254. }
  2255. return a;
  2256. };
  2257. }(),
  2258. multiplyScalar: function ( s ) {
  2259. var te = this.elements;
  2260. te[0] *= s; te[3] *= s; te[6] *= s;
  2261. te[1] *= s; te[4] *= s; te[7] *= s;
  2262. te[2] *= s; te[5] *= s; te[8] *= s;
  2263. return this;
  2264. },
  2265. determinant: function () {
  2266. var te = this.elements;
  2267. var a = te[0], b = te[1], c = te[2],
  2268. d = te[3], e = te[4], f = te[5],
  2269. g = te[6], h = te[7], i = te[8];
  2270. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  2271. },
  2272. getInverse: function ( matrix, throwOnInvertible ) {
  2273. // input: THREE.Matrix4
  2274. // ( based on http://code.google.com/p/webgl-mjs/ )
  2275. var me = matrix.elements;
  2276. var te = this.elements;
  2277. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  2278. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  2279. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  2280. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  2281. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  2282. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  2283. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  2284. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  2285. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  2286. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2287. // no inverse
  2288. if ( det === 0 ) {
  2289. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2290. if ( throwOnInvertible || false ) {
  2291. throw new Error( msg );
  2292. } else {
  2293. console.warn( msg );
  2294. }
  2295. this.identity();
  2296. return this;
  2297. }
  2298. this.multiplyScalar( 1.0 / det );
  2299. return this;
  2300. },
  2301. transpose: function () {
  2302. var tmp, m = this.elements;
  2303. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  2304. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  2305. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  2306. return this;
  2307. },
  2308. getNormalMatrix: function ( m ) {
  2309. // input: THREE.Matrix4
  2310. this.getInverse( m ).transpose();
  2311. return this;
  2312. },
  2313. transposeIntoArray: function ( r ) {
  2314. var m = this.elements;
  2315. r[ 0 ] = m[ 0 ];
  2316. r[ 1 ] = m[ 3 ];
  2317. r[ 2 ] = m[ 6 ];
  2318. r[ 3 ] = m[ 1 ];
  2319. r[ 4 ] = m[ 4 ];
  2320. r[ 5 ] = m[ 7 ];
  2321. r[ 6 ] = m[ 2 ];
  2322. r[ 7 ] = m[ 5 ];
  2323. r[ 8 ] = m[ 8 ];
  2324. return this;
  2325. },
  2326. clone: function () {
  2327. var te = this.elements;
  2328. return new THREE.Matrix3(
  2329. te[0], te[3], te[6],
  2330. te[1], te[4], te[7],
  2331. te[2], te[5], te[8]
  2332. );
  2333. }
  2334. };
  2335. /**
  2336. * @author mrdoob / http://mrdoob.com/
  2337. * @author supereggbert / http://www.paulbrunt.co.uk/
  2338. * @author philogb / http://blog.thejit.org/
  2339. * @author jordi_ros / http://plattsoft.com
  2340. * @author D1plo1d / http://github.com/D1plo1d
  2341. * @author alteredq / http://alteredqualia.com/
  2342. * @author mikael emtinger / http://gomo.se/
  2343. * @author timknip / http://www.floorplanner.com/
  2344. * @author bhouston / http://exocortex.com
  2345. * @author WestLangley / http://github.com/WestLangley
  2346. */
  2347. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2348. this.elements = new Float32Array( 16 );
  2349. // TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix
  2350. // we should not support semi specification of Matrix4, it is just weird.
  2351. var te = this.elements;
  2352. te[0] = ( n11 !== undefined ) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  2353. te[1] = n21 || 0; te[5] = ( n22 !== undefined ) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  2354. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = ( n33 !== undefined ) ? n33 : 1; te[14] = n34 || 0;
  2355. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = ( n44 !== undefined ) ? n44 : 1;
  2356. };
  2357. THREE.Matrix4.prototype = {
  2358. constructor: THREE.Matrix4,
  2359. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2360. var te = this.elements;
  2361. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  2362. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  2363. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  2364. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  2365. return this;
  2366. },
  2367. identity: function () {
  2368. this.set(
  2369. 1, 0, 0, 0,
  2370. 0, 1, 0, 0,
  2371. 0, 0, 1, 0,
  2372. 0, 0, 0, 1
  2373. );
  2374. return this;
  2375. },
  2376. copy: function ( m ) {
  2377. this.elements.set( m.elements );
  2378. return this;
  2379. },
  2380. extractPosition: function ( m ) {
  2381. console.warn( 'DEPRECATED: Matrix4\'s .extractPosition() has been renamed to .copyPosition().' );
  2382. return this.copyPosition( m );
  2383. },
  2384. copyPosition: function ( m ) {
  2385. var te = this.elements;
  2386. var me = m.elements;
  2387. te[12] = me[12];
  2388. te[13] = me[13];
  2389. te[14] = me[14];
  2390. return this;
  2391. },
  2392. extractRotation: function () {
  2393. var v1 = new THREE.Vector3();
  2394. return function ( m ) {
  2395. var te = this.elements;
  2396. var me = m.elements;
  2397. var scaleX = 1 / v1.set( me[0], me[1], me[2] ).length();
  2398. var scaleY = 1 / v1.set( me[4], me[5], me[6] ).length();
  2399. var scaleZ = 1 / v1.set( me[8], me[9], me[10] ).length();
  2400. te[0] = me[0] * scaleX;
  2401. te[1] = me[1] * scaleX;
  2402. te[2] = me[2] * scaleX;
  2403. te[4] = me[4] * scaleY;
  2404. te[5] = me[5] * scaleY;
  2405. te[6] = me[6] * scaleY;
  2406. te[8] = me[8] * scaleZ;
  2407. te[9] = me[9] * scaleZ;
  2408. te[10] = me[10] * scaleZ;
  2409. return this;
  2410. };
  2411. }(),
  2412. makeRotationFromEuler: function ( euler ) {
  2413. if ( typeof euler['order'] === undefined ) {
  2414. console.error( 'ERROR: Matrix\'s .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  2415. }
  2416. var te = this.elements;
  2417. var x = euler.x, y = euler.y, z = euler.z;
  2418. var a = Math.cos( x ), b = Math.sin( x );
  2419. var c = Math.cos( y ), d = Math.sin( y );
  2420. var e = Math.cos( z ), f = Math.sin( z );
  2421. if ( euler.order === undefined || euler.order === 'XYZ' ) {
  2422. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2423. te[0] = c * e;
  2424. te[4] = - c * f;
  2425. te[8] = d;
  2426. te[1] = af + be * d;
  2427. te[5] = ae - bf * d;
  2428. te[9] = - b * c;
  2429. te[2] = bf - ae * d;
  2430. te[6] = be + af * d;
  2431. te[10] = a * c;
  2432. } else if ( euler.order === 'YXZ' ) {
  2433. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2434. te[0] = ce + df * b;
  2435. te[4] = de * b - cf;
  2436. te[8] = a * d;
  2437. te[1] = a * f;
  2438. te[5] = a * e;
  2439. te[9] = - b;
  2440. te[2] = cf * b - de;
  2441. te[6] = df + ce * b;
  2442. te[10] = a * c;
  2443. } else if ( euler.order === 'ZXY' ) {
  2444. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2445. te[0] = ce - df * b;
  2446. te[4] = - a * f;
  2447. te[8] = de + cf * b;
  2448. te[1] = cf + de * b;
  2449. te[5] = a * e;
  2450. te[9] = df - ce * b;
  2451. te[2] = - a * d;
  2452. te[6] = b;
  2453. te[10] = a * c;
  2454. } else if ( euler.order === 'ZYX' ) {
  2455. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2456. te[0] = c * e;
  2457. te[4] = be * d - af;
  2458. te[8] = ae * d + bf;
  2459. te[1] = c * f;
  2460. te[5] = bf * d + ae;
  2461. te[9] = af * d - be;
  2462. te[2] = - d;
  2463. te[6] = b * c;
  2464. te[10] = a * c;
  2465. } else if ( euler.order === 'YZX' ) {
  2466. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2467. te[0] = c * e;
  2468. te[4] = bd - ac * f;
  2469. te[8] = bc * f + ad;
  2470. te[1] = f;
  2471. te[5] = a * e;
  2472. te[9] = - b * e;
  2473. te[2] = - d * e;
  2474. te[6] = ad * f + bc;
  2475. te[10] = ac - bd * f;
  2476. } else if ( euler.order === 'XZY' ) {
  2477. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2478. te[0] = c * e;
  2479. te[4] = - f;
  2480. te[8] = d * e;
  2481. te[1] = ac * f + bd;
  2482. te[5] = a * e;
  2483. te[9] = ad * f - bc;
  2484. te[2] = bc * f - ad;
  2485. te[6] = b * e;
  2486. te[10] = bd * f + ac;
  2487. }
  2488. // last column
  2489. te[3] = 0;
  2490. te[7] = 0;
  2491. te[11] = 0;
  2492. // bottom row
  2493. te[12] = 0;
  2494. te[13] = 0;
  2495. te[14] = 0;
  2496. te[15] = 1;
  2497. return this;
  2498. },
  2499. setRotationFromQuaternion: function ( q ) {
  2500. console.warn( 'DEPRECATED: Matrix4\'s .setRotationFromQuaternion() has been deprecated in favor of makeRotationFromQuaternion. Please update your code.' );
  2501. return this.makeRotationFromQuaternion( q );
  2502. },
  2503. makeRotationFromQuaternion: function ( q ) {
  2504. var te = this.elements;
  2505. var x = q.x, y = q.y, z = q.z, w = q.w;
  2506. var x2 = x + x, y2 = y + y, z2 = z + z;
  2507. var xx = x * x2, xy = x * y2, xz = x * z2;
  2508. var yy = y * y2, yz = y * z2, zz = z * z2;
  2509. var wx = w * x2, wy = w * y2, wz = w * z2;
  2510. te[0] = 1 - ( yy + zz );
  2511. te[4] = xy - wz;
  2512. te[8] = xz + wy;
  2513. te[1] = xy + wz;
  2514. te[5] = 1 - ( xx + zz );
  2515. te[9] = yz - wx;
  2516. te[2] = xz - wy;
  2517. te[6] = yz + wx;
  2518. te[10] = 1 - ( xx + yy );
  2519. // last column
  2520. te[3] = 0;
  2521. te[7] = 0;
  2522. te[11] = 0;
  2523. // bottom row
  2524. te[12] = 0;
  2525. te[13] = 0;
  2526. te[14] = 0;
  2527. te[15] = 1;
  2528. return this;
  2529. },
  2530. lookAt: function() {
  2531. var x = new THREE.Vector3();
  2532. var y = new THREE.Vector3();
  2533. var z = new THREE.Vector3();
  2534. return function ( eye, target, up ) {
  2535. var te = this.elements;
  2536. z.subVectors( eye, target ).normalize();
  2537. if ( z.length() === 0 ) {
  2538. z.z = 1;
  2539. }
  2540. x.crossVectors( up, z ).normalize();
  2541. if ( x.length() === 0 ) {
  2542. z.x += 0.0001;
  2543. x.crossVectors( up, z ).normalize();
  2544. }
  2545. y.crossVectors( z, x );
  2546. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  2547. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  2548. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  2549. return this;
  2550. };
  2551. }(),
  2552. multiply: function ( m, n ) {
  2553. if ( n !== undefined ) {
  2554. console.warn( 'DEPRECATED: Matrix4\'s .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2555. return this.multiplyMatrices( m, n );
  2556. }
  2557. return this.multiplyMatrices( this, m );
  2558. },
  2559. multiplyMatrices: function ( a, b ) {
  2560. var ae = a.elements;
  2561. var be = b.elements;
  2562. var te = this.elements;
  2563. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  2564. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  2565. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  2566. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  2567. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  2568. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  2569. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  2570. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  2571. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2572. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2573. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2574. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2575. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2576. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2577. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2578. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2579. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2580. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2581. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2582. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2583. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2584. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2585. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2586. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2587. return this;
  2588. },
  2589. multiplyToArray: function ( a, b, r ) {
  2590. var te = this.elements;
  2591. this.multiplyMatrices( a, b );
  2592. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  2593. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  2594. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  2595. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  2596. return this;
  2597. },
  2598. multiplyScalar: function ( s ) {
  2599. var te = this.elements;
  2600. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  2601. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  2602. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  2603. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  2604. return this;
  2605. },
  2606. multiplyVector3: function ( vector ) {
  2607. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2608. return vector.applyProjection( this );
  2609. },
  2610. multiplyVector4: function ( vector ) {
  2611. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2612. return vector.applyMatrix4( this );
  2613. },
  2614. multiplyVector3Array: function() {
  2615. var v1 = new THREE.Vector3();
  2616. return function ( a ) {
  2617. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2618. v1.x = a[ i ];
  2619. v1.y = a[ i + 1 ];
  2620. v1.z = a[ i + 2 ];
  2621. v1.applyProjection( this );
  2622. a[ i ] = v1.x;
  2623. a[ i + 1 ] = v1.y;
  2624. a[ i + 2 ] = v1.z;
  2625. }
  2626. return a;
  2627. };
  2628. }(),
  2629. rotateAxis: function ( v ) {
  2630. console.warn( 'DEPRECATED: Matrix4\'s .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2631. v.transformDirection( this );
  2632. },
  2633. crossVector: function ( vector ) {
  2634. console.warn( 'DEPRECATED: Matrix4\'s .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2635. return vector.applyMatrix4( this );
  2636. },
  2637. determinant: function () {
  2638. var te = this.elements;
  2639. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  2640. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  2641. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  2642. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  2643. //TODO: make this more efficient
  2644. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2645. return (
  2646. n41 * (
  2647. +n14 * n23 * n32
  2648. -n13 * n24 * n32
  2649. -n14 * n22 * n33
  2650. +n12 * n24 * n33
  2651. +n13 * n22 * n34
  2652. -n12 * n23 * n34
  2653. ) +
  2654. n42 * (
  2655. +n11 * n23 * n34
  2656. -n11 * n24 * n33
  2657. +n14 * n21 * n33
  2658. -n13 * n21 * n34
  2659. +n13 * n24 * n31
  2660. -n14 * n23 * n31
  2661. ) +
  2662. n43 * (
  2663. +n11 * n24 * n32
  2664. -n11 * n22 * n34
  2665. -n14 * n21 * n32
  2666. +n12 * n21 * n34
  2667. +n14 * n22 * n31
  2668. -n12 * n24 * n31
  2669. ) +
  2670. n44 * (
  2671. -n13 * n22 * n31
  2672. -n11 * n23 * n32
  2673. +n11 * n22 * n33
  2674. +n13 * n21 * n32
  2675. -n12 * n21 * n33
  2676. +n12 * n23 * n31
  2677. )
  2678. );
  2679. },
  2680. transpose: function () {
  2681. var te = this.elements;
  2682. var tmp;
  2683. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  2684. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  2685. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  2686. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  2687. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  2688. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  2689. return this;
  2690. },
  2691. flattenToArray: function ( flat ) {
  2692. var te = this.elements;
  2693. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  2694. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  2695. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  2696. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  2697. return flat;
  2698. },
  2699. flattenToArrayOffset: function( flat, offset ) {
  2700. var te = this.elements;
  2701. flat[ offset ] = te[0];
  2702. flat[ offset + 1 ] = te[1];
  2703. flat[ offset + 2 ] = te[2];
  2704. flat[ offset + 3 ] = te[3];
  2705. flat[ offset + 4 ] = te[4];
  2706. flat[ offset + 5 ] = te[5];
  2707. flat[ offset + 6 ] = te[6];
  2708. flat[ offset + 7 ] = te[7];
  2709. flat[ offset + 8 ] = te[8];
  2710. flat[ offset + 9 ] = te[9];
  2711. flat[ offset + 10 ] = te[10];
  2712. flat[ offset + 11 ] = te[11];
  2713. flat[ offset + 12 ] = te[12];
  2714. flat[ offset + 13 ] = te[13];
  2715. flat[ offset + 14 ] = te[14];
  2716. flat[ offset + 15 ] = te[15];
  2717. return flat;
  2718. },
  2719. getPosition: function() {
  2720. var v1 = new THREE.Vector3();
  2721. return function () {
  2722. console.warn( 'DEPRECATED: Matrix4\'s .getPosition() has been removed. Use Vector3.getPositionFromMatrix( matrix ) instead.' );
  2723. var te = this.elements;
  2724. return v1.set( te[12], te[13], te[14] );
  2725. };
  2726. }(),
  2727. setPosition: function ( v ) {
  2728. var te = this.elements;
  2729. te[12] = v.x;
  2730. te[13] = v.y;
  2731. te[14] = v.z;
  2732. return this;
  2733. },
  2734. getInverse: function ( m, throwOnInvertible ) {
  2735. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2736. var te = this.elements;
  2737. var me = m.elements;
  2738. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2739. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2740. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2741. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2742. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2743. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2744. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2745. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2746. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2747. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2748. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2749. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2750. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2751. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2752. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2753. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2754. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2755. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2756. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2757. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2758. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  2759. if ( det == 0 ) {
  2760. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2761. if ( throwOnInvertible || false ) {
  2762. throw new Error( msg );
  2763. } else {
  2764. console.warn( msg );
  2765. }
  2766. this.identity();
  2767. return this;
  2768. }
  2769. this.multiplyScalar( 1 / det );
  2770. return this;
  2771. },
  2772. translate: function ( v ) {
  2773. console.warn( 'DEPRECATED: Matrix4\'s .translate() has been removed.');
  2774. },
  2775. rotateX: function ( angle ) {
  2776. console.warn( 'DEPRECATED: Matrix4\'s .rotateX() has been removed.');
  2777. },
  2778. rotateY: function ( angle ) {
  2779. console.warn( 'DEPRECATED: Matrix4\'s .rotateY() has been removed.');
  2780. },
  2781. rotateZ: function ( angle ) {
  2782. console.warn( 'DEPRECATED: Matrix4\'s .rotateZ() has been removed.');
  2783. },
  2784. rotateByAxis: function ( axis, angle ) {
  2785. console.warn( 'DEPRECATED: Matrix4\'s .rotateByAxis() has been removed.');
  2786. },
  2787. scale: function ( v ) {
  2788. var te = this.elements;
  2789. var x = v.x, y = v.y, z = v.z;
  2790. te[0] *= x; te[4] *= y; te[8] *= z;
  2791. te[1] *= x; te[5] *= y; te[9] *= z;
  2792. te[2] *= x; te[6] *= y; te[10] *= z;
  2793. te[3] *= x; te[7] *= y; te[11] *= z;
  2794. return this;
  2795. },
  2796. getMaxScaleOnAxis: function () {
  2797. var te = this.elements;
  2798. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2799. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2800. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2801. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2802. },
  2803. makeTranslation: function ( x, y, z ) {
  2804. this.set(
  2805. 1, 0, 0, x,
  2806. 0, 1, 0, y,
  2807. 0, 0, 1, z,
  2808. 0, 0, 0, 1
  2809. );
  2810. return this;
  2811. },
  2812. makeRotationX: function ( theta ) {
  2813. var c = Math.cos( theta ), s = Math.sin( theta );
  2814. this.set(
  2815. 1, 0, 0, 0,
  2816. 0, c, -s, 0,
  2817. 0, s, c, 0,
  2818. 0, 0, 0, 1
  2819. );
  2820. return this;
  2821. },
  2822. makeRotationY: function ( theta ) {
  2823. var c = Math.cos( theta ), s = Math.sin( theta );
  2824. this.set(
  2825. c, 0, s, 0,
  2826. 0, 1, 0, 0,
  2827. -s, 0, c, 0,
  2828. 0, 0, 0, 1
  2829. );
  2830. return this;
  2831. },
  2832. makeRotationZ: function ( theta ) {
  2833. var c = Math.cos( theta ), s = Math.sin( theta );
  2834. this.set(
  2835. c, -s, 0, 0,
  2836. s, c, 0, 0,
  2837. 0, 0, 1, 0,
  2838. 0, 0, 0, 1
  2839. );
  2840. return this;
  2841. },
  2842. makeRotationAxis: function ( axis, angle ) {
  2843. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2844. var c = Math.cos( angle );
  2845. var s = Math.sin( angle );
  2846. var t = 1 - c;
  2847. var x = axis.x, y = axis.y, z = axis.z;
  2848. var tx = t * x, ty = t * y;
  2849. this.set(
  2850. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2851. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2852. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2853. 0, 0, 0, 1
  2854. );
  2855. return this;
  2856. },
  2857. makeScale: function ( x, y, z ) {
  2858. this.set(
  2859. x, 0, 0, 0,
  2860. 0, y, 0, 0,
  2861. 0, 0, z, 0,
  2862. 0, 0, 0, 1
  2863. );
  2864. return this;
  2865. },
  2866. compose: function ( position, quaternion, scale ) {
  2867. this.makeRotationFromQuaternion( quaternion );
  2868. this.scale( scale );
  2869. this.setPosition( position );
  2870. return this;
  2871. },
  2872. decompose: function () {
  2873. var vector = new THREE.Vector3();
  2874. var matrix = new THREE.Matrix4();
  2875. return function ( position, quaternion, scale ) {
  2876. var te = this.elements;
  2877. var sx = vector.set( te[0], te[1], te[2] ).length();
  2878. var sy = vector.set( te[4], te[5], te[6] ).length();
  2879. var sz = vector.set( te[8], te[9], te[10] ).length();
  2880. position.x = te[12];
  2881. position.y = te[13];
  2882. position.z = te[14];
  2883. // scale the rotation part
  2884. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  2885. matrix.elements[0] /= sx;
  2886. matrix.elements[1] /= sx;
  2887. matrix.elements[2] /= sx;
  2888. matrix.elements[4] /= sy;
  2889. matrix.elements[5] /= sy;
  2890. matrix.elements[6] /= sy;
  2891. matrix.elements[8] /= sz;
  2892. matrix.elements[9] /= sz;
  2893. matrix.elements[10] /= sz;
  2894. quaternion.setFromRotationMatrix( matrix );
  2895. scale.x = sx;
  2896. scale.y = sy;
  2897. scale.z = sz;
  2898. return this;
  2899. };
  2900. }(),
  2901. makeFrustum: function ( left, right, bottom, top, near, far ) {
  2902. var te = this.elements;
  2903. var x = 2 * near / ( right - left );
  2904. var y = 2 * near / ( top - bottom );
  2905. var a = ( right + left ) / ( right - left );
  2906. var b = ( top + bottom ) / ( top - bottom );
  2907. var c = - ( far + near ) / ( far - near );
  2908. var d = - 2 * far * near / ( far - near );
  2909. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  2910. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  2911. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  2912. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  2913. return this;
  2914. },
  2915. makePerspective: function ( fov, aspect, near, far ) {
  2916. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  2917. var ymin = - ymax;
  2918. var xmin = ymin * aspect;
  2919. var xmax = ymax * aspect;
  2920. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  2921. },
  2922. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2923. var te = this.elements;
  2924. var w = right - left;
  2925. var h = top - bottom;
  2926. var p = far - near;
  2927. var x = ( right + left ) / w;
  2928. var y = ( top + bottom ) / h;
  2929. var z = ( far + near ) / p;
  2930. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  2931. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  2932. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  2933. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  2934. return this;
  2935. },
  2936. fromArray: function ( array ) {
  2937. this.elements.set( array );
  2938. return this;
  2939. },
  2940. toArray: function () {
  2941. var te = this.elements;
  2942. return [
  2943. te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ],
  2944. te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ],
  2945. te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ],
  2946. te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ]
  2947. ];
  2948. },
  2949. clone: function () {
  2950. var te = this.elements;
  2951. return new THREE.Matrix4(
  2952. te[0], te[4], te[8], te[12],
  2953. te[1], te[5], te[9], te[13],
  2954. te[2], te[6], te[10], te[14],
  2955. te[3], te[7], te[11], te[15]
  2956. );
  2957. }
  2958. };
  2959. /**
  2960. * @author bhouston / http://exocortex.com
  2961. */
  2962. THREE.Ray = function ( origin, direction ) {
  2963. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  2964. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  2965. };
  2966. THREE.Ray.prototype = {
  2967. constructor: THREE.Ray,
  2968. set: function ( origin, direction ) {
  2969. this.origin.copy( origin );
  2970. this.direction.copy( direction );
  2971. return this;
  2972. },
  2973. copy: function ( ray ) {
  2974. this.origin.copy( ray.origin );
  2975. this.direction.copy( ray.direction );
  2976. return this;
  2977. },
  2978. at: function( t, optionalTarget ) {
  2979. var result = optionalTarget || new THREE.Vector3();
  2980. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  2981. },
  2982. recast: function() {
  2983. var v1 = new THREE.Vector3();
  2984. return function ( t ) {
  2985. this.origin.copy( this.at( t, v1 ) );
  2986. return this;
  2987. };
  2988. }(),
  2989. closestPointToPoint: function ( point, optionalTarget ) {
  2990. var result = optionalTarget || new THREE.Vector3();
  2991. result.subVectors( point, this.origin );
  2992. var directionDistance = result.dot( this.direction );
  2993. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  2994. },
  2995. distanceToPoint: function() {
  2996. var v1 = new THREE.Vector3();
  2997. return function ( point ) {
  2998. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  2999. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3000. return v1.distanceTo( point );
  3001. };
  3002. }(),
  3003. isIntersectionSphere: function( sphere ) {
  3004. return ( this.distanceToPoint( sphere.center ) <= sphere.radius );
  3005. },
  3006. isIntersectionPlane: function ( plane ) {
  3007. // check if the line and plane are non-perpendicular, if they
  3008. // eventually they will intersect.
  3009. var denominator = plane.normal.dot( this.direction );
  3010. if ( denominator != 0 ) {
  3011. return true;
  3012. }
  3013. // line is coplanar, return origin
  3014. if( plane.distanceToPoint( this.origin ) == 0 ) {
  3015. return true;
  3016. }
  3017. return false;
  3018. },
  3019. distanceToPlane: function ( plane ) {
  3020. var denominator = plane.normal.dot( this.direction );
  3021. if ( denominator == 0 ) {
  3022. // line is coplanar, return origin
  3023. if( plane.distanceToPoint( this.origin ) == 0 ) {
  3024. return 0;
  3025. }
  3026. // Unsure if this is the correct method to handle this case.
  3027. return undefined;
  3028. }
  3029. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3030. return t;
  3031. },
  3032. intersectPlane: function ( plane, optionalTarget ) {
  3033. var t = this.distanceToPlane( plane );
  3034. if ( t === undefined ) {
  3035. return undefined;
  3036. }
  3037. return this.at( t, optionalTarget );
  3038. },
  3039. applyMatrix4: function ( matrix4 ) {
  3040. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3041. this.origin.applyMatrix4( matrix4 );
  3042. this.direction.sub( this.origin );
  3043. return this;
  3044. },
  3045. equals: function ( ray ) {
  3046. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3047. },
  3048. clone: function () {
  3049. return new THREE.Ray().copy( this );
  3050. }
  3051. };
  3052. /**
  3053. * @author bhouston / http://exocortex.com
  3054. * @author mrdoob / http://mrdoob.com/
  3055. */
  3056. THREE.Sphere = function ( center, radius ) {
  3057. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3058. this.radius = ( radius !== undefined ) ? radius : 0;
  3059. };
  3060. THREE.Sphere.prototype = {
  3061. constructor: THREE.Sphere,
  3062. set: function ( center, radius ) {
  3063. this.center.copy( center );
  3064. this.radius = radius;
  3065. return this;
  3066. },
  3067. setFromPoints: function ( points ) {
  3068. var radiusSq, maxRadiusSq = 0;
  3069. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3070. radiusSq = points[ i ].lengthSq();
  3071. maxRadiusSq = Math.max( maxRadiusSq, radiusSq );
  3072. }
  3073. this.center.set( 0, 0, 0 );
  3074. this.radius = Math.sqrt( maxRadiusSq );
  3075. return this;
  3076. },
  3077. copy: function ( sphere ) {
  3078. this.center.copy( sphere.center );
  3079. this.radius = sphere.radius;
  3080. return this;
  3081. },
  3082. empty: function () {
  3083. return ( this.radius <= 0 );
  3084. },
  3085. containsPoint: function ( point ) {
  3086. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3087. },
  3088. distanceToPoint: function ( point ) {
  3089. return ( point.distanceTo( this.center ) - this.radius );
  3090. },
  3091. intersectsSphere: function ( sphere ) {
  3092. var radiusSum = this.radius + sphere.radius;
  3093. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3094. },
  3095. clampPoint: function ( point, optionalTarget ) {
  3096. var deltaLengthSq = this.center.distanceToSquared( point );
  3097. var result = optionalTarget || new THREE.Vector3();
  3098. result.copy( point );
  3099. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3100. result.sub( this.center ).normalize();
  3101. result.multiplyScalar( this.radius ).add( this.center );
  3102. }
  3103. return result;
  3104. },
  3105. getBoundingBox: function ( optionalTarget ) {
  3106. var box = optionalTarget || new THREE.Box3();
  3107. box.set( this.center, this.center );
  3108. box.expandByScalar( this.radius );
  3109. return box;
  3110. },
  3111. applyMatrix4: function ( matrix ) {
  3112. this.center.applyMatrix4( matrix );
  3113. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3114. return this;
  3115. },
  3116. translate: function ( offset ) {
  3117. this.center.add( offset );
  3118. return this;
  3119. },
  3120. equals: function ( sphere ) {
  3121. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3122. },
  3123. clone: function () {
  3124. return new THREE.Sphere().copy( this );
  3125. }
  3126. };
  3127. /**
  3128. * @author mrdoob / http://mrdoob.com/
  3129. * @author alteredq / http://alteredqualia.com/
  3130. * @author bhouston / http://exocortex.com
  3131. */
  3132. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3133. this.planes = [
  3134. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3135. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3136. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3137. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3138. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3139. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3140. ];
  3141. };
  3142. THREE.Frustum.prototype = {
  3143. constructor: THREE.Frustum,
  3144. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3145. var planes = this.planes;
  3146. planes[0].copy( p0 );
  3147. planes[1].copy( p1 );
  3148. planes[2].copy( p2 );
  3149. planes[3].copy( p3 );
  3150. planes[4].copy( p4 );
  3151. planes[5].copy( p5 );
  3152. return this;
  3153. },
  3154. copy: function ( frustum ) {
  3155. var planes = this.planes;
  3156. for( var i = 0; i < 6; i ++ ) {
  3157. planes[i].copy( frustum.planes[i] );
  3158. }
  3159. return this;
  3160. },
  3161. setFromMatrix: function ( m ) {
  3162. var planes = this.planes;
  3163. var me = m.elements;
  3164. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  3165. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  3166. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  3167. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  3168. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3169. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3170. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3171. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3172. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3173. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3174. return this;
  3175. },
  3176. intersectsObject: function () {
  3177. var center = new THREE.Vector3();
  3178. return function ( object ) {
  3179. // this method is expanded inlined for performance reasons.
  3180. var matrix = object.matrixWorld;
  3181. var planes = this.planes;
  3182. var negRadius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  3183. center.getPositionFromMatrix( matrix );
  3184. for ( var i = 0; i < 6; i ++ ) {
  3185. var distance = planes[ i ].distanceToPoint( center );
  3186. if ( distance < negRadius ) {
  3187. return false;
  3188. }
  3189. }
  3190. return true;
  3191. };
  3192. }(),
  3193. intersectsSphere: function ( sphere ) {
  3194. var planes = this.planes;
  3195. var center = sphere.center;
  3196. var negRadius = -sphere.radius;
  3197. for ( var i = 0; i < 6; i ++ ) {
  3198. var distance = planes[ i ].distanceToPoint( center );
  3199. if ( distance < negRadius ) {
  3200. return false;
  3201. }
  3202. }
  3203. return true;
  3204. },
  3205. containsPoint: function ( point ) {
  3206. var planes = this.planes;
  3207. for ( var i = 0; i < 6; i ++ ) {
  3208. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3209. return false;
  3210. }
  3211. }
  3212. return true;
  3213. },
  3214. clone: function () {
  3215. return new THREE.Frustum().copy( this );
  3216. }
  3217. };
  3218. /**
  3219. * @author bhouston / http://exocortex.com
  3220. */
  3221. THREE.Plane = function ( normal, constant ) {
  3222. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3223. this.constant = ( constant !== undefined ) ? constant : 0;
  3224. };
  3225. THREE.Plane.prototype = {
  3226. constructor: THREE.Plane,
  3227. set: function ( normal, constant ) {
  3228. this.normal.copy( normal );
  3229. this.constant = constant;
  3230. return this;
  3231. },
  3232. setComponents: function ( x, y, z, w ) {
  3233. this.normal.set( x, y, z );
  3234. this.constant = w;
  3235. return this;
  3236. },
  3237. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3238. this.normal.copy( normal );
  3239. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3240. return this;
  3241. },
  3242. setFromCoplanarPoints: function() {
  3243. var v1 = new THREE.Vector3();
  3244. var v2 = new THREE.Vector3();
  3245. return function ( a, b, c ) {
  3246. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3247. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3248. this.setFromNormalAndCoplanarPoint( normal, a );
  3249. return this;
  3250. };
  3251. }(),
  3252. copy: function ( plane ) {
  3253. this.normal.copy( plane.normal );
  3254. this.constant = plane.constant;
  3255. return this;
  3256. },
  3257. normalize: function () {
  3258. // Note: will lead to a divide by zero if the plane is invalid.
  3259. var inverseNormalLength = 1.0 / this.normal.length();
  3260. this.normal.multiplyScalar( inverseNormalLength );
  3261. this.constant *= inverseNormalLength;
  3262. return this;
  3263. },
  3264. negate: function () {
  3265. this.constant *= -1;
  3266. this.normal.negate();
  3267. return this;
  3268. },
  3269. distanceToPoint: function ( point ) {
  3270. return this.normal.dot( point ) + this.constant;
  3271. },
  3272. distanceToSphere: function ( sphere ) {
  3273. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3274. },
  3275. projectPoint: function ( point, optionalTarget ) {
  3276. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3277. },
  3278. orthoPoint: function ( point, optionalTarget ) {
  3279. var perpendicularMagnitude = this.distanceToPoint( point );
  3280. var result = optionalTarget || new THREE.Vector3();
  3281. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3282. },
  3283. isIntersectionLine: function ( line ) {
  3284. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3285. var startSign = this.distanceToPoint( line.start );
  3286. var endSign = this.distanceToPoint( line.end );
  3287. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3288. },
  3289. intersectLine: function() {
  3290. var v1 = new THREE.Vector3();
  3291. return function ( line, optionalTarget ) {
  3292. var result = optionalTarget || new THREE.Vector3();
  3293. var direction = line.delta( v1 );
  3294. var denominator = this.normal.dot( direction );
  3295. if ( denominator == 0 ) {
  3296. // line is coplanar, return origin
  3297. if( this.distanceToPoint( line.start ) == 0 ) {
  3298. return result.copy( line.start );
  3299. }
  3300. // Unsure if this is the correct method to handle this case.
  3301. return undefined;
  3302. }
  3303. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3304. if( t < 0 || t > 1 ) {
  3305. return undefined;
  3306. }
  3307. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3308. };
  3309. }(),
  3310. coplanarPoint: function ( optionalTarget ) {
  3311. var result = optionalTarget || new THREE.Vector3();
  3312. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3313. },
  3314. applyMatrix4: function() {
  3315. var v1 = new THREE.Vector3();
  3316. var v2 = new THREE.Vector3();
  3317. return function ( matrix, optionalNormalMatrix ) {
  3318. // compute new normal based on theory here:
  3319. // http://www.songho.ca/opengl/gl_normaltransform.html
  3320. optionalNormalMatrix = optionalNormalMatrix || new THREE.Matrix3().getNormalMatrix( matrix );
  3321. var newNormal = v1.copy( this.normal ).applyMatrix3( optionalNormalMatrix );
  3322. var newCoplanarPoint = this.coplanarPoint( v2 );
  3323. newCoplanarPoint.applyMatrix4( matrix );
  3324. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3325. return this;
  3326. };
  3327. }(),
  3328. translate: function ( offset ) {
  3329. this.constant = this.constant - offset.dot( this.normal );
  3330. return this;
  3331. },
  3332. equals: function ( plane ) {
  3333. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3334. },
  3335. clone: function () {
  3336. return new THREE.Plane().copy( this );
  3337. }
  3338. };
  3339. /**
  3340. * @author alteredq / http://alteredqualia.com/
  3341. * @author mrdoob / http://mrdoob.com/
  3342. */
  3343. THREE.Math = {
  3344. PI2: Math.PI * 2,
  3345. generateUUID: function () {
  3346. // http://www.broofa.com/Tools/Math.uuid.htm
  3347. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  3348. var uuid = new Array(36);
  3349. var rnd = 0, r;
  3350. return function () {
  3351. for ( var i = 0; i < 36; i ++ ) {
  3352. if ( i == 8 || i == 13 || i == 18 || i == 23 ) {
  3353. uuid[ i ] = '-';
  3354. } else if ( i == 14 ) {
  3355. uuid[ i ] = '4';
  3356. } else {
  3357. if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
  3358. r = rnd & 0xf;
  3359. rnd = rnd >> 4;
  3360. uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
  3361. }
  3362. }
  3363. return uuid.join('');
  3364. };
  3365. }(),
  3366. // Clamp value to range <a, b>
  3367. clamp: function ( x, a, b ) {
  3368. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3369. },
  3370. // Clamp value to range <a, inf)
  3371. clampBottom: function ( x, a ) {
  3372. return x < a ? a : x;
  3373. },
  3374. // Linear mapping from range <a1, a2> to range <b1, b2>
  3375. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3376. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3377. },
  3378. // http://en.wikipedia.org/wiki/Smoothstep
  3379. smoothstep: function ( x, min, max ) {
  3380. if ( x <= min ) return 0;
  3381. if ( x >= max ) return 1;
  3382. x = ( x - min )/( max - min );
  3383. return x*x*(3 - 2*x);
  3384. },
  3385. smootherstep: function ( x, min, max ) {
  3386. if ( x <= min ) return 0;
  3387. if ( x >= max ) return 1;
  3388. x = ( x - min )/( max - min );
  3389. return x*x*x*(x*(x*6 - 15) + 10);
  3390. },
  3391. // Random float from <0, 1> with 16 bits of randomness
  3392. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3393. random16: function () {
  3394. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3395. },
  3396. // Random integer from <low, high> interval
  3397. randInt: function ( low, high ) {
  3398. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  3399. },
  3400. // Random float from <low, high> interval
  3401. randFloat: function ( low, high ) {
  3402. return low + Math.random() * ( high - low );
  3403. },
  3404. // Random float from <-range/2, range/2> interval
  3405. randFloatSpread: function ( range ) {
  3406. return range * ( 0.5 - Math.random() );
  3407. },
  3408. sign: function ( x ) {
  3409. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  3410. },
  3411. degToRad: function() {
  3412. var degreeToRadiansFactor = Math.PI / 180;
  3413. return function ( degrees ) {
  3414. return degrees * degreeToRadiansFactor;
  3415. };
  3416. }(),
  3417. radToDeg: function() {
  3418. var radianToDegreesFactor = 180 / Math.PI;
  3419. return function ( radians ) {
  3420. return radians * radianToDegreesFactor;
  3421. };
  3422. }()
  3423. };
  3424. /**
  3425. * Spline from Tween.js, slightly optimized (and trashed)
  3426. * http://sole.github.com/tween.js/examples/05_spline.html
  3427. *
  3428. * @author mrdoob / http://mrdoob.com/
  3429. * @author alteredq / http://alteredqualia.com/
  3430. */
  3431. THREE.Spline = function ( points ) {
  3432. this.points = points;
  3433. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3434. point, intPoint, weight, w2, w3,
  3435. pa, pb, pc, pd;
  3436. this.initFromArray = function( a ) {
  3437. this.points = [];
  3438. for ( var i = 0; i < a.length; i++ ) {
  3439. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3440. }
  3441. };
  3442. this.getPoint = function ( k ) {
  3443. point = ( this.points.length - 1 ) * k;
  3444. intPoint = Math.floor( point );
  3445. weight = point - intPoint;
  3446. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3447. c[ 1 ] = intPoint;
  3448. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3449. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3450. pa = this.points[ c[ 0 ] ];
  3451. pb = this.points[ c[ 1 ] ];
  3452. pc = this.points[ c[ 2 ] ];
  3453. pd = this.points[ c[ 3 ] ];
  3454. w2 = weight * weight;
  3455. w3 = weight * w2;
  3456. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3457. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3458. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3459. return v3;
  3460. };
  3461. this.getControlPointsArray = function () {
  3462. var i, p, l = this.points.length,
  3463. coords = [];
  3464. for ( i = 0; i < l; i ++ ) {
  3465. p = this.points[ i ];
  3466. coords[ i ] = [ p.x, p.y, p.z ];
  3467. }
  3468. return coords;
  3469. };
  3470. // approximate length by summing linear segments
  3471. this.getLength = function ( nSubDivisions ) {
  3472. var i, index, nSamples, position,
  3473. point = 0, intPoint = 0, oldIntPoint = 0,
  3474. oldPosition = new THREE.Vector3(),
  3475. tmpVec = new THREE.Vector3(),
  3476. chunkLengths = [],
  3477. totalLength = 0;
  3478. // first point has 0 length
  3479. chunkLengths[ 0 ] = 0;
  3480. if ( !nSubDivisions ) nSubDivisions = 100;
  3481. nSamples = this.points.length * nSubDivisions;
  3482. oldPosition.copy( this.points[ 0 ] );
  3483. for ( i = 1; i < nSamples; i ++ ) {
  3484. index = i / nSamples;
  3485. position = this.getPoint( index );
  3486. tmpVec.copy( position );
  3487. totalLength += tmpVec.distanceTo( oldPosition );
  3488. oldPosition.copy( position );
  3489. point = ( this.points.length - 1 ) * index;
  3490. intPoint = Math.floor( point );
  3491. if ( intPoint != oldIntPoint ) {
  3492. chunkLengths[ intPoint ] = totalLength;
  3493. oldIntPoint = intPoint;
  3494. }
  3495. }
  3496. // last point ends with total length
  3497. chunkLengths[ chunkLengths.length ] = totalLength;
  3498. return { chunks: chunkLengths, total: totalLength };
  3499. };
  3500. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3501. var i, j,
  3502. index, indexCurrent, indexNext,
  3503. linearDistance, realDistance,
  3504. sampling, position,
  3505. newpoints = [],
  3506. tmpVec = new THREE.Vector3(),
  3507. sl = this.getLength();
  3508. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3509. for ( i = 1; i < this.points.length; i++ ) {
  3510. //tmpVec.copy( this.points[ i - 1 ] );
  3511. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3512. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3513. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3514. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3515. indexNext = i / ( this.points.length - 1 );
  3516. for ( j = 1; j < sampling - 1; j++ ) {
  3517. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3518. position = this.getPoint( index );
  3519. newpoints.push( tmpVec.copy( position ).clone() );
  3520. }
  3521. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3522. }
  3523. this.points = newpoints;
  3524. };
  3525. // Catmull-Rom
  3526. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3527. var v0 = ( p2 - p0 ) * 0.5,
  3528. v1 = ( p3 - p1 ) * 0.5;
  3529. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3530. };
  3531. };
  3532. /**
  3533. * @author bhouston / http://exocortex.com
  3534. * @author mrdoob / http://mrdoob.com/
  3535. */
  3536. THREE.Triangle = function ( a, b, c ) {
  3537. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3538. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3539. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3540. };
  3541. THREE.Triangle.normal = function() {
  3542. var v0 = new THREE.Vector3();
  3543. return function ( a, b, c, optionalTarget ) {
  3544. var result = optionalTarget || new THREE.Vector3();
  3545. result.subVectors( c, b );
  3546. v0.subVectors( a, b );
  3547. result.cross( v0 );
  3548. var resultLengthSq = result.lengthSq();
  3549. if( resultLengthSq > 0 ) {
  3550. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3551. }
  3552. return result.set( 0, 0, 0 );
  3553. };
  3554. }();
  3555. // static/instance method to calculate barycoordinates
  3556. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3557. THREE.Triangle.barycoordFromPoint = function() {
  3558. var v0 = new THREE.Vector3();
  3559. var v1 = new THREE.Vector3();
  3560. var v2 = new THREE.Vector3();
  3561. return function ( point, a, b, c, optionalTarget ) {
  3562. v0.subVectors( c, a );
  3563. v1.subVectors( b, a );
  3564. v2.subVectors( point, a );
  3565. var dot00 = v0.dot( v0 );
  3566. var dot01 = v0.dot( v1 );
  3567. var dot02 = v0.dot( v2 );
  3568. var dot11 = v1.dot( v1 );
  3569. var dot12 = v1.dot( v2 );
  3570. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3571. var result = optionalTarget || new THREE.Vector3();
  3572. // colinear or singular triangle
  3573. if( denom == 0 ) {
  3574. // arbitrary location outside of triangle?
  3575. // not sure if this is the best idea, maybe should be returning undefined
  3576. return result.set( -2, -1, -1 );
  3577. }
  3578. var invDenom = 1 / denom;
  3579. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3580. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3581. // barycoordinates must always sum to 1
  3582. return result.set( 1 - u - v, v, u );
  3583. };
  3584. }();
  3585. THREE.Triangle.containsPoint = function() {
  3586. var v1 = new THREE.Vector3();
  3587. return function ( point, a, b, c ) {
  3588. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  3589. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3590. };
  3591. }();
  3592. THREE.Triangle.prototype = {
  3593. constructor: THREE.Triangle,
  3594. set: function ( a, b, c ) {
  3595. this.a.copy( a );
  3596. this.b.copy( b );
  3597. this.c.copy( c );
  3598. return this;
  3599. },
  3600. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3601. this.a.copy( points[i0] );
  3602. this.b.copy( points[i1] );
  3603. this.c.copy( points[i2] );
  3604. return this;
  3605. },
  3606. copy: function ( triangle ) {
  3607. this.a.copy( triangle.a );
  3608. this.b.copy( triangle.b );
  3609. this.c.copy( triangle.c );
  3610. return this;
  3611. },
  3612. area: function() {
  3613. var v0 = new THREE.Vector3();
  3614. var v1 = new THREE.Vector3();
  3615. return function () {
  3616. v0.subVectors( this.c, this.b );
  3617. v1.subVectors( this.a, this.b );
  3618. return v0.cross( v1 ).length() * 0.5;
  3619. };
  3620. }(),
  3621. midpoint: function ( optionalTarget ) {
  3622. var result = optionalTarget || new THREE.Vector3();
  3623. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  3624. },
  3625. normal: function ( optionalTarget ) {
  3626. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3627. },
  3628. plane: function ( optionalTarget ) {
  3629. var result = optionalTarget || new THREE.Plane();
  3630. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  3631. },
  3632. barycoordFromPoint: function ( point, optionalTarget ) {
  3633. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  3634. },
  3635. containsPoint: function ( point ) {
  3636. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  3637. },
  3638. equals: function ( triangle ) {
  3639. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  3640. },
  3641. clone: function () {
  3642. return new THREE.Triangle().copy( this );
  3643. }
  3644. };
  3645. /**
  3646. * @author mrdoob / http://mrdoob.com/
  3647. */
  3648. THREE.Vertex = function ( v ) {
  3649. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  3650. return v;
  3651. };
  3652. /**
  3653. * @author mrdoob / http://mrdoob.com/
  3654. */
  3655. THREE.UV = function ( u, v ) {
  3656. console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
  3657. return new THREE.Vector2( u, v );
  3658. };
  3659. /**
  3660. * @author alteredq / http://alteredqualia.com/
  3661. */
  3662. THREE.Clock = function ( autoStart ) {
  3663. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  3664. this.startTime = 0;
  3665. this.oldTime = 0;
  3666. this.elapsedTime = 0;
  3667. this.running = false;
  3668. };
  3669. THREE.Clock.prototype = {
  3670. constructor: THREE.Clock,
  3671. start: function () {
  3672. this.startTime = self.performance !== undefined && self.performance.now !== undefined
  3673. ? self.performance.now()
  3674. : Date.now();
  3675. this.oldTime = this.startTime;
  3676. this.running = true;
  3677. },
  3678. stop: function () {
  3679. this.getElapsedTime();
  3680. this.running = false;
  3681. },
  3682. getElapsedTime: function () {
  3683. this.getDelta();
  3684. return this.elapsedTime;
  3685. },
  3686. getDelta: function () {
  3687. var diff = 0;
  3688. if ( this.autoStart && ! this.running ) {
  3689. this.start();
  3690. }
  3691. if ( this.running ) {
  3692. var newTime = self.performance !== undefined && self.performance.now !== undefined
  3693. ? self.performance.now()
  3694. : Date.now();
  3695. diff = 0.001 * ( newTime - this.oldTime );
  3696. this.oldTime = newTime;
  3697. this.elapsedTime += diff;
  3698. }
  3699. return diff;
  3700. }
  3701. };
  3702. /**
  3703. * https://github.com/mrdoob/eventdispatcher.js/
  3704. */
  3705. THREE.EventDispatcher = function () {}
  3706. THREE.EventDispatcher.prototype = {
  3707. constructor: THREE.EventDispatcher,
  3708. addEventListener: function ( type, listener ) {
  3709. if ( this._listeners === undefined ) this._listeners = {};
  3710. var listeners = this._listeners;
  3711. if ( listeners[ type ] === undefined ) {
  3712. listeners[ type ] = [];
  3713. }
  3714. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  3715. listeners[ type ].push( listener );
  3716. }
  3717. },
  3718. hasEventListener: function ( type, listener ) {
  3719. if ( this._listeners === undefined ) return false;
  3720. var listeners = this._listeners;
  3721. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  3722. return true;
  3723. }
  3724. return false;
  3725. },
  3726. removeEventListener: function ( type, listener ) {
  3727. if ( this._listeners === undefined ) return;
  3728. var listeners = this._listeners;
  3729. var index = listeners[ type ].indexOf( listener );
  3730. if ( index !== - 1 ) {
  3731. listeners[ type ].splice( index, 1 );
  3732. }
  3733. },
  3734. dispatchEvent: function ( event ) {
  3735. if ( this._listeners === undefined ) return;
  3736. var listeners = this._listeners;
  3737. var listenerArray = listeners[ event.type ];
  3738. if ( listenerArray !== undefined ) {
  3739. event.target = this;
  3740. for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
  3741. listenerArray[ i ].call( this, event );
  3742. }
  3743. }
  3744. }
  3745. };
  3746. /**
  3747. * @author mrdoob / http://mrdoob.com/
  3748. * @author bhouston / http://exocortex.com/
  3749. */
  3750. ( function ( THREE ) {
  3751. THREE.Raycaster = function ( origin, direction, near, far ) {
  3752. this.ray = new THREE.Ray( origin, direction );
  3753. // normalized ray.direction required for accurate distance calculations
  3754. if ( this.ray.direction.lengthSq() > 0 ) {
  3755. this.ray.direction.normalize();
  3756. }
  3757. this.near = near || 0;
  3758. this.far = far || Infinity;
  3759. };
  3760. var sphere = new THREE.Sphere();
  3761. var localRay = new THREE.Ray();
  3762. var facePlane = new THREE.Plane();
  3763. var intersectPoint = new THREE.Vector3();
  3764. var matrixPosition = new THREE.Vector3();
  3765. var inverseMatrix = new THREE.Matrix4();
  3766. var descSort = function ( a, b ) {
  3767. return a.distance - b.distance;
  3768. };
  3769. var intersectObject = function ( object, raycaster, intersects ) {
  3770. if ( object instanceof THREE.Particle ) {
  3771. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3772. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  3773. if ( distance > object.scale.x ) {
  3774. return intersects;
  3775. }
  3776. intersects.push( {
  3777. distance: distance,
  3778. point: object.position,
  3779. face: null,
  3780. object: object
  3781. } );
  3782. } else if ( object instanceof THREE.LOD ) {
  3783. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3784. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  3785. intersectObject( object.getObjectForDistance( distance ), raycaster, intersects );
  3786. } else if (object instanceof THREE.Mesh ) {
  3787. // Checking boundingSphere distance to ray
  3788. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3789. sphere.set( matrixPosition, object.geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis() );
  3790. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  3791. return intersects;
  3792. }
  3793. var geometry = object.geometry;
  3794. var vertices = geometry.vertices;
  3795. if ( geometry instanceof THREE.BufferGeometry ) {
  3796. var material = object.material;
  3797. if ( material === undefined ) return intersects;
  3798. if ( ! geometry.dynamic ) return intersects;
  3799. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3800. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  3801. var side = object.material.side;
  3802. var a, b, c;
  3803. var precision = raycaster.precision;
  3804. inverseMatrix.getInverse( object.matrixWorld );
  3805. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  3806. var fl;
  3807. var indexed = false;
  3808. if ( geometry.attributes.index ) {
  3809. indexed = true;
  3810. fl = geometry.attributes.index.numItems / 3;
  3811. } else {
  3812. fl = geometry.attributes.position.numItems / 9;
  3813. }
  3814. var vA = new THREE.Vector3();
  3815. var vB = new THREE.Vector3();
  3816. var vC = new THREE.Vector3();
  3817. var vCB = new THREE.Vector3();
  3818. var vAB = new THREE.Vector3();
  3819. for ( var oi = 0; oi < geometry.offsets.length; ++oi ) {
  3820. var start = geometry.offsets[ oi ].start;
  3821. var count = geometry.offsets[ oi ].count;
  3822. var index = geometry.offsets[ oi ].index;
  3823. for ( var i = start, il = start + count; i < il; i += 3 ) {
  3824. if ( indexed ) {
  3825. a = index + geometry.attributes.index.array[ i ];
  3826. b = index + geometry.attributes.index.array[ i + 1 ];
  3827. c = index + geometry.attributes.index.array[ i + 2 ];
  3828. } else {
  3829. a = index;
  3830. b = index + 1;
  3831. c = index + 2;
  3832. }
  3833. vA.set( geometry.attributes.position.array[ a * 3 ],
  3834. geometry.attributes.position.array[ a * 3 + 1 ],
  3835. geometry.attributes.position.array[ a * 3 + 2] );
  3836. vB.set( geometry.attributes.position.array[ b * 3 ],
  3837. geometry.attributes.position.array[ b * 3 + 1 ],
  3838. geometry.attributes.position.array[ b * 3 + 2] );
  3839. vC.set( geometry.attributes.position.array[ c * 3 ],
  3840. geometry.attributes.position.array[ c * 3 + 1 ],
  3841. geometry.attributes.position.array[ c * 3 + 2 ] );
  3842. facePlane.setFromCoplanarPoints( vA, vB, vC );
  3843. var planeDistance = localRay.distanceToPlane( facePlane );
  3844. // bail if raycaster and plane are parallel
  3845. if ( Math.abs( planeDistance ) < precision ) continue;
  3846. // if negative distance, then plane is behind raycaster
  3847. if ( planeDistance < 0 ) continue;
  3848. // check if we hit the wrong side of a single sided face
  3849. side = material.side;
  3850. if ( side !== THREE.DoubleSide ) {
  3851. var planeSign = localRay.direction.dot( facePlane.normal );
  3852. if ( ! ( side === THREE.FrontSide ? planeSign < 0 : planeSign > 0 ) ) continue;
  3853. }
  3854. // this can be done using the planeDistance from localRay because localRay wasn't normalized, but ray was
  3855. if ( planeDistance < raycaster.near || planeDistance > raycaster.far ) continue;
  3856. intersectPoint = localRay.at( planeDistance, intersectPoint ); // passing in intersectPoint avoids a copy
  3857. if ( ! THREE.Triangle.containsPoint( intersectPoint, vA, vB, vC ) ) continue;
  3858. intersects.push( {
  3859. distance: planeDistance, // this works because the original ray was normalized, and the transformed localRay wasn't
  3860. point: raycaster.ray.at(planeDistance),
  3861. face: null,
  3862. faceIndex: null,
  3863. object: object
  3864. } );
  3865. }
  3866. }
  3867. } else if ( geometry instanceof THREE.Geometry ) {
  3868. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3869. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  3870. var side = object.material.side;
  3871. var a, b, c, d;
  3872. var precision = raycaster.precision;
  3873. inverseMatrix.getInverse( object.matrixWorld );
  3874. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  3875. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  3876. var face = geometry.faces[ f ];
  3877. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  3878. if ( material === undefined ) continue;
  3879. facePlane.setFromNormalAndCoplanarPoint( face.normal, vertices[face.a] );
  3880. var planeDistance = localRay.distanceToPlane( facePlane );
  3881. // bail if raycaster and plane are parallel
  3882. if ( Math.abs( planeDistance ) < precision ) continue;
  3883. // if negative distance, then plane is behind raycaster
  3884. if ( planeDistance < 0 ) continue;
  3885. // check if we hit the wrong side of a single sided face
  3886. side = material.side;
  3887. if ( side !== THREE.DoubleSide ) {
  3888. var planeSign = localRay.direction.dot( facePlane.normal );
  3889. if ( ! ( side === THREE.FrontSide ? planeSign < 0 : planeSign > 0 ) ) continue;
  3890. }
  3891. // this can be done using the planeDistance from localRay because localRay wasn't normalized, but ray was
  3892. if ( planeDistance < raycaster.near || planeDistance > raycaster.far ) continue;
  3893. intersectPoint = localRay.at( planeDistance, intersectPoint ); // passing in intersectPoint avoids a copy
  3894. if ( face instanceof THREE.Face3 ) {
  3895. a = vertices[ face.a ];
  3896. b = vertices[ face.b ];
  3897. c = vertices[ face.c ];
  3898. if ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, c ) ) continue;
  3899. } else if ( face instanceof THREE.Face4 ) {
  3900. a = vertices[ face.a ];
  3901. b = vertices[ face.b ];
  3902. c = vertices[ face.c ];
  3903. d = vertices[ face.d ];
  3904. if ( ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, d ) ) &&
  3905. ( ! THREE.Triangle.containsPoint( intersectPoint, b, c, d ) ) ) continue;
  3906. } else {
  3907. // This is added because if we call out of this if/else group when none of the cases
  3908. // match it will add a point to the intersection list erroneously.
  3909. throw Error( "face type not supported" );
  3910. }
  3911. intersects.push( {
  3912. distance: planeDistance, // this works because the original ray was normalized, and the transformed localRay wasn't
  3913. point: raycaster.ray.at( planeDistance ),
  3914. face: face,
  3915. faceIndex: f,
  3916. object: object
  3917. } );
  3918. }
  3919. }
  3920. }
  3921. };
  3922. var intersectDescendants = function ( object, raycaster, intersects ) {
  3923. var descendants = object.getDescendants();
  3924. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  3925. intersectObject( descendants[ i ], raycaster, intersects );
  3926. }
  3927. };
  3928. //
  3929. THREE.Raycaster.prototype.precision = 0.0001;
  3930. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  3931. this.ray.set( origin, direction );
  3932. // normalized ray.direction required for accurate distance calculations
  3933. if ( this.ray.direction.length() > 0 ) {
  3934. this.ray.direction.normalize();
  3935. }
  3936. };
  3937. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  3938. var intersects = [];
  3939. if ( recursive === true ) {
  3940. intersectDescendants( object, this, intersects );
  3941. }
  3942. intersectObject( object, this, intersects );
  3943. intersects.sort( descSort );
  3944. return intersects;
  3945. };
  3946. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  3947. var intersects = [];
  3948. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  3949. intersectObject( objects[ i ], this, intersects );
  3950. if ( recursive === true ) {
  3951. intersectDescendants( objects[ i ], this, intersects );
  3952. }
  3953. }
  3954. intersects.sort( descSort );
  3955. return intersects;
  3956. };
  3957. }( THREE ) );
  3958. /**
  3959. * @author mrdoob / http://mrdoob.com/
  3960. * @author mikael emtinger / http://gomo.se/
  3961. * @author alteredq / http://alteredqualia.com/
  3962. * @author WestLangley / http://github.com/WestLangley
  3963. */
  3964. THREE.Object3D = function () {
  3965. this.id = THREE.Math.generateUUID();
  3966. this.name = '';
  3967. this.parent = undefined;
  3968. this.children = [];
  3969. this.up = new THREE.Vector3( 0, 1, 0 );
  3970. this.position = new THREE.Vector3();
  3971. this.rotation = new THREE.Euler();
  3972. this.quaternion = new THREE.Quaternion();
  3973. this.scale = new THREE.Vector3( 1, 1, 1 );
  3974. // keep rotation and quaternion in sync
  3975. this.rotation._quaternion = this.quaternion;
  3976. this.quaternion._euler = this.rotation;
  3977. this.renderDepth = null;
  3978. this.rotationAutoUpdate = true;
  3979. this.matrix = new THREE.Matrix4();
  3980. this.matrixWorld = new THREE.Matrix4();
  3981. this.matrixAutoUpdate = true;
  3982. this.matrixWorldNeedsUpdate = true;
  3983. this.visible = true;
  3984. this.castShadow = false;
  3985. this.receiveShadow = false;
  3986. this.frustumCulled = true;
  3987. this.userData = {};
  3988. };
  3989. THREE.Object3D.prototype = {
  3990. constructor: THREE.Object3D,
  3991. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  3992. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  3993. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  3994. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  3995. get eulerOrder () {
  3996. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  3997. return this.rotation.order;
  3998. },
  3999. set eulerOrder ( value ) {
  4000. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4001. this.rotation.order = value;
  4002. },
  4003. get useQuaternion () {
  4004. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4005. },
  4006. set useQuaternion ( value ) {
  4007. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4008. },
  4009. applyMatrix: function () {
  4010. var m1 = new THREE.Matrix4();
  4011. return function ( matrix ) {
  4012. this.matrix.multiplyMatrices( matrix, this.matrix );
  4013. this.position.getPositionFromMatrix( this.matrix );
  4014. this.scale.getScaleFromMatrix( this.matrix );
  4015. m1.extractRotation( this.matrix );
  4016. this.quaternion.setFromRotationMatrix( m1 );
  4017. }
  4018. }(),
  4019. rotateOnAxis: function() {
  4020. // rotate object on axis in object space
  4021. // axis is assumed to be normalized
  4022. var q1 = new THREE.Quaternion();
  4023. var q2 = new THREE.Quaternion();
  4024. return function ( axis, angle ) {
  4025. q1.setFromAxisAngle( axis, angle );
  4026. this.quaternion.multiply( q1 );
  4027. return this;
  4028. }
  4029. }(),
  4030. translateOnAxis: function () {
  4031. // translate object by distance along axis in object space
  4032. // axis is assumed to be normalized
  4033. var v1 = new THREE.Vector3();
  4034. return function ( axis, distance ) {
  4035. v1.copy( axis );
  4036. v1.applyQuaternion( this.quaternion );
  4037. this.position.add( v1.multiplyScalar( distance ) );
  4038. return this;
  4039. }
  4040. }(),
  4041. translate: function ( distance, axis ) {
  4042. console.warn( 'DEPRECATED: Object3D\'s .translate() has been removed. Use .translateOnAxis( axis, distance ) instead. Note args have been changed.' );
  4043. return this.translateOnAxis( axis, distance );
  4044. },
  4045. translateX: function () {
  4046. var v1 = new THREE.Vector3( 1, 0, 0 );
  4047. return function ( distance ) {
  4048. return this.translateOnAxis( v1, distance );
  4049. };
  4050. }(),
  4051. translateY: function () {
  4052. var v1 = new THREE.Vector3( 0, 1, 0 );
  4053. return function ( distance ) {
  4054. return this.translateOnAxis( v1, distance );
  4055. };
  4056. }(),
  4057. translateZ: function () {
  4058. var v1 = new THREE.Vector3( 0, 0, 1 );
  4059. return function ( distance ) {
  4060. return this.translateOnAxis( v1, distance );
  4061. };
  4062. }(),
  4063. localToWorld: function ( vector ) {
  4064. return vector.applyMatrix4( this.matrixWorld );
  4065. },
  4066. worldToLocal: function () {
  4067. var m1 = new THREE.Matrix4();
  4068. return function ( vector ) {
  4069. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  4070. };
  4071. }(),
  4072. lookAt: function () {
  4073. // This routine does not support objects with rotated and/or translated parent(s)
  4074. var m1 = new THREE.Matrix4();
  4075. return function ( vector ) {
  4076. m1.lookAt( vector, this.position, this.up );
  4077. this.quaternion.setFromRotationMatrix( m1 );
  4078. };
  4079. }(),
  4080. add: function ( object ) {
  4081. if ( object === this ) {
  4082. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  4083. return;
  4084. }
  4085. if ( object instanceof THREE.Object3D ) {
  4086. if ( object.parent !== undefined ) {
  4087. object.parent.remove( object );
  4088. }
  4089. object.parent = this;
  4090. this.children.push( object );
  4091. // add to scene
  4092. var scene = this;
  4093. while ( scene.parent !== undefined ) {
  4094. scene = scene.parent;
  4095. }
  4096. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4097. scene.__addObject( object );
  4098. }
  4099. }
  4100. },
  4101. remove: function ( object ) {
  4102. var index = this.children.indexOf( object );
  4103. if ( index !== - 1 ) {
  4104. object.parent = undefined;
  4105. this.children.splice( index, 1 );
  4106. // remove from scene
  4107. var scene = this;
  4108. while ( scene.parent !== undefined ) {
  4109. scene = scene.parent;
  4110. }
  4111. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4112. scene.__removeObject( object );
  4113. }
  4114. }
  4115. },
  4116. traverse: function ( callback ) {
  4117. callback( this );
  4118. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4119. this.children[ i ].traverse( callback );
  4120. }
  4121. },
  4122. getObjectById: function ( id, recursive ) {
  4123. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4124. var child = this.children[ i ];
  4125. if ( child.id === id ) {
  4126. return child;
  4127. }
  4128. if ( recursive === true ) {
  4129. child = child.getObjectById( id, recursive );
  4130. if ( child !== undefined ) {
  4131. return child;
  4132. }
  4133. }
  4134. }
  4135. return undefined;
  4136. },
  4137. getObjectByName: function ( name, recursive ) {
  4138. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4139. var child = this.children[ i ];
  4140. if ( child.name === name ) {
  4141. return child;
  4142. }
  4143. if ( recursive === true ) {
  4144. child = child.getObjectByName( name, recursive );
  4145. if ( child !== undefined ) {
  4146. return child;
  4147. }
  4148. }
  4149. }
  4150. return undefined;
  4151. },
  4152. getChildByName: function ( name, recursive ) {
  4153. console.warn( 'DEPRECATED: Object3D\'s .getChildByName() has been renamed to .getObjectByName().' );
  4154. return this.getObjectByName( name, recursive );
  4155. },
  4156. getDescendants: function ( array ) {
  4157. if ( array === undefined ) array = [];
  4158. Array.prototype.push.apply( array, this.children );
  4159. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4160. this.children[ i ].getDescendants( array );
  4161. }
  4162. return array;
  4163. },
  4164. updateMatrix: function () {
  4165. this.matrix.compose( this.position, this.quaternion, this.scale );
  4166. this.matrixWorldNeedsUpdate = true;
  4167. },
  4168. updateMatrixWorld: function ( force ) {
  4169. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  4170. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  4171. if ( this.parent === undefined ) {
  4172. this.matrixWorld.copy( this.matrix );
  4173. } else {
  4174. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4175. }
  4176. this.matrixWorldNeedsUpdate = false;
  4177. force = true;
  4178. }
  4179. // update children
  4180. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4181. this.children[ i ].updateMatrixWorld( force );
  4182. }
  4183. },
  4184. clone: function ( object, recursive ) {
  4185. if ( object === undefined ) object = new THREE.Object3D();
  4186. if ( recursive === undefined ) recursive = true;
  4187. object.name = this.name;
  4188. object.up.copy( this.up );
  4189. object.position.copy( this.position );
  4190. object.quaternion.copy( this.quaternion );
  4191. object.scale.copy( this.scale );
  4192. object.renderDepth = this.renderDepth;
  4193. object.rotationAutoUpdate = this.rotationAutoUpdate;
  4194. object.matrix.copy( this.matrix );
  4195. object.matrixWorld.copy( this.matrixWorld );
  4196. object.matrixAutoUpdate = this.matrixAutoUpdate;
  4197. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  4198. object.visible = this.visible;
  4199. object.castShadow = this.castShadow;
  4200. object.receiveShadow = this.receiveShadow;
  4201. object.frustumCulled = this.frustumCulled;
  4202. object.userData = JSON.parse( JSON.stringify( this.userData ) );
  4203. if ( recursive === true ) {
  4204. for ( var i = 0; i < this.children.length; i ++ ) {
  4205. var child = this.children[ i ];
  4206. object.add( child.clone() );
  4207. }
  4208. }
  4209. return object;
  4210. }
  4211. };
  4212. THREE.Object3D.defaultEulerOrder = 'XYZ';
  4213. /**
  4214. * @author mrdoob / http://mrdoob.com/
  4215. * @author supereggbert / http://www.paulbrunt.co.uk/
  4216. * @author julianwa / https://github.com/julianwa
  4217. */
  4218. THREE.Projector = function () {
  4219. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  4220. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  4221. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  4222. _face4Count, _face4Pool = [], _face4PoolLength = 0,
  4223. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  4224. _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
  4225. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  4226. _vector3 = new THREE.Vector3(),
  4227. _vector4 = new THREE.Vector4(),
  4228. _clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ),
  4229. _boundingBox = new THREE.Box3(),
  4230. _points3 = new Array( 3 ),
  4231. _points4 = new Array( 4 ),
  4232. _viewMatrix = new THREE.Matrix4(),
  4233. _viewProjectionMatrix = new THREE.Matrix4(),
  4234. _modelMatrix,
  4235. _modelViewProjectionMatrix = new THREE.Matrix4(),
  4236. _normalMatrix = new THREE.Matrix3(),
  4237. _normalViewMatrix = new THREE.Matrix3(),
  4238. _centroid = new THREE.Vector3(),
  4239. _frustum = new THREE.Frustum(),
  4240. _clippedVertex1PositionScreen = new THREE.Vector4(),
  4241. _clippedVertex2PositionScreen = new THREE.Vector4();
  4242. this.projectVector = function ( vector, camera ) {
  4243. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  4244. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  4245. return vector.applyProjection( _viewProjectionMatrix );
  4246. };
  4247. this.unprojectVector = function ( vector, camera ) {
  4248. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  4249. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, camera.projectionMatrixInverse );
  4250. return vector.applyProjection( _viewProjectionMatrix );
  4251. };
  4252. this.pickingRay = function ( vector, camera ) {
  4253. // set two vectors with opposing z values
  4254. vector.z = -1.0;
  4255. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  4256. this.unprojectVector( vector, camera );
  4257. this.unprojectVector( end, camera );
  4258. // find direction from vector to end
  4259. end.sub( vector ).normalize();
  4260. return new THREE.Raycaster( vector, end );
  4261. };
  4262. var getObject = function ( object ) {
  4263. _object = getNextObjectInPool();
  4264. _object.object = object;
  4265. if ( object.renderDepth !== null ) {
  4266. _object.z = object.renderDepth;
  4267. } else {
  4268. _vector3.getPositionFromMatrix( object.matrixWorld );
  4269. _vector3.applyProjection( _viewProjectionMatrix );
  4270. _object.z = _vector3.z;
  4271. }
  4272. return _object;
  4273. };
  4274. var projectObject = function ( object ) {
  4275. if ( object.visible === false ) return;
  4276. if ( object instanceof THREE.Light ) {
  4277. _renderData.lights.push( object );
  4278. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  4279. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  4280. _renderData.objects.push( getObject( object ) );
  4281. }
  4282. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  4283. _renderData.sprites.push( getObject( object ) );
  4284. }
  4285. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  4286. projectObject( object.children[ i ] );
  4287. }
  4288. };
  4289. var projectGraph = function ( root, sortObjects ) {
  4290. _objectCount = 0;
  4291. _renderData.objects.length = 0;
  4292. _renderData.sprites.length = 0;
  4293. _renderData.lights.length = 0;
  4294. projectObject( root );
  4295. if ( sortObjects === true ) {
  4296. _renderData.objects.sort( painterSort );
  4297. }
  4298. };
  4299. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  4300. var visible = false,
  4301. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  4302. geometry, vertices, faces, face, faceVertexNormals, faceVertexUvs, uvs,
  4303. v1, v2, v3, v4, isFaceMaterial, objectMaterials;
  4304. _face3Count = 0;
  4305. _face4Count = 0;
  4306. _lineCount = 0;
  4307. _particleCount = 0;
  4308. _renderData.elements.length = 0;
  4309. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  4310. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  4311. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  4312. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  4313. _normalViewMatrix.getNormalMatrix( _viewMatrix );
  4314. _frustum.setFromMatrix( _viewProjectionMatrix );
  4315. projectGraph( scene, sortObjects );
  4316. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  4317. object = _renderData.objects[ o ].object;
  4318. _modelMatrix = object.matrixWorld;
  4319. _vertexCount = 0;
  4320. if ( object instanceof THREE.Mesh ) {
  4321. geometry = object.geometry;
  4322. vertices = geometry.vertices;
  4323. faces = geometry.faces;
  4324. faceVertexUvs = geometry.faceVertexUvs;
  4325. _normalMatrix.getNormalMatrix( _modelMatrix );
  4326. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4327. objectMaterials = isFaceMaterial === true ? object.material : null;
  4328. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  4329. _vertex = getNextVertexInPool();
  4330. _vertex.positionWorld.copy( vertices[ v ] ).applyMatrix4( _modelMatrix );
  4331. _vertex.positionScreen.copy( _vertex.positionWorld ).applyMatrix4( _viewProjectionMatrix );
  4332. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  4333. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  4334. _vertex.positionScreen.z /= _vertex.positionScreen.w;
  4335. _vertex.visible = ! ( _vertex.positionScreen.x < -1 || _vertex.positionScreen.x > 1 ||
  4336. _vertex.positionScreen.y < -1 || _vertex.positionScreen.y > 1 ||
  4337. _vertex.positionScreen.z < -1 || _vertex.positionScreen.z > 1 );
  4338. }
  4339. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  4340. face = faces[ f ];
  4341. var material = isFaceMaterial === true
  4342. ? objectMaterials.materials[ face.materialIndex ]
  4343. : object.material;
  4344. if ( material === undefined ) continue;
  4345. var side = material.side;
  4346. if ( face instanceof THREE.Face3 ) {
  4347. v1 = _vertexPool[ face.a ];
  4348. v2 = _vertexPool[ face.b ];
  4349. v3 = _vertexPool[ face.c ];
  4350. _points3[ 0 ] = v1.positionScreen;
  4351. _points3[ 1 ] = v2.positionScreen;
  4352. _points3[ 2 ] = v3.positionScreen;
  4353. if ( v1.visible === true || v2.visible === true || v3.visible === true ||
  4354. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) ) ) {
  4355. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  4356. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  4357. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  4358. _face = getNextFace3InPool();
  4359. _face.v1.copy( v1 );
  4360. _face.v2.copy( v2 );
  4361. _face.v3.copy( v3 );
  4362. } else {
  4363. continue;
  4364. }
  4365. } else {
  4366. continue;
  4367. }
  4368. } else if ( face instanceof THREE.Face4 ) {
  4369. v1 = _vertexPool[ face.a ];
  4370. v2 = _vertexPool[ face.b ];
  4371. v3 = _vertexPool[ face.c ];
  4372. v4 = _vertexPool[ face.d ];
  4373. _points4[ 0 ] = v1.positionScreen;
  4374. _points4[ 1 ] = v2.positionScreen;
  4375. _points4[ 2 ] = v3.positionScreen;
  4376. _points4[ 3 ] = v4.positionScreen;
  4377. if ( v1.visible === true || v2.visible === true || v3.visible === true || v4.visible === true ||
  4378. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points4 ) ) ) {
  4379. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  4380. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  4381. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  4382. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  4383. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  4384. _face = getNextFace4InPool();
  4385. _face.v1.copy( v1 );
  4386. _face.v2.copy( v2 );
  4387. _face.v3.copy( v3 );
  4388. _face.v4.copy( v4 );
  4389. } else {
  4390. continue;
  4391. }
  4392. } else {
  4393. continue;
  4394. }
  4395. }
  4396. _face.normalModel.copy( face.normal );
  4397. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4398. _face.normalModel.negate();
  4399. }
  4400. _face.normalModel.applyMatrix3( _normalMatrix ).normalize();
  4401. _face.normalModelView.copy( _face.normalModel ).applyMatrix3( _normalViewMatrix );
  4402. _face.centroidModel.copy( face.centroid ).applyMatrix4( _modelMatrix );
  4403. faceVertexNormals = face.vertexNormals;
  4404. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  4405. var normalModel = _face.vertexNormalsModel[ n ];
  4406. normalModel.copy( faceVertexNormals[ n ] );
  4407. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4408. normalModel.negate();
  4409. }
  4410. normalModel.applyMatrix3( _normalMatrix ).normalize();
  4411. var normalModelView = _face.vertexNormalsModelView[ n ];
  4412. normalModelView.copy( normalModel ).applyMatrix3( _normalViewMatrix );
  4413. }
  4414. _face.vertexNormalsLength = faceVertexNormals.length;
  4415. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  4416. uvs = faceVertexUvs[ c ][ f ];
  4417. if ( uvs === undefined ) continue;
  4418. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  4419. _face.uvs[ c ][ u ] = uvs[ u ];
  4420. }
  4421. }
  4422. _face.color = face.color;
  4423. _face.material = material;
  4424. _centroid.copy( _face.centroidModel ).applyProjection( _viewProjectionMatrix );
  4425. _face.z = _centroid.z;
  4426. _renderData.elements.push( _face );
  4427. }
  4428. } else if ( object instanceof THREE.Line ) {
  4429. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  4430. vertices = object.geometry.vertices;
  4431. v1 = getNextVertexInPool();
  4432. v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
  4433. // Handle LineStrip and LinePieces
  4434. var step = object.type === THREE.LinePieces ? 2 : 1;
  4435. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  4436. v1 = getNextVertexInPool();
  4437. v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
  4438. if ( ( v + 1 ) % step > 0 ) continue;
  4439. v2 = _vertexPool[ _vertexCount - 2 ];
  4440. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  4441. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  4442. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  4443. // Perform the perspective divide
  4444. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  4445. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  4446. _line = getNextLineInPool();
  4447. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  4448. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  4449. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  4450. _line.material = object.material;
  4451. if ( object.material.vertexColors === THREE.VertexColors ) {
  4452. _line.vertexColors[ 0 ].copy( object.geometry.colors[ v ] );
  4453. _line.vertexColors[ 1 ].copy( object.geometry.colors[ v - 1 ] );
  4454. }
  4455. _renderData.elements.push( _line );
  4456. }
  4457. }
  4458. }
  4459. }
  4460. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  4461. object = _renderData.sprites[ o ].object;
  4462. _modelMatrix = object.matrixWorld;
  4463. if ( object instanceof THREE.Particle ) {
  4464. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  4465. _vector4.applyMatrix4( _viewProjectionMatrix );
  4466. _vector4.z /= _vector4.w;
  4467. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  4468. _particle = getNextParticleInPool();
  4469. _particle.object = object;
  4470. _particle.x = _vector4.x / _vector4.w;
  4471. _particle.y = _vector4.y / _vector4.w;
  4472. _particle.z = _vector4.z;
  4473. _particle.rotation = object.rotation.z;
  4474. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  4475. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  4476. _particle.material = object.material;
  4477. _renderData.elements.push( _particle );
  4478. }
  4479. }
  4480. }
  4481. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  4482. return _renderData;
  4483. };
  4484. // Pools
  4485. function getNextObjectInPool() {
  4486. if ( _objectCount === _objectPoolLength ) {
  4487. var object = new THREE.RenderableObject();
  4488. _objectPool.push( object );
  4489. _objectPoolLength ++;
  4490. _objectCount ++;
  4491. return object;
  4492. }
  4493. return _objectPool[ _objectCount ++ ];
  4494. }
  4495. function getNextVertexInPool() {
  4496. if ( _vertexCount === _vertexPoolLength ) {
  4497. var vertex = new THREE.RenderableVertex();
  4498. _vertexPool.push( vertex );
  4499. _vertexPoolLength ++;
  4500. _vertexCount ++;
  4501. return vertex;
  4502. }
  4503. return _vertexPool[ _vertexCount ++ ];
  4504. }
  4505. function getNextFace3InPool() {
  4506. if ( _face3Count === _face3PoolLength ) {
  4507. var face = new THREE.RenderableFace3();
  4508. _face3Pool.push( face );
  4509. _face3PoolLength ++;
  4510. _face3Count ++;
  4511. return face;
  4512. }
  4513. return _face3Pool[ _face3Count ++ ];
  4514. }
  4515. function getNextFace4InPool() {
  4516. if ( _face4Count === _face4PoolLength ) {
  4517. var face = new THREE.RenderableFace4();
  4518. _face4Pool.push( face );
  4519. _face4PoolLength ++;
  4520. _face4Count ++;
  4521. return face;
  4522. }
  4523. return _face4Pool[ _face4Count ++ ];
  4524. }
  4525. function getNextLineInPool() {
  4526. if ( _lineCount === _linePoolLength ) {
  4527. var line = new THREE.RenderableLine();
  4528. _linePool.push( line );
  4529. _linePoolLength ++;
  4530. _lineCount ++
  4531. return line;
  4532. }
  4533. return _linePool[ _lineCount ++ ];
  4534. }
  4535. function getNextParticleInPool() {
  4536. if ( _particleCount === _particlePoolLength ) {
  4537. var particle = new THREE.RenderableParticle();
  4538. _particlePool.push( particle );
  4539. _particlePoolLength ++;
  4540. _particleCount ++
  4541. return particle;
  4542. }
  4543. return _particlePool[ _particleCount ++ ];
  4544. }
  4545. //
  4546. function painterSort( a, b ) {
  4547. return b.z - a.z;
  4548. }
  4549. function clipLine( s1, s2 ) {
  4550. var alpha1 = 0, alpha2 = 1,
  4551. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  4552. // Z = -1 and Z = +1, respectively.
  4553. bc1near = s1.z + s1.w,
  4554. bc2near = s2.z + s2.w,
  4555. bc1far = - s1.z + s1.w,
  4556. bc2far = - s2.z + s2.w;
  4557. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  4558. // Both vertices lie entirely within all clip planes.
  4559. return true;
  4560. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  4561. // Both vertices lie entirely outside one of the clip planes.
  4562. return false;
  4563. } else {
  4564. // The line segment spans at least one clip plane.
  4565. if ( bc1near < 0 ) {
  4566. // v1 lies outside the near plane, v2 inside
  4567. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  4568. } else if ( bc2near < 0 ) {
  4569. // v2 lies outside the near plane, v1 inside
  4570. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  4571. }
  4572. if ( bc1far < 0 ) {
  4573. // v1 lies outside the far plane, v2 inside
  4574. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  4575. } else if ( bc2far < 0 ) {
  4576. // v2 lies outside the far plane, v2 inside
  4577. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  4578. }
  4579. if ( alpha2 < alpha1 ) {
  4580. // The line segment spans two boundaries, but is outside both of them.
  4581. // (This can't happen when we're only clipping against just near/far but good
  4582. // to leave the check here for future usage if other clip planes are added.)
  4583. return false;
  4584. } else {
  4585. // Update the s1 and s2 vertices to match the clipped line segment.
  4586. s1.lerp( s2, alpha1 );
  4587. s2.lerp( s1, 1 - alpha2 );
  4588. return true;
  4589. }
  4590. }
  4591. }
  4592. };
  4593. /**
  4594. * @author mrdoob / http://mrdoob.com/
  4595. * @author alteredq / http://alteredqualia.com/
  4596. */
  4597. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  4598. this.a = a;
  4599. this.b = b;
  4600. this.c = c;
  4601. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4602. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4603. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4604. this.vertexColors = color instanceof Array ? color : [];
  4605. this.vertexTangents = [];
  4606. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4607. this.centroid = new THREE.Vector3();
  4608. };
  4609. THREE.Face3.prototype = {
  4610. constructor: THREE.Face3,
  4611. clone: function () {
  4612. var face = new THREE.Face3( this.a, this.b, this.c );
  4613. face.normal.copy( this.normal );
  4614. face.color.copy( this.color );
  4615. face.centroid.copy( this.centroid );
  4616. face.materialIndex = this.materialIndex;
  4617. var i, il;
  4618. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4619. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4620. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4621. return face;
  4622. }
  4623. };
  4624. /**
  4625. * @author mrdoob / http://mrdoob.com/
  4626. * @author alteredq / http://alteredqualia.com/
  4627. */
  4628. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  4629. this.a = a;
  4630. this.b = b;
  4631. this.c = c;
  4632. this.d = d;
  4633. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4634. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4635. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4636. this.vertexColors = color instanceof Array ? color : [];
  4637. this.vertexTangents = [];
  4638. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4639. this.centroid = new THREE.Vector3();
  4640. };
  4641. THREE.Face4.prototype = {
  4642. constructor: THREE.Face4,
  4643. clone: function () {
  4644. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  4645. face.normal.copy( this.normal );
  4646. face.color.copy( this.color );
  4647. face.centroid.copy( this.centroid );
  4648. face.materialIndex = this.materialIndex;
  4649. var i, il;
  4650. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4651. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4652. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4653. return face;
  4654. }
  4655. };
  4656. /**
  4657. * @author mrdoob / http://mrdoob.com/
  4658. * @author kile / http://kile.stravaganza.org/
  4659. * @author alteredq / http://alteredqualia.com/
  4660. * @author mikael emtinger / http://gomo.se/
  4661. * @author zz85 / http://www.lab4games.net/zz85/blog
  4662. * @author bhouston / http://exocortex.com
  4663. */
  4664. THREE.Geometry = function () {
  4665. this.id = THREE.Math.generateUUID();
  4666. this.name = '';
  4667. this.vertices = [];
  4668. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  4669. this.normals = []; // one-to-one vertex normals, used in Ribbon
  4670. this.faces = [];
  4671. this.faceUvs = [[]];
  4672. this.faceVertexUvs = [[]];
  4673. this.morphTargets = [];
  4674. this.morphColors = [];
  4675. this.morphNormals = [];
  4676. this.skinWeights = [];
  4677. this.skinIndices = [];
  4678. this.lineDistances = [];
  4679. this.boundingBox = null;
  4680. this.boundingSphere = null;
  4681. this.hasTangents = false;
  4682. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  4683. // update flags
  4684. this.verticesNeedUpdate = false;
  4685. this.elementsNeedUpdate = false;
  4686. this.uvsNeedUpdate = false;
  4687. this.normalsNeedUpdate = false;
  4688. this.tangentsNeedUpdate = false;
  4689. this.colorsNeedUpdate = false;
  4690. this.lineDistancesNeedUpdate = false;
  4691. this.buffersNeedUpdate = false;
  4692. };
  4693. THREE.Geometry.prototype = {
  4694. constructor: THREE.Geometry,
  4695. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  4696. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  4697. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  4698. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  4699. applyMatrix: function ( matrix ) {
  4700. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  4701. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  4702. var vertex = this.vertices[ i ];
  4703. vertex.applyMatrix4( matrix );
  4704. }
  4705. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  4706. var face = this.faces[ i ];
  4707. face.normal.applyMatrix3( normalMatrix ).normalize();
  4708. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  4709. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  4710. }
  4711. face.centroid.applyMatrix4( matrix );
  4712. }
  4713. if ( this.boundingBox instanceof THREE.Box3 ) {
  4714. this.computeBoundingBox();
  4715. }
  4716. if ( this.boundingSphere instanceof THREE.Sphere ) {
  4717. this.computeBoundingSphere();
  4718. }
  4719. },
  4720. computeCentroids: function () {
  4721. var f, fl, face;
  4722. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4723. face = this.faces[ f ];
  4724. face.centroid.set( 0, 0, 0 );
  4725. if ( face instanceof THREE.Face3 ) {
  4726. face.centroid.add( this.vertices[ face.a ] );
  4727. face.centroid.add( this.vertices[ face.b ] );
  4728. face.centroid.add( this.vertices[ face.c ] );
  4729. face.centroid.divideScalar( 3 );
  4730. } else if ( face instanceof THREE.Face4 ) {
  4731. face.centroid.add( this.vertices[ face.a ] );
  4732. face.centroid.add( this.vertices[ face.b ] );
  4733. face.centroid.add( this.vertices[ face.c ] );
  4734. face.centroid.add( this.vertices[ face.d ] );
  4735. face.centroid.divideScalar( 4 );
  4736. }
  4737. }
  4738. },
  4739. computeFaceNormals: function () {
  4740. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  4741. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4742. var face = this.faces[ f ];
  4743. var vA = this.vertices[ face.a ];
  4744. var vB = this.vertices[ face.b ];
  4745. var vC = this.vertices[ face.c ];
  4746. cb.subVectors( vC, vB );
  4747. ab.subVectors( vA, vB );
  4748. cb.cross( ab );
  4749. cb.normalize();
  4750. face.normal.copy( cb );
  4751. }
  4752. },
  4753. computeVertexNormals: function ( areaWeighted ) {
  4754. var v, vl, f, fl, face, vertices;
  4755. // create internal buffers for reuse when calling this method repeatedly
  4756. // (otherwise memory allocation / deallocation every frame is big resource hog)
  4757. if ( this.__tmpVertices === undefined ) {
  4758. this.__tmpVertices = new Array( this.vertices.length );
  4759. vertices = this.__tmpVertices;
  4760. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4761. vertices[ v ] = new THREE.Vector3();
  4762. }
  4763. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4764. face = this.faces[ f ];
  4765. if ( face instanceof THREE.Face3 ) {
  4766. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4767. } else if ( face instanceof THREE.Face4 ) {
  4768. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4769. }
  4770. }
  4771. } else {
  4772. vertices = this.__tmpVertices;
  4773. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4774. vertices[ v ].set( 0, 0, 0 );
  4775. }
  4776. }
  4777. if ( areaWeighted ) {
  4778. // vertex normals weighted by triangle areas
  4779. // http://www.iquilezles.org/www/articles/normals/normals.htm
  4780. var vA, vB, vC, vD;
  4781. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  4782. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  4783. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4784. face = this.faces[ f ];
  4785. if ( face instanceof THREE.Face3 ) {
  4786. vA = this.vertices[ face.a ];
  4787. vB = this.vertices[ face.b ];
  4788. vC = this.vertices[ face.c ];
  4789. cb.subVectors( vC, vB );
  4790. ab.subVectors( vA, vB );
  4791. cb.cross( ab );
  4792. vertices[ face.a ].add( cb );
  4793. vertices[ face.b ].add( cb );
  4794. vertices[ face.c ].add( cb );
  4795. } else if ( face instanceof THREE.Face4 ) {
  4796. vA = this.vertices[ face.a ];
  4797. vB = this.vertices[ face.b ];
  4798. vC = this.vertices[ face.c ];
  4799. vD = this.vertices[ face.d ];
  4800. // abd
  4801. db.subVectors( vD, vB );
  4802. ab.subVectors( vA, vB );
  4803. db.cross( ab );
  4804. vertices[ face.a ].add( db );
  4805. vertices[ face.b ].add( db );
  4806. vertices[ face.d ].add( db );
  4807. // bcd
  4808. dc.subVectors( vD, vC );
  4809. bc.subVectors( vB, vC );
  4810. dc.cross( bc );
  4811. vertices[ face.b ].add( dc );
  4812. vertices[ face.c ].add( dc );
  4813. vertices[ face.d ].add( dc );
  4814. }
  4815. }
  4816. } else {
  4817. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4818. face = this.faces[ f ];
  4819. if ( face instanceof THREE.Face3 ) {
  4820. vertices[ face.a ].add( face.normal );
  4821. vertices[ face.b ].add( face.normal );
  4822. vertices[ face.c ].add( face.normal );
  4823. } else if ( face instanceof THREE.Face4 ) {
  4824. vertices[ face.a ].add( face.normal );
  4825. vertices[ face.b ].add( face.normal );
  4826. vertices[ face.c ].add( face.normal );
  4827. vertices[ face.d ].add( face.normal );
  4828. }
  4829. }
  4830. }
  4831. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4832. vertices[ v ].normalize();
  4833. }
  4834. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4835. face = this.faces[ f ];
  4836. if ( face instanceof THREE.Face3 ) {
  4837. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4838. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4839. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4840. } else if ( face instanceof THREE.Face4 ) {
  4841. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4842. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4843. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4844. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  4845. }
  4846. }
  4847. },
  4848. computeMorphNormals: function () {
  4849. var i, il, f, fl, face;
  4850. // save original normals
  4851. // - create temp variables on first access
  4852. // otherwise just copy (for faster repeated calls)
  4853. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4854. face = this.faces[ f ];
  4855. if ( ! face.__originalFaceNormal ) {
  4856. face.__originalFaceNormal = face.normal.clone();
  4857. } else {
  4858. face.__originalFaceNormal.copy( face.normal );
  4859. }
  4860. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  4861. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  4862. if ( ! face.__originalVertexNormals[ i ] ) {
  4863. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  4864. } else {
  4865. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  4866. }
  4867. }
  4868. }
  4869. // use temp geometry to compute face and vertex normals for each morph
  4870. var tmpGeo = new THREE.Geometry();
  4871. tmpGeo.faces = this.faces;
  4872. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  4873. // create on first access
  4874. if ( ! this.morphNormals[ i ] ) {
  4875. this.morphNormals[ i ] = {};
  4876. this.morphNormals[ i ].faceNormals = [];
  4877. this.morphNormals[ i ].vertexNormals = [];
  4878. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  4879. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  4880. var faceNormal, vertexNormals;
  4881. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4882. face = this.faces[ f ];
  4883. faceNormal = new THREE.Vector3();
  4884. if ( face instanceof THREE.Face3 ) {
  4885. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  4886. } else {
  4887. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  4888. }
  4889. dstNormalsFace.push( faceNormal );
  4890. dstNormalsVertex.push( vertexNormals );
  4891. }
  4892. }
  4893. var morphNormals = this.morphNormals[ i ];
  4894. // set vertices to morph target
  4895. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  4896. // compute morph normals
  4897. tmpGeo.computeFaceNormals();
  4898. tmpGeo.computeVertexNormals();
  4899. // store morph normals
  4900. var faceNormal, vertexNormals;
  4901. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4902. face = this.faces[ f ];
  4903. faceNormal = morphNormals.faceNormals[ f ];
  4904. vertexNormals = morphNormals.vertexNormals[ f ];
  4905. faceNormal.copy( face.normal );
  4906. if ( face instanceof THREE.Face3 ) {
  4907. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4908. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4909. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4910. } else {
  4911. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4912. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4913. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4914. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  4915. }
  4916. }
  4917. }
  4918. // restore original normals
  4919. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4920. face = this.faces[ f ];
  4921. face.normal = face.__originalFaceNormal;
  4922. face.vertexNormals = face.__originalVertexNormals;
  4923. }
  4924. },
  4925. computeTangents: function () {
  4926. // based on http://www.terathon.com/code/tangent.html
  4927. // tangents go to vertices
  4928. var f, fl, v, vl, i, il, vertexIndex,
  4929. face, uv, vA, vB, vC, uvA, uvB, uvC,
  4930. x1, x2, y1, y2, z1, z2,
  4931. s1, s2, t1, t2, r, t, test,
  4932. tan1 = [], tan2 = [],
  4933. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  4934. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  4935. n = new THREE.Vector3(), w;
  4936. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4937. tan1[ v ] = new THREE.Vector3();
  4938. tan2[ v ] = new THREE.Vector3();
  4939. }
  4940. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  4941. vA = context.vertices[ a ];
  4942. vB = context.vertices[ b ];
  4943. vC = context.vertices[ c ];
  4944. uvA = uv[ ua ];
  4945. uvB = uv[ ub ];
  4946. uvC = uv[ uc ];
  4947. x1 = vB.x - vA.x;
  4948. x2 = vC.x - vA.x;
  4949. y1 = vB.y - vA.y;
  4950. y2 = vC.y - vA.y;
  4951. z1 = vB.z - vA.z;
  4952. z2 = vC.z - vA.z;
  4953. s1 = uvB.x - uvA.x;
  4954. s2 = uvC.x - uvA.x;
  4955. t1 = uvB.y - uvA.y;
  4956. t2 = uvC.y - uvA.y;
  4957. r = 1.0 / ( s1 * t2 - s2 * t1 );
  4958. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  4959. ( t2 * y1 - t1 * y2 ) * r,
  4960. ( t2 * z1 - t1 * z2 ) * r );
  4961. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  4962. ( s1 * y2 - s2 * y1 ) * r,
  4963. ( s1 * z2 - s2 * z1 ) * r );
  4964. tan1[ a ].add( sdir );
  4965. tan1[ b ].add( sdir );
  4966. tan1[ c ].add( sdir );
  4967. tan2[ a ].add( tdir );
  4968. tan2[ b ].add( tdir );
  4969. tan2[ c ].add( tdir );
  4970. }
  4971. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4972. face = this.faces[ f ];
  4973. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  4974. if ( face instanceof THREE.Face3 ) {
  4975. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  4976. } else if ( face instanceof THREE.Face4 ) {
  4977. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  4978. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  4979. }
  4980. }
  4981. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  4982. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4983. face = this.faces[ f ];
  4984. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  4985. n.copy( face.vertexNormals[ i ] );
  4986. vertexIndex = face[ faceIndex[ i ] ];
  4987. t = tan1[ vertexIndex ];
  4988. // Gram-Schmidt orthogonalize
  4989. tmp.copy( t );
  4990. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  4991. // Calculate handedness
  4992. tmp2.crossVectors( face.vertexNormals[ i ], t );
  4993. test = tmp2.dot( tan2[ vertexIndex ] );
  4994. w = (test < 0.0) ? -1.0 : 1.0;
  4995. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  4996. }
  4997. }
  4998. this.hasTangents = true;
  4999. },
  5000. computeLineDistances: function ( ) {
  5001. var d = 0;
  5002. var vertices = this.vertices;
  5003. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5004. if ( i > 0 ) {
  5005. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  5006. }
  5007. this.lineDistances[ i ] = d;
  5008. }
  5009. },
  5010. computeBoundingBox: function () {
  5011. if ( this.boundingBox === null ) {
  5012. this.boundingBox = new THREE.Box3();
  5013. }
  5014. this.boundingBox.setFromPoints( this.vertices );
  5015. },
  5016. computeBoundingSphere: function () {
  5017. if ( this.boundingSphere === null ) {
  5018. this.boundingSphere = new THREE.Sphere();
  5019. }
  5020. this.boundingSphere.setFromPoints( this.vertices );
  5021. },
  5022. /*
  5023. * Checks for duplicate vertices with hashmap.
  5024. * Duplicated vertices are removed
  5025. * and faces' vertices are updated.
  5026. */
  5027. mergeVertices: function () {
  5028. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  5029. var unique = [], changes = [];
  5030. var v, key;
  5031. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  5032. var precision = Math.pow( 10, precisionPoints );
  5033. var i,il, face;
  5034. var indices, k, j, jl, u;
  5035. // reset cache of vertices as it now will be changing.
  5036. this.__tmpVertices = undefined;
  5037. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  5038. v = this.vertices[ i ];
  5039. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  5040. if ( verticesMap[ key ] === undefined ) {
  5041. verticesMap[ key ] = i;
  5042. unique.push( this.vertices[ i ] );
  5043. changes[ i ] = unique.length - 1;
  5044. } else {
  5045. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  5046. changes[ i ] = changes[ verticesMap[ key ] ];
  5047. }
  5048. };
  5049. // if faces are completely degenerate after merging vertices, we
  5050. // have to remove them from the geometry.
  5051. var faceIndicesToRemove = [];
  5052. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  5053. face = this.faces[ i ];
  5054. if ( face instanceof THREE.Face3 ) {
  5055. face.a = changes[ face.a ];
  5056. face.b = changes[ face.b ];
  5057. face.c = changes[ face.c ];
  5058. indices = [ face.a, face.b, face.c ];
  5059. var dupIndex = -1;
  5060. // if any duplicate vertices are found in a Face3
  5061. // we have to remove the face as nothing can be saved
  5062. for ( var n = 0; n < 3; n ++ ) {
  5063. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  5064. dupIndex = n;
  5065. faceIndicesToRemove.push( i );
  5066. break;
  5067. }
  5068. }
  5069. } else if ( face instanceof THREE.Face4 ) {
  5070. face.a = changes[ face.a ];
  5071. face.b = changes[ face.b ];
  5072. face.c = changes[ face.c ];
  5073. face.d = changes[ face.d ];
  5074. // check dups in (a, b, c, d) and convert to -> face3
  5075. indices = [ face.a, face.b, face.c, face.d ];
  5076. var dupIndex = -1;
  5077. for ( var n = 0; n < 4; n ++ ) {
  5078. if ( indices[ n ] == indices[ ( n + 1 ) % 4 ] ) {
  5079. // if more than one duplicated vertex is found
  5080. // we can't generate any valid Face3's, thus
  5081. // we need to remove this face complete.
  5082. if ( dupIndex >= 0 ) {
  5083. faceIndicesToRemove.push( i );
  5084. }
  5085. dupIndex = n;
  5086. }
  5087. }
  5088. if ( dupIndex >= 0 ) {
  5089. indices.splice( dupIndex, 1 );
  5090. var newFace = new THREE.Face3( indices[0], indices[1], indices[2], face.normal, face.color, face.materialIndex );
  5091. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  5092. u = this.faceVertexUvs[ j ][ i ];
  5093. if ( u ) {
  5094. u.splice( dupIndex, 1 );
  5095. }
  5096. }
  5097. if( face.vertexNormals && face.vertexNormals.length > 0) {
  5098. newFace.vertexNormals = face.vertexNormals;
  5099. newFace.vertexNormals.splice( dupIndex, 1 );
  5100. }
  5101. if( face.vertexColors && face.vertexColors.length > 0 ) {
  5102. newFace.vertexColors = face.vertexColors;
  5103. newFace.vertexColors.splice( dupIndex, 1 );
  5104. }
  5105. this.faces[ i ] = newFace;
  5106. }
  5107. }
  5108. }
  5109. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  5110. this.faces.splice( i, 1 );
  5111. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  5112. this.faceVertexUvs[ j ].splice( i, 1 );
  5113. }
  5114. }
  5115. // Use unique set of vertices
  5116. var diff = this.vertices.length - unique.length;
  5117. this.vertices = unique;
  5118. return diff;
  5119. },
  5120. clone: function () {
  5121. var geometry = new THREE.Geometry();
  5122. var vertices = this.vertices;
  5123. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5124. geometry.vertices.push( vertices[ i ].clone() );
  5125. }
  5126. var faces = this.faces;
  5127. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  5128. geometry.faces.push( faces[ i ].clone() );
  5129. }
  5130. var uvs = this.faceVertexUvs[ 0 ];
  5131. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  5132. var uv = uvs[ i ], uvCopy = [];
  5133. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  5134. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  5135. }
  5136. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  5137. }
  5138. return geometry;
  5139. },
  5140. dispose: function () {
  5141. this.dispatchEvent( { type: 'dispose' } );
  5142. }
  5143. };
  5144. /**
  5145. * @author alteredq / http://alteredqualia.com/
  5146. */
  5147. THREE.BufferGeometry = function () {
  5148. this.id = THREE.Math.generateUUID();
  5149. // attributes
  5150. this.attributes = {};
  5151. // attributes typed arrays are kept only if dynamic flag is set
  5152. this.dynamic = false;
  5153. // offsets for chunks when using indexed elements
  5154. this.offsets = [];
  5155. // boundings
  5156. this.boundingBox = null;
  5157. this.boundingSphere = null;
  5158. this.hasTangents = false;
  5159. // for compatibility
  5160. this.morphTargets = [];
  5161. };
  5162. THREE.BufferGeometry.prototype = {
  5163. constructor: THREE.BufferGeometry,
  5164. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  5165. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  5166. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  5167. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  5168. applyMatrix: function ( matrix ) {
  5169. var positionArray;
  5170. var normalArray;
  5171. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  5172. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  5173. if ( positionArray !== undefined ) {
  5174. matrix.multiplyVector3Array( positionArray );
  5175. this.verticesNeedUpdate = true;
  5176. }
  5177. if ( normalArray !== undefined ) {
  5178. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5179. normalMatrix.multiplyVector3Array( normalArray );
  5180. this.normalizeNormals();
  5181. this.normalsNeedUpdate = true;
  5182. }
  5183. },
  5184. computeBoundingBox: function () {
  5185. if ( this.boundingBox === null ) {
  5186. this.boundingBox = new THREE.Box3();
  5187. }
  5188. var positions = this.attributes[ "position" ].array;
  5189. if ( positions ) {
  5190. var bb = this.boundingBox;
  5191. var x, y, z;
  5192. if( positions.length >= 3 ) {
  5193. bb.min.x = bb.max.x = positions[ 0 ];
  5194. bb.min.y = bb.max.y = positions[ 1 ];
  5195. bb.min.z = bb.max.z = positions[ 2 ];
  5196. }
  5197. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  5198. x = positions[ i ];
  5199. y = positions[ i + 1 ];
  5200. z = positions[ i + 2 ];
  5201. // bounding box
  5202. if ( x < bb.min.x ) {
  5203. bb.min.x = x;
  5204. } else if ( x > bb.max.x ) {
  5205. bb.max.x = x;
  5206. }
  5207. if ( y < bb.min.y ) {
  5208. bb.min.y = y;
  5209. } else if ( y > bb.max.y ) {
  5210. bb.max.y = y;
  5211. }
  5212. if ( z < bb.min.z ) {
  5213. bb.min.z = z;
  5214. } else if ( z > bb.max.z ) {
  5215. bb.max.z = z;
  5216. }
  5217. }
  5218. }
  5219. if ( positions === undefined || positions.length === 0 ) {
  5220. this.boundingBox.min.set( 0, 0, 0 );
  5221. this.boundingBox.max.set( 0, 0, 0 );
  5222. }
  5223. },
  5224. computeBoundingSphere: function () {
  5225. if ( this.boundingSphere === null ) {
  5226. this.boundingSphere = new THREE.Sphere();
  5227. }
  5228. var positions = this.attributes[ "position" ].array;
  5229. if ( positions ) {
  5230. var radiusSq, maxRadiusSq = 0;
  5231. var x, y, z;
  5232. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5233. x = positions[ i ];
  5234. y = positions[ i + 1 ];
  5235. z = positions[ i + 2 ];
  5236. radiusSq = x * x + y * y + z * z;
  5237. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  5238. }
  5239. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5240. }
  5241. },
  5242. computeVertexNormals: function () {
  5243. if ( this.attributes[ "position" ] ) {
  5244. var i, il;
  5245. var j, jl;
  5246. var nVertexElements = this.attributes[ "position" ].array.length;
  5247. if ( this.attributes[ "normal" ] === undefined ) {
  5248. this.attributes[ "normal" ] = {
  5249. itemSize: 3,
  5250. array: new Float32Array( nVertexElements )
  5251. };
  5252. } else {
  5253. // reset existing normals to zero
  5254. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  5255. this.attributes[ "normal" ].array[ i ] = 0;
  5256. }
  5257. }
  5258. var positions = this.attributes[ "position" ].array;
  5259. var normals = this.attributes[ "normal" ].array;
  5260. var vA, vB, vC, x, y, z,
  5261. pA = new THREE.Vector3(),
  5262. pB = new THREE.Vector3(),
  5263. pC = new THREE.Vector3(),
  5264. cb = new THREE.Vector3(),
  5265. ab = new THREE.Vector3();
  5266. // indexed elements
  5267. if ( this.attributes[ "index" ] ) {
  5268. var indices = this.attributes[ "index" ].array;
  5269. var offsets = this.offsets;
  5270. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5271. var start = offsets[ j ].start;
  5272. var count = offsets[ j ].count;
  5273. var index = offsets[ j ].index;
  5274. for ( i = start, il = start + count; i < il; i += 3 ) {
  5275. vA = index + indices[ i ];
  5276. vB = index + indices[ i + 1 ];
  5277. vC = index + indices[ i + 2 ];
  5278. x = positions[ vA * 3 ];
  5279. y = positions[ vA * 3 + 1 ];
  5280. z = positions[ vA * 3 + 2 ];
  5281. pA.set( x, y, z );
  5282. x = positions[ vB * 3 ];
  5283. y = positions[ vB * 3 + 1 ];
  5284. z = positions[ vB * 3 + 2 ];
  5285. pB.set( x, y, z );
  5286. x = positions[ vC * 3 ];
  5287. y = positions[ vC * 3 + 1 ];
  5288. z = positions[ vC * 3 + 2 ];
  5289. pC.set( x, y, z );
  5290. cb.subVectors( pC, pB );
  5291. ab.subVectors( pA, pB );
  5292. cb.cross( ab );
  5293. normals[ vA * 3 ] += cb.x;
  5294. normals[ vA * 3 + 1 ] += cb.y;
  5295. normals[ vA * 3 + 2 ] += cb.z;
  5296. normals[ vB * 3 ] += cb.x;
  5297. normals[ vB * 3 + 1 ] += cb.y;
  5298. normals[ vB * 3 + 2 ] += cb.z;
  5299. normals[ vC * 3 ] += cb.x;
  5300. normals[ vC * 3 + 1 ] += cb.y;
  5301. normals[ vC * 3 + 2 ] += cb.z;
  5302. }
  5303. }
  5304. // non-indexed elements (unconnected triangle soup)
  5305. } else {
  5306. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  5307. x = positions[ i ];
  5308. y = positions[ i + 1 ];
  5309. z = positions[ i + 2 ];
  5310. pA.set( x, y, z );
  5311. x = positions[ i + 3 ];
  5312. y = positions[ i + 4 ];
  5313. z = positions[ i + 5 ];
  5314. pB.set( x, y, z );
  5315. x = positions[ i + 6 ];
  5316. y = positions[ i + 7 ];
  5317. z = positions[ i + 8 ];
  5318. pC.set( x, y, z );
  5319. cb.subVectors( pC, pB );
  5320. ab.subVectors( pA, pB );
  5321. cb.cross( ab );
  5322. normals[ i ] = cb.x;
  5323. normals[ i + 1 ] = cb.y;
  5324. normals[ i + 2 ] = cb.z;
  5325. normals[ i + 3 ] = cb.x;
  5326. normals[ i + 4 ] = cb.y;
  5327. normals[ i + 5 ] = cb.z;
  5328. normals[ i + 6 ] = cb.x;
  5329. normals[ i + 7 ] = cb.y;
  5330. normals[ i + 8 ] = cb.z;
  5331. }
  5332. }
  5333. this.normalizeNormals();
  5334. this.normalsNeedUpdate = true;
  5335. }
  5336. },
  5337. normalizeNormals: function () {
  5338. var normals = this.attributes[ "normal" ].array;
  5339. var x, y, z, n;
  5340. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5341. x = normals[ i ];
  5342. y = normals[ i + 1 ];
  5343. z = normals[ i + 2 ];
  5344. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5345. normals[ i ] *= n;
  5346. normals[ i + 1 ] *= n;
  5347. normals[ i + 2 ] *= n;
  5348. }
  5349. },
  5350. computeTangents: function () {
  5351. // based on http://www.terathon.com/code/tangent.html
  5352. // (per vertex tangents)
  5353. if ( this.attributes[ "index" ] === undefined ||
  5354. this.attributes[ "position" ] === undefined ||
  5355. this.attributes[ "normal" ] === undefined ||
  5356. this.attributes[ "uv" ] === undefined ) {
  5357. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  5358. return;
  5359. }
  5360. var indices = this.attributes[ "index" ].array;
  5361. var positions = this.attributes[ "position" ].array;
  5362. var normals = this.attributes[ "normal" ].array;
  5363. var uvs = this.attributes[ "uv" ].array;
  5364. var nVertices = positions.length / 3;
  5365. if ( this.attributes[ "tangent" ] === undefined ) {
  5366. var nTangentElements = 4 * nVertices;
  5367. this.attributes[ "tangent" ] = {
  5368. itemSize: 4,
  5369. array: new Float32Array( nTangentElements )
  5370. };
  5371. }
  5372. var tangents = this.attributes[ "tangent" ].array;
  5373. var tan1 = [], tan2 = [];
  5374. for ( var k = 0; k < nVertices; k ++ ) {
  5375. tan1[ k ] = new THREE.Vector3();
  5376. tan2[ k ] = new THREE.Vector3();
  5377. }
  5378. var xA, yA, zA,
  5379. xB, yB, zB,
  5380. xC, yC, zC,
  5381. uA, vA,
  5382. uB, vB,
  5383. uC, vC,
  5384. x1, x2, y1, y2, z1, z2,
  5385. s1, s2, t1, t2, r;
  5386. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5387. function handleTriangle( a, b, c ) {
  5388. xA = positions[ a * 3 ];
  5389. yA = positions[ a * 3 + 1 ];
  5390. zA = positions[ a * 3 + 2 ];
  5391. xB = positions[ b * 3 ];
  5392. yB = positions[ b * 3 + 1 ];
  5393. zB = positions[ b * 3 + 2 ];
  5394. xC = positions[ c * 3 ];
  5395. yC = positions[ c * 3 + 1 ];
  5396. zC = positions[ c * 3 + 2 ];
  5397. uA = uvs[ a * 2 ];
  5398. vA = uvs[ a * 2 + 1 ];
  5399. uB = uvs[ b * 2 ];
  5400. vB = uvs[ b * 2 + 1 ];
  5401. uC = uvs[ c * 2 ];
  5402. vC = uvs[ c * 2 + 1 ];
  5403. x1 = xB - xA;
  5404. x2 = xC - xA;
  5405. y1 = yB - yA;
  5406. y2 = yC - yA;
  5407. z1 = zB - zA;
  5408. z2 = zC - zA;
  5409. s1 = uB - uA;
  5410. s2 = uC - uA;
  5411. t1 = vB - vA;
  5412. t2 = vC - vA;
  5413. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5414. sdir.set(
  5415. ( t2 * x1 - t1 * x2 ) * r,
  5416. ( t2 * y1 - t1 * y2 ) * r,
  5417. ( t2 * z1 - t1 * z2 ) * r
  5418. );
  5419. tdir.set(
  5420. ( s1 * x2 - s2 * x1 ) * r,
  5421. ( s1 * y2 - s2 * y1 ) * r,
  5422. ( s1 * z2 - s2 * z1 ) * r
  5423. );
  5424. tan1[ a ].add( sdir );
  5425. tan1[ b ].add( sdir );
  5426. tan1[ c ].add( sdir );
  5427. tan2[ a ].add( tdir );
  5428. tan2[ b ].add( tdir );
  5429. tan2[ c ].add( tdir );
  5430. }
  5431. var i, il;
  5432. var j, jl;
  5433. var iA, iB, iC;
  5434. var offsets = this.offsets;
  5435. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5436. var start = offsets[ j ].start;
  5437. var count = offsets[ j ].count;
  5438. var index = offsets[ j ].index;
  5439. for ( i = start, il = start + count; i < il; i += 3 ) {
  5440. iA = index + indices[ i ];
  5441. iB = index + indices[ i + 1 ];
  5442. iC = index + indices[ i + 2 ];
  5443. handleTriangle( iA, iB, iC );
  5444. }
  5445. }
  5446. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5447. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5448. var w, t, test;
  5449. function handleVertex( v ) {
  5450. n.x = normals[ v * 3 ];
  5451. n.y = normals[ v * 3 + 1 ];
  5452. n.z = normals[ v * 3 + 2 ];
  5453. n2.copy( n );
  5454. t = tan1[ v ];
  5455. // Gram-Schmidt orthogonalize
  5456. tmp.copy( t );
  5457. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5458. // Calculate handedness
  5459. tmp2.crossVectors( n2, t );
  5460. test = tmp2.dot( tan2[ v ] );
  5461. w = ( test < 0.0 ) ? -1.0 : 1.0;
  5462. tangents[ v * 4 ] = tmp.x;
  5463. tangents[ v * 4 + 1 ] = tmp.y;
  5464. tangents[ v * 4 + 2 ] = tmp.z;
  5465. tangents[ v * 4 + 3 ] = w;
  5466. }
  5467. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5468. var start = offsets[ j ].start;
  5469. var count = offsets[ j ].count;
  5470. var index = offsets[ j ].index;
  5471. for ( i = start, il = start + count; i < il; i += 3 ) {
  5472. iA = index + indices[ i ];
  5473. iB = index + indices[ i + 1 ];
  5474. iC = index + indices[ i + 2 ];
  5475. handleVertex( iA );
  5476. handleVertex( iB );
  5477. handleVertex( iC );
  5478. }
  5479. }
  5480. this.hasTangents = true;
  5481. this.tangentsNeedUpdate = true;
  5482. },
  5483. dispose: function () {
  5484. this.dispatchEvent( { type: 'dispose' } );
  5485. }
  5486. };
  5487. /**
  5488. * @author mrdoob / http://mrdoob.com/
  5489. * @author mikael emtinger / http://gomo.se/
  5490. * @author WestLangley / http://github.com/WestLangley
  5491. */
  5492. THREE.Camera = function () {
  5493. THREE.Object3D.call( this );
  5494. this.matrixWorldInverse = new THREE.Matrix4();
  5495. this.projectionMatrix = new THREE.Matrix4();
  5496. this.projectionMatrixInverse = new THREE.Matrix4();
  5497. };
  5498. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  5499. THREE.Camera.prototype.lookAt = function () {
  5500. // This routine does not support cameras with rotated and/or translated parent(s)
  5501. var m1 = new THREE.Matrix4();
  5502. return function ( vector ) {
  5503. m1.lookAt( this.position, vector, this.up );
  5504. this.quaternion.setFromRotationMatrix( m1 );
  5505. };
  5506. }();
  5507. /**
  5508. * @author alteredq / http://alteredqualia.com/
  5509. */
  5510. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  5511. THREE.Camera.call( this );
  5512. this.left = left;
  5513. this.right = right;
  5514. this.top = top;
  5515. this.bottom = bottom;
  5516. this.near = ( near !== undefined ) ? near : 0.1;
  5517. this.far = ( far !== undefined ) ? far : 2000;
  5518. this.updateProjectionMatrix();
  5519. };
  5520. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  5521. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  5522. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  5523. };
  5524. /**
  5525. * @author mrdoob / http://mrdoob.com/
  5526. * @author greggman / http://games.greggman.com/
  5527. * @author zz85 / http://www.lab4games.net/zz85/blog
  5528. */
  5529. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  5530. THREE.Camera.call( this );
  5531. this.fov = fov !== undefined ? fov : 50;
  5532. this.aspect = aspect !== undefined ? aspect : 1;
  5533. this.near = near !== undefined ? near : 0.1;
  5534. this.far = far !== undefined ? far : 2000;
  5535. this.updateProjectionMatrix();
  5536. };
  5537. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  5538. /**
  5539. * Uses Focal Length (in mm) to estimate and set FOV
  5540. * 35mm (fullframe) camera is used if frame size is not specified;
  5541. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  5542. */
  5543. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  5544. if ( frameHeight === undefined ) frameHeight = 24;
  5545. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  5546. this.updateProjectionMatrix();
  5547. }
  5548. /**
  5549. * Sets an offset in a larger frustum. This is useful for multi-window or
  5550. * multi-monitor/multi-machine setups.
  5551. *
  5552. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  5553. * the monitors are in grid like this
  5554. *
  5555. * +---+---+---+
  5556. * | A | B | C |
  5557. * +---+---+---+
  5558. * | D | E | F |
  5559. * +---+---+---+
  5560. *
  5561. * then for each monitor you would call it like this
  5562. *
  5563. * var w = 1920;
  5564. * var h = 1080;
  5565. * var fullWidth = w * 3;
  5566. * var fullHeight = h * 2;
  5567. *
  5568. * --A--
  5569. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  5570. * --B--
  5571. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  5572. * --C--
  5573. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  5574. * --D--
  5575. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  5576. * --E--
  5577. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  5578. * --F--
  5579. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  5580. *
  5581. * Note there is no reason monitors have to be the same size or in a grid.
  5582. */
  5583. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  5584. this.fullWidth = fullWidth;
  5585. this.fullHeight = fullHeight;
  5586. this.x = x;
  5587. this.y = y;
  5588. this.width = width;
  5589. this.height = height;
  5590. this.updateProjectionMatrix();
  5591. };
  5592. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  5593. if ( this.fullWidth ) {
  5594. var aspect = this.fullWidth / this.fullHeight;
  5595. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  5596. var bottom = -top;
  5597. var left = aspect * bottom;
  5598. var right = aspect * top;
  5599. var width = Math.abs( right - left );
  5600. var height = Math.abs( top - bottom );
  5601. this.projectionMatrix.makeFrustum(
  5602. left + this.x * width / this.fullWidth,
  5603. left + ( this.x + this.width ) * width / this.fullWidth,
  5604. top - ( this.y + this.height ) * height / this.fullHeight,
  5605. top - this.y * height / this.fullHeight,
  5606. this.near,
  5607. this.far
  5608. );
  5609. } else {
  5610. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  5611. }
  5612. };
  5613. /**
  5614. * @author mrdoob / http://mrdoob.com/
  5615. * @author alteredq / http://alteredqualia.com/
  5616. */
  5617. THREE.Light = function ( hex ) {
  5618. THREE.Object3D.call( this );
  5619. this.color = new THREE.Color( hex );
  5620. };
  5621. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  5622. THREE.Light.prototype.clone = function ( light ) {
  5623. if ( light === undefined ) light = new THREE.Light();
  5624. THREE.Object3D.prototype.clone.call( this, light );
  5625. light.color.copy( this.color );
  5626. return light;
  5627. };
  5628. /**
  5629. * @author mrdoob / http://mrdoob.com/
  5630. */
  5631. THREE.AmbientLight = function ( hex ) {
  5632. THREE.Light.call( this, hex );
  5633. };
  5634. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  5635. THREE.AmbientLight.prototype.clone = function () {
  5636. var light = new THREE.AmbientLight();
  5637. THREE.Light.prototype.clone.call( this, light );
  5638. return light;
  5639. };
  5640. /**
  5641. * @author MPanknin / http://www.redplant.de/
  5642. * @author alteredq / http://alteredqualia.com/
  5643. */
  5644. THREE.AreaLight = function ( hex, intensity ) {
  5645. THREE.Light.call( this, hex );
  5646. this.normal = new THREE.Vector3( 0, -1, 0 );
  5647. this.right = new THREE.Vector3( 1, 0, 0 );
  5648. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5649. this.width = 1.0;
  5650. this.height = 1.0;
  5651. this.constantAttenuation = 1.5;
  5652. this.linearAttenuation = 0.5;
  5653. this.quadraticAttenuation = 0.1;
  5654. };
  5655. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  5656. /**
  5657. * @author mrdoob / http://mrdoob.com/
  5658. * @author alteredq / http://alteredqualia.com/
  5659. */
  5660. THREE.DirectionalLight = function ( hex, intensity ) {
  5661. THREE.Light.call( this, hex );
  5662. this.position.set( 0, 1, 0 );
  5663. this.target = new THREE.Object3D();
  5664. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5665. this.castShadow = false;
  5666. this.onlyShadow = false;
  5667. //
  5668. this.shadowCameraNear = 50;
  5669. this.shadowCameraFar = 5000;
  5670. this.shadowCameraLeft = -500;
  5671. this.shadowCameraRight = 500;
  5672. this.shadowCameraTop = 500;
  5673. this.shadowCameraBottom = -500;
  5674. this.shadowCameraVisible = false;
  5675. this.shadowBias = 0;
  5676. this.shadowDarkness = 0.5;
  5677. this.shadowMapWidth = 512;
  5678. this.shadowMapHeight = 512;
  5679. //
  5680. this.shadowCascade = false;
  5681. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  5682. this.shadowCascadeCount = 2;
  5683. this.shadowCascadeBias = [ 0, 0, 0 ];
  5684. this.shadowCascadeWidth = [ 512, 512, 512 ];
  5685. this.shadowCascadeHeight = [ 512, 512, 512 ];
  5686. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  5687. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  5688. this.shadowCascadeArray = [];
  5689. //
  5690. this.shadowMap = null;
  5691. this.shadowMapSize = null;
  5692. this.shadowCamera = null;
  5693. this.shadowMatrix = null;
  5694. };
  5695. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  5696. THREE.DirectionalLight.prototype.clone = function () {
  5697. var light = new THREE.DirectionalLight();
  5698. THREE.Light.prototype.clone.call( this, light );
  5699. light.target = this.target.clone();
  5700. light.intensity = this.intensity;
  5701. light.castShadow = this.castShadow;
  5702. light.onlyShadow = this.onlyShadow;
  5703. return light;
  5704. };
  5705. /**
  5706. * @author alteredq / http://alteredqualia.com/
  5707. */
  5708. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  5709. THREE.Light.call( this, skyColorHex );
  5710. this.position.set( 0, 100, 0 );
  5711. this.groundColor = new THREE.Color( groundColorHex );
  5712. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5713. };
  5714. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  5715. THREE.HemisphereLight.prototype.clone = function () {
  5716. var light = new THREE.PointLight();
  5717. THREE.Light.prototype.clone.call( this, light );
  5718. light.groundColor.copy( this.groundColor );
  5719. light.intensity = this.intensity;
  5720. return light;
  5721. };
  5722. /**
  5723. * @author mrdoob / http://mrdoob.com/
  5724. */
  5725. THREE.PointLight = function ( hex, intensity, distance ) {
  5726. THREE.Light.call( this, hex );
  5727. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5728. this.distance = ( distance !== undefined ) ? distance : 0;
  5729. };
  5730. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  5731. THREE.PointLight.prototype.clone = function () {
  5732. var light = new THREE.PointLight();
  5733. THREE.Light.prototype.clone.call( this, light );
  5734. light.intensity = this.intensity;
  5735. light.distance = this.distance;
  5736. return light;
  5737. };
  5738. /**
  5739. * @author alteredq / http://alteredqualia.com/
  5740. */
  5741. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  5742. THREE.Light.call( this, hex );
  5743. this.position.set( 0, 1, 0 );
  5744. this.target = new THREE.Object3D();
  5745. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5746. this.distance = ( distance !== undefined ) ? distance : 0;
  5747. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  5748. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  5749. this.castShadow = false;
  5750. this.onlyShadow = false;
  5751. //
  5752. this.shadowCameraNear = 50;
  5753. this.shadowCameraFar = 5000;
  5754. this.shadowCameraFov = 50;
  5755. this.shadowCameraVisible = false;
  5756. this.shadowBias = 0;
  5757. this.shadowDarkness = 0.5;
  5758. this.shadowMapWidth = 512;
  5759. this.shadowMapHeight = 512;
  5760. //
  5761. this.shadowMap = null;
  5762. this.shadowMapSize = null;
  5763. this.shadowCamera = null;
  5764. this.shadowMatrix = null;
  5765. };
  5766. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  5767. THREE.SpotLight.prototype.clone = function () {
  5768. var light = new THREE.SpotLight();
  5769. THREE.Light.prototype.clone.call( this, light );
  5770. light.target = this.target.clone();
  5771. light.intensity = this.intensity;
  5772. light.distance = this.distance;
  5773. light.angle = this.angle;
  5774. light.exponent = this.exponent;
  5775. light.castShadow = this.castShadow;
  5776. light.onlyShadow = this.onlyShadow;
  5777. return light;
  5778. };
  5779. /**
  5780. * @author alteredq / http://alteredqualia.com/
  5781. */
  5782. THREE.Loader = function ( showStatus ) {
  5783. this.showStatus = showStatus;
  5784. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  5785. this.onLoadStart = function () {};
  5786. this.onLoadProgress = function () {};
  5787. this.onLoadComplete = function () {};
  5788. };
  5789. THREE.Loader.prototype = {
  5790. constructor: THREE.Loader,
  5791. crossOrigin: 'anonymous',
  5792. addStatusElement: function () {
  5793. var e = document.createElement( "div" );
  5794. e.style.position = "absolute";
  5795. e.style.right = "0px";
  5796. e.style.top = "0px";
  5797. e.style.fontSize = "0.8em";
  5798. e.style.textAlign = "left";
  5799. e.style.background = "rgba(0,0,0,0.25)";
  5800. e.style.color = "#fff";
  5801. e.style.width = "120px";
  5802. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  5803. e.style.zIndex = 1000;
  5804. e.innerHTML = "Loading ...";
  5805. return e;
  5806. },
  5807. updateProgress: function ( progress ) {
  5808. var message = "Loaded ";
  5809. if ( progress.total ) {
  5810. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  5811. } else {
  5812. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  5813. }
  5814. this.statusDomElement.innerHTML = message;
  5815. },
  5816. extractUrlBase: function ( url ) {
  5817. var parts = url.split( '/' );
  5818. parts.pop();
  5819. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  5820. },
  5821. initMaterials: function ( materials, texturePath ) {
  5822. var array = [];
  5823. for ( var i = 0; i < materials.length; ++ i ) {
  5824. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  5825. }
  5826. return array;
  5827. },
  5828. needsTangents: function ( materials ) {
  5829. for( var i = 0, il = materials.length; i < il; i ++ ) {
  5830. var m = materials[ i ];
  5831. if ( m instanceof THREE.ShaderMaterial ) return true;
  5832. }
  5833. return false;
  5834. },
  5835. createMaterial: function ( m, texturePath ) {
  5836. var _this = this;
  5837. function is_pow2( n ) {
  5838. var l = Math.log( n ) / Math.LN2;
  5839. return Math.floor( l ) == l;
  5840. }
  5841. function nearest_pow2( n ) {
  5842. var l = Math.log( n ) / Math.LN2;
  5843. return Math.pow( 2, Math.round( l ) );
  5844. }
  5845. function load_image( where, url ) {
  5846. var image = new Image();
  5847. image.onload = function () {
  5848. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  5849. var width = nearest_pow2( this.width );
  5850. var height = nearest_pow2( this.height );
  5851. where.image.width = width;
  5852. where.image.height = height;
  5853. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  5854. } else {
  5855. where.image = this;
  5856. }
  5857. where.needsUpdate = true;
  5858. };
  5859. image.crossOrigin = _this.crossOrigin;
  5860. image.src = url;
  5861. }
  5862. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  5863. var isCompressed = /\.dds$/i.test( sourceFile );
  5864. var fullPath = texturePath + "/" + sourceFile;
  5865. if ( isCompressed ) {
  5866. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  5867. where[ name ] = texture;
  5868. } else {
  5869. var texture = document.createElement( 'canvas' );
  5870. where[ name ] = new THREE.Texture( texture );
  5871. }
  5872. where[ name ].sourceFile = sourceFile;
  5873. if( repeat ) {
  5874. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  5875. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  5876. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  5877. }
  5878. if ( offset ) {
  5879. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  5880. }
  5881. if ( wrap ) {
  5882. var wrapMap = {
  5883. "repeat": THREE.RepeatWrapping,
  5884. "mirror": THREE.MirroredRepeatWrapping
  5885. }
  5886. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  5887. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  5888. }
  5889. if ( anisotropy ) {
  5890. where[ name ].anisotropy = anisotropy;
  5891. }
  5892. if ( ! isCompressed ) {
  5893. load_image( where[ name ], fullPath );
  5894. }
  5895. }
  5896. function rgb2hex( rgb ) {
  5897. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  5898. }
  5899. // defaults
  5900. var mtype = "MeshLambertMaterial";
  5901. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  5902. // parameters from model file
  5903. if ( m.shading ) {
  5904. var shading = m.shading.toLowerCase();
  5905. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  5906. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  5907. }
  5908. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  5909. mpars.blending = THREE[ m.blending ];
  5910. }
  5911. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  5912. mpars.transparent = m.transparent;
  5913. }
  5914. if ( m.depthTest !== undefined ) {
  5915. mpars.depthTest = m.depthTest;
  5916. }
  5917. if ( m.depthWrite !== undefined ) {
  5918. mpars.depthWrite = m.depthWrite;
  5919. }
  5920. if ( m.visible !== undefined ) {
  5921. mpars.visible = m.visible;
  5922. }
  5923. if ( m.flipSided !== undefined ) {
  5924. mpars.side = THREE.BackSide;
  5925. }
  5926. if ( m.doubleSided !== undefined ) {
  5927. mpars.side = THREE.DoubleSide;
  5928. }
  5929. if ( m.wireframe !== undefined ) {
  5930. mpars.wireframe = m.wireframe;
  5931. }
  5932. if ( m.vertexColors !== undefined ) {
  5933. if ( m.vertexColors === "face" ) {
  5934. mpars.vertexColors = THREE.FaceColors;
  5935. } else if ( m.vertexColors ) {
  5936. mpars.vertexColors = THREE.VertexColors;
  5937. }
  5938. }
  5939. // colors
  5940. if ( m.colorDiffuse ) {
  5941. mpars.color = rgb2hex( m.colorDiffuse );
  5942. } else if ( m.DbgColor ) {
  5943. mpars.color = m.DbgColor;
  5944. }
  5945. if ( m.colorSpecular ) {
  5946. mpars.specular = rgb2hex( m.colorSpecular );
  5947. }
  5948. if ( m.colorAmbient ) {
  5949. mpars.ambient = rgb2hex( m.colorAmbient );
  5950. }
  5951. // modifiers
  5952. if ( m.transparency ) {
  5953. mpars.opacity = m.transparency;
  5954. }
  5955. if ( m.specularCoef ) {
  5956. mpars.shininess = m.specularCoef;
  5957. }
  5958. // textures
  5959. if ( m.mapDiffuse && texturePath ) {
  5960. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  5961. }
  5962. if ( m.mapLight && texturePath ) {
  5963. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  5964. }
  5965. if ( m.mapBump && texturePath ) {
  5966. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  5967. }
  5968. if ( m.mapNormal && texturePath ) {
  5969. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  5970. }
  5971. if ( m.mapSpecular && texturePath ) {
  5972. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  5973. }
  5974. //
  5975. if ( m.mapBumpScale ) {
  5976. mpars.bumpScale = m.mapBumpScale;
  5977. }
  5978. // special case for normal mapped material
  5979. if ( m.mapNormal ) {
  5980. var shader = THREE.ShaderLib[ "normalmap" ];
  5981. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5982. uniforms[ "tNormal" ].value = mpars.normalMap;
  5983. if ( m.mapNormalFactor ) {
  5984. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  5985. }
  5986. if ( mpars.map ) {
  5987. uniforms[ "tDiffuse" ].value = mpars.map;
  5988. uniforms[ "enableDiffuse" ].value = true;
  5989. }
  5990. if ( mpars.specularMap ) {
  5991. uniforms[ "tSpecular" ].value = mpars.specularMap;
  5992. uniforms[ "enableSpecular" ].value = true;
  5993. }
  5994. if ( mpars.lightMap ) {
  5995. uniforms[ "tAO" ].value = mpars.lightMap;
  5996. uniforms[ "enableAO" ].value = true;
  5997. }
  5998. // for the moment don't handle displacement texture
  5999. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  6000. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  6001. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  6002. uniforms[ "uShininess" ].value = mpars.shininess;
  6003. if ( mpars.opacity !== undefined ) {
  6004. uniforms[ "uOpacity" ].value = mpars.opacity;
  6005. }
  6006. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6007. var material = new THREE.ShaderMaterial( parameters );
  6008. if ( mpars.transparent ) {
  6009. material.transparent = true;
  6010. }
  6011. } else {
  6012. var material = new THREE[ mtype ]( mpars );
  6013. }
  6014. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  6015. return material;
  6016. }
  6017. };
  6018. /**
  6019. * @author mrdoob / http://mrdoob.com/
  6020. */
  6021. THREE.XHRLoader = function ( manager ) {
  6022. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6023. };
  6024. THREE.XHRLoader.prototype = {
  6025. constructor: THREE.XHRLoader,
  6026. load: function ( url, onLoad, onProgress, onError ) {
  6027. var scope = this;
  6028. var request = new XMLHttpRequest();
  6029. if ( onLoad !== undefined ) {
  6030. request.addEventListener( 'load', function ( event ) {
  6031. scope.manager.itemEnd( url );
  6032. onLoad( event.target.responseText );
  6033. }, false );
  6034. }
  6035. if ( onProgress !== undefined ) {
  6036. request.addEventListener( 'progress', function ( event ) {
  6037. onProgress( event );
  6038. }, false );
  6039. }
  6040. if ( onError !== undefined ) {
  6041. request.addEventListener( 'error', function ( event ) {
  6042. onError( event );
  6043. }, false );
  6044. }
  6045. if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
  6046. request.open( 'GET', url, true );
  6047. request.send( null );
  6048. scope.manager.itemStart( url );
  6049. },
  6050. setCrossOrigin: function ( value ) {
  6051. this.crossOrigin = value;
  6052. }
  6053. };
  6054. /**
  6055. * @author mrdoob / http://mrdoob.com/
  6056. */
  6057. THREE.ImageLoader = function ( manager ) {
  6058. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6059. };
  6060. THREE.ImageLoader.prototype = {
  6061. constructor: THREE.ImageLoader,
  6062. load: function ( url, onLoad, onProgress, onError ) {
  6063. var scope = this;
  6064. var image = document.createElement( 'img' );
  6065. if ( onLoad !== undefined ) {
  6066. image.addEventListener( 'load', function ( event ) {
  6067. scope.manager.itemEnd( url );
  6068. onLoad( this );
  6069. }, false );
  6070. }
  6071. if ( onProgress !== undefined ) {
  6072. image.addEventListener( 'progress', function ( event ) {
  6073. onProgress( event );
  6074. }, false );
  6075. }
  6076. if ( onError !== undefined ) {
  6077. image.addEventListener( 'error', function ( event ) {
  6078. onError( event );
  6079. }, false );
  6080. }
  6081. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  6082. image.src = url;
  6083. scope.manager.itemStart( url );
  6084. },
  6085. setCrossOrigin: function ( value ) {
  6086. this.crossOrigin = value;
  6087. }
  6088. }
  6089. /**
  6090. * @author mrdoob / http://mrdoob.com/
  6091. * @author alteredq / http://alteredqualia.com/
  6092. */
  6093. THREE.JSONLoader = function ( showStatus ) {
  6094. THREE.Loader.call( this, showStatus );
  6095. this.withCredentials = false;
  6096. };
  6097. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  6098. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  6099. var scope = this;
  6100. // todo: unify load API to for easier SceneLoader use
  6101. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  6102. this.onLoadStart();
  6103. this.loadAjaxJSON( this, url, callback, texturePath );
  6104. };
  6105. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  6106. var xhr = new XMLHttpRequest();
  6107. var length = 0;
  6108. xhr.onreadystatechange = function () {
  6109. if ( xhr.readyState === xhr.DONE ) {
  6110. if ( xhr.status === 200 || xhr.status === 0 ) {
  6111. if ( xhr.responseText ) {
  6112. var json = JSON.parse( xhr.responseText );
  6113. var result = context.parse( json, texturePath );
  6114. callback( result.geometry, result.materials );
  6115. } else {
  6116. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  6117. }
  6118. // in context of more complex asset initialization
  6119. // do not block on single failed file
  6120. // maybe should go even one more level up
  6121. context.onLoadComplete();
  6122. } else {
  6123. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  6124. }
  6125. } else if ( xhr.readyState === xhr.LOADING ) {
  6126. if ( callbackProgress ) {
  6127. if ( length === 0 ) {
  6128. length = xhr.getResponseHeader( "Content-Length" );
  6129. }
  6130. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  6131. }
  6132. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  6133. if ( callbackProgress !== undefined ) {
  6134. length = xhr.getResponseHeader( "Content-Length" );
  6135. }
  6136. }
  6137. };
  6138. xhr.open( "GET", url, true );
  6139. xhr.withCredentials = this.withCredentials;
  6140. xhr.send( null );
  6141. };
  6142. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  6143. var scope = this,
  6144. geometry = new THREE.Geometry(),
  6145. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  6146. parseModel( scale );
  6147. parseSkin();
  6148. parseMorphing( scale );
  6149. geometry.computeCentroids();
  6150. geometry.computeFaceNormals();
  6151. function parseModel( scale ) {
  6152. function isBitSet( value, position ) {
  6153. return value & ( 1 << position );
  6154. }
  6155. var i, j, fi,
  6156. offset, zLength, nVertices,
  6157. colorIndex, normalIndex, uvIndex, materialIndex,
  6158. type,
  6159. isQuad,
  6160. hasMaterial,
  6161. hasFaceUv, hasFaceVertexUv,
  6162. hasFaceNormal, hasFaceVertexNormal,
  6163. hasFaceColor, hasFaceVertexColor,
  6164. vertex, face, color, normal,
  6165. uvLayer, uvs, u, v,
  6166. faces = json.faces,
  6167. vertices = json.vertices,
  6168. normals = json.normals,
  6169. colors = json.colors,
  6170. nUvLayers = 0;
  6171. // disregard empty arrays
  6172. for ( i = 0; i < json.uvs.length; i++ ) {
  6173. if ( json.uvs[ i ].length ) nUvLayers ++;
  6174. }
  6175. for ( i = 0; i < nUvLayers; i++ ) {
  6176. geometry.faceUvs[ i ] = [];
  6177. geometry.faceVertexUvs[ i ] = [];
  6178. }
  6179. offset = 0;
  6180. zLength = vertices.length;
  6181. while ( offset < zLength ) {
  6182. vertex = new THREE.Vector3();
  6183. vertex.x = vertices[ offset ++ ] * scale;
  6184. vertex.y = vertices[ offset ++ ] * scale;
  6185. vertex.z = vertices[ offset ++ ] * scale;
  6186. geometry.vertices.push( vertex );
  6187. }
  6188. offset = 0;
  6189. zLength = faces.length;
  6190. while ( offset < zLength ) {
  6191. type = faces[ offset ++ ];
  6192. isQuad = isBitSet( type, 0 );
  6193. hasMaterial = isBitSet( type, 1 );
  6194. hasFaceUv = isBitSet( type, 2 );
  6195. hasFaceVertexUv = isBitSet( type, 3 );
  6196. hasFaceNormal = isBitSet( type, 4 );
  6197. hasFaceVertexNormal = isBitSet( type, 5 );
  6198. hasFaceColor = isBitSet( type, 6 );
  6199. hasFaceVertexColor = isBitSet( type, 7 );
  6200. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  6201. if ( isQuad ) {
  6202. face = new THREE.Face4();
  6203. face.a = faces[ offset ++ ];
  6204. face.b = faces[ offset ++ ];
  6205. face.c = faces[ offset ++ ];
  6206. face.d = faces[ offset ++ ];
  6207. nVertices = 4;
  6208. } else {
  6209. face = new THREE.Face3();
  6210. face.a = faces[ offset ++ ];
  6211. face.b = faces[ offset ++ ];
  6212. face.c = faces[ offset ++ ];
  6213. nVertices = 3;
  6214. }
  6215. if ( hasMaterial ) {
  6216. materialIndex = faces[ offset ++ ];
  6217. face.materialIndex = materialIndex;
  6218. }
  6219. // to get face <=> uv index correspondence
  6220. fi = geometry.faces.length;
  6221. if ( hasFaceUv ) {
  6222. for ( i = 0; i < nUvLayers; i++ ) {
  6223. uvLayer = json.uvs[ i ];
  6224. uvIndex = faces[ offset ++ ];
  6225. u = uvLayer[ uvIndex * 2 ];
  6226. v = uvLayer[ uvIndex * 2 + 1 ];
  6227. geometry.faceUvs[ i ][ fi ] = new THREE.Vector2( u, v );
  6228. }
  6229. }
  6230. if ( hasFaceVertexUv ) {
  6231. for ( i = 0; i < nUvLayers; i++ ) {
  6232. uvLayer = json.uvs[ i ];
  6233. uvs = [];
  6234. for ( j = 0; j < nVertices; j ++ ) {
  6235. uvIndex = faces[ offset ++ ];
  6236. u = uvLayer[ uvIndex * 2 ];
  6237. v = uvLayer[ uvIndex * 2 + 1 ];
  6238. uvs[ j ] = new THREE.Vector2( u, v );
  6239. }
  6240. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  6241. }
  6242. }
  6243. if ( hasFaceNormal ) {
  6244. normalIndex = faces[ offset ++ ] * 3;
  6245. normal = new THREE.Vector3();
  6246. normal.x = normals[ normalIndex ++ ];
  6247. normal.y = normals[ normalIndex ++ ];
  6248. normal.z = normals[ normalIndex ];
  6249. face.normal = normal;
  6250. }
  6251. if ( hasFaceVertexNormal ) {
  6252. for ( i = 0; i < nVertices; i++ ) {
  6253. normalIndex = faces[ offset ++ ] * 3;
  6254. normal = new THREE.Vector3();
  6255. normal.x = normals[ normalIndex ++ ];
  6256. normal.y = normals[ normalIndex ++ ];
  6257. normal.z = normals[ normalIndex ];
  6258. face.vertexNormals.push( normal );
  6259. }
  6260. }
  6261. if ( hasFaceColor ) {
  6262. colorIndex = faces[ offset ++ ];
  6263. color = new THREE.Color( colors[ colorIndex ] );
  6264. face.color = color;
  6265. }
  6266. if ( hasFaceVertexColor ) {
  6267. for ( i = 0; i < nVertices; i++ ) {
  6268. colorIndex = faces[ offset ++ ];
  6269. color = new THREE.Color( colors[ colorIndex ] );
  6270. face.vertexColors.push( color );
  6271. }
  6272. }
  6273. geometry.faces.push( face );
  6274. }
  6275. };
  6276. function parseSkin() {
  6277. var i, l, x, y, z, w, a, b, c, d;
  6278. if ( json.skinWeights ) {
  6279. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  6280. x = json.skinWeights[ i ];
  6281. y = json.skinWeights[ i + 1 ];
  6282. z = 0;
  6283. w = 0;
  6284. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  6285. }
  6286. }
  6287. if ( json.skinIndices ) {
  6288. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  6289. a = json.skinIndices[ i ];
  6290. b = json.skinIndices[ i + 1 ];
  6291. c = 0;
  6292. d = 0;
  6293. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  6294. }
  6295. }
  6296. geometry.bones = json.bones;
  6297. geometry.animation = json.animation;
  6298. };
  6299. function parseMorphing( scale ) {
  6300. if ( json.morphTargets !== undefined ) {
  6301. var i, l, v, vl, dstVertices, srcVertices;
  6302. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  6303. geometry.morphTargets[ i ] = {};
  6304. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  6305. geometry.morphTargets[ i ].vertices = [];
  6306. dstVertices = geometry.morphTargets[ i ].vertices;
  6307. srcVertices = json.morphTargets [ i ].vertices;
  6308. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  6309. var vertex = new THREE.Vector3();
  6310. vertex.x = srcVertices[ v ] * scale;
  6311. vertex.y = srcVertices[ v + 1 ] * scale;
  6312. vertex.z = srcVertices[ v + 2 ] * scale;
  6313. dstVertices.push( vertex );
  6314. }
  6315. }
  6316. }
  6317. if ( json.morphColors !== undefined ) {
  6318. var i, l, c, cl, dstColors, srcColors, color;
  6319. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  6320. geometry.morphColors[ i ] = {};
  6321. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  6322. geometry.morphColors[ i ].colors = [];
  6323. dstColors = geometry.morphColors[ i ].colors;
  6324. srcColors = json.morphColors [ i ].colors;
  6325. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  6326. color = new THREE.Color( 0xffaa00 );
  6327. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  6328. dstColors.push( color );
  6329. }
  6330. }
  6331. }
  6332. };
  6333. if ( json.materials === undefined ) {
  6334. return { geometry: geometry };
  6335. } else {
  6336. var materials = this.initMaterials( json.materials, texturePath );
  6337. if ( this.needsTangents( materials ) ) {
  6338. geometry.computeTangents();
  6339. }
  6340. return { geometry: geometry, materials: materials };
  6341. }
  6342. };
  6343. /**
  6344. * @author mrdoob / http://mrdoob.com/
  6345. */
  6346. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  6347. var scope = this;
  6348. var loaded = 0, total = 0;
  6349. this.onLoad = onLoad;
  6350. this.onProgress = onProgress;
  6351. this.onError = onError;
  6352. this.itemStart = function ( url ) {
  6353. total ++;
  6354. };
  6355. this.itemEnd = function ( url ) {
  6356. loaded ++;
  6357. if ( scope.onProgress !== undefined ) {
  6358. scope.onProgress( url, loaded, total );
  6359. }
  6360. if ( loaded === total && scope.onLoad !== undefined ) {
  6361. scope.onLoad();
  6362. }
  6363. };
  6364. };
  6365. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  6366. /**
  6367. * @author mrdoob / http://mrdoob.com/
  6368. */
  6369. THREE.GeometryLoader = function ( manager ) {
  6370. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6371. };
  6372. THREE.GeometryLoader.prototype = {
  6373. constructor: THREE.GeometryLoader,
  6374. load: function ( url, onLoad, onProgress, onError ) {
  6375. var scope = this;
  6376. var loader = new THREE.XHRLoader();
  6377. loader.setCrossOrigin( this.crossOrigin );
  6378. loader.load( url, function ( text ) {
  6379. onLoad( scope.parse( JSON.parse( text ) ) );
  6380. } );
  6381. },
  6382. setCrossOrigin: function ( value ) {
  6383. this.crossOrigin = value;
  6384. },
  6385. parse: function ( json ) {
  6386. }
  6387. };
  6388. /**
  6389. * @author mrdoob / http://mrdoob.com/
  6390. */
  6391. THREE.MaterialLoader = function ( manager ) {
  6392. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6393. };
  6394. THREE.MaterialLoader.prototype = {
  6395. constructor: THREE.MaterialLoader,
  6396. load: function ( url, onLoad, onProgress, onError ) {
  6397. var scope = this;
  6398. var loader = new THREE.XHRLoader();
  6399. loader.setCrossOrigin( this.crossOrigin );
  6400. loader.load( url, function ( text ) {
  6401. onLoad( scope.parse( JSON.parse( text ) ) );
  6402. } );
  6403. },
  6404. setCrossOrigin: function ( value ) {
  6405. this.crossOrigin = value;
  6406. },
  6407. parse: function ( json ) {
  6408. var material;
  6409. switch ( json.type ) {
  6410. case 'MeshBasicMaterial':
  6411. material = new THREE.MeshBasicMaterial( {
  6412. color: json.color,
  6413. opacity: json.opacity,
  6414. transparent: json.transparent,
  6415. wireframe: json.wireframe
  6416. } );
  6417. break;
  6418. case 'MeshLambertMaterial':
  6419. material = new THREE.MeshLambertMaterial( {
  6420. color: json.color,
  6421. ambient: json.ambient,
  6422. emissive: json.emissive,
  6423. opacity: json.opacity,
  6424. transparent: json.transparent,
  6425. wireframe: json.wireframe
  6426. } );
  6427. break;
  6428. case 'MeshPhongMaterial':
  6429. material = new THREE.MeshPhongMaterial( {
  6430. color: json.color,
  6431. ambient: json.ambient,
  6432. emissive: json.emissive,
  6433. specular: json.specular,
  6434. shininess: json.shininess,
  6435. opacity: json.opacity,
  6436. transparent: json.transparent,
  6437. wireframe: json.wireframe
  6438. } );
  6439. break;
  6440. case 'MeshNormalMaterial':
  6441. material = new THREE.MeshNormalMaterial( {
  6442. opacity: json.opacity,
  6443. transparent: json.transparent,
  6444. wireframe: json.wireframe
  6445. } );
  6446. break;
  6447. case 'MeshDepthMaterial':
  6448. material = new THREE.MeshDepthMaterial( {
  6449. opacity: json.opacity,
  6450. transparent: json.transparent,
  6451. wireframe: json.wireframe
  6452. } );
  6453. break;
  6454. }
  6455. return material;
  6456. }
  6457. };
  6458. /**
  6459. * @author mrdoob / http://mrdoob.com/
  6460. */
  6461. THREE.ObjectLoader = function ( manager ) {
  6462. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6463. };
  6464. THREE.ObjectLoader.prototype = {
  6465. constructor: THREE.ObjectLoader,
  6466. load: function ( url, onLoad, onProgress, onError ) {
  6467. var scope = this;
  6468. var loader = new THREE.XHRLoader( scope.manager );
  6469. loader.setCrossOrigin( this.crossOrigin );
  6470. loader.load( url, function ( text ) {
  6471. onLoad( scope.parse( JSON.parse( text ) ) );
  6472. } );
  6473. },
  6474. setCrossOrigin: function ( value ) {
  6475. this.crossOrigin = value;
  6476. },
  6477. parse: function ( json ) {
  6478. var geometries = this.parseGeometries( json.geometries );
  6479. var materials = this.parseMaterials( json.materials );
  6480. var object = this.parseObject( json.object, geometries, materials );
  6481. return object;
  6482. },
  6483. parseGeometries: function ( json ) {
  6484. var geometries = {};
  6485. if ( json !== undefined ) {
  6486. var loader = new THREE.JSONLoader();
  6487. for ( var i = 0, l = json.length; i < l; i ++ ) {
  6488. var geometry;
  6489. var data = json[ i ];
  6490. switch ( data.type ) {
  6491. case 'PlaneGeometry':
  6492. geometry = new THREE.PlaneGeometry(
  6493. data.width,
  6494. data.height,
  6495. data.widthSegments,
  6496. data.heightSegments
  6497. );
  6498. break;
  6499. case 'CubeGeometry':
  6500. geometry = new THREE.CubeGeometry(
  6501. data.width,
  6502. data.height,
  6503. data.depth,
  6504. data.widthSegments,
  6505. data.heightSegments,
  6506. data.depthSegments
  6507. );
  6508. break;
  6509. case 'CylinderGeometry':
  6510. geometry = new THREE.CylinderGeometry(
  6511. data.radiusTop,
  6512. data.radiusBottom,
  6513. data.height,
  6514. data.radiusSegments,
  6515. data.heightSegments,
  6516. data.openEnded
  6517. );
  6518. break;
  6519. case 'SphereGeometry':
  6520. geometry = new THREE.SphereGeometry(
  6521. data.radius,
  6522. data.widthSegments,
  6523. data.heightSegments,
  6524. data.phiStart,
  6525. data.phiLength,
  6526. data.thetaStart,
  6527. data.thetaLength
  6528. );
  6529. break;
  6530. case 'IcosahedronGeometry':
  6531. geometry = new THREE.IcosahedronGeometry(
  6532. data.radius,
  6533. data.detail
  6534. );
  6535. break;
  6536. case 'TorusGeometry':
  6537. geometry = new THREE.TorusGeometry(
  6538. data.radius,
  6539. data.tube,
  6540. data.radialSegments,
  6541. data.tubularSegments,
  6542. data.arc
  6543. );
  6544. break;
  6545. case 'TorusKnotGeometry':
  6546. geometry = new THREE.TorusKnotGeometry(
  6547. data.radius,
  6548. data.tube,
  6549. data.radialSegments,
  6550. data.tubularSegments,
  6551. data.p,
  6552. data.q,
  6553. data.heightScale
  6554. );
  6555. break;
  6556. case 'Geometry':
  6557. geometry = loader.parse( data.data ).geometry;
  6558. break;
  6559. }
  6560. if ( data.id !== undefined ) geometry.id = data.id;
  6561. if ( data.name !== undefined ) geometry.name = data.name;
  6562. geometries[ data.id ] = geometry;
  6563. }
  6564. }
  6565. return geometries;
  6566. },
  6567. parseMaterials: function ( json ) {
  6568. var materials = {};
  6569. if ( json !== undefined ) {
  6570. var loader = new THREE.MaterialLoader();
  6571. for ( var i = 0, l = json.length; i < l; i ++ ) {
  6572. var data = json[ i ];
  6573. var material = loader.parse( data );
  6574. if ( data.id !== undefined ) material.id = data.id;
  6575. if ( data.name !== undefined ) material.name = data.name;
  6576. materials[ data.id ] = material;
  6577. }
  6578. }
  6579. return materials;
  6580. },
  6581. parseObject: function () {
  6582. var matrix = new THREE.Matrix4();
  6583. return function ( data, geometries, materials ) {
  6584. var object;
  6585. switch ( data.type ) {
  6586. case 'Scene':
  6587. object = new THREE.Scene();
  6588. break;
  6589. case 'PerspectiveCamera':
  6590. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  6591. break;
  6592. case 'OrthographicCamera':
  6593. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  6594. break;
  6595. case 'AmbientLight':
  6596. object = new THREE.AmbientLight( data.color );
  6597. break;
  6598. case 'DirectionalLight':
  6599. object = new THREE.DirectionalLight( data.color, data.intensity );
  6600. break;
  6601. case 'PointLight':
  6602. object = new THREE.PointLight( data.color, data.intensity, data.distance );
  6603. break;
  6604. case 'SpotLight':
  6605. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent );
  6606. break;
  6607. case 'HemisphereLight':
  6608. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  6609. break;
  6610. case 'Mesh':
  6611. object = new THREE.Mesh( geometries[ data.geometry ], materials[ data.material ] );
  6612. break;
  6613. default:
  6614. object = new THREE.Object3D();
  6615. }
  6616. if ( data.matrix !== undefined ) {
  6617. matrix.fromArray( data.matrix );
  6618. matrix.decompose( object.position, object.quaternion, object.scale );
  6619. } else {
  6620. if ( data.position !== undefined ) object.position.fromArray( data.position );
  6621. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  6622. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  6623. }
  6624. if ( data.id !== undefined ) object.id = data.id;
  6625. if ( data.name !== undefined ) object.name = data.name;
  6626. if ( data.visible !== undefined ) object.visible = data.visible;
  6627. if ( data.userData !== undefined ) object.userData = data.userData;
  6628. if ( data.children !== undefined ) {
  6629. for ( var child in data.children ) {
  6630. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  6631. }
  6632. }
  6633. return object;
  6634. }
  6635. }()
  6636. };
  6637. /**
  6638. * @author alteredq / http://alteredqualia.com/
  6639. */
  6640. THREE.SceneLoader = function () {
  6641. this.onLoadStart = function () {};
  6642. this.onLoadProgress = function() {};
  6643. this.onLoadComplete = function () {};
  6644. this.callbackSync = function () {};
  6645. this.callbackProgress = function () {};
  6646. this.geometryHandlers = {};
  6647. this.hierarchyHandlers = {};
  6648. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  6649. };
  6650. THREE.SceneLoader.prototype = {
  6651. constructor: THREE.SceneLoader,
  6652. load: function ( url, onLoad, onProgress, onError ) {
  6653. var scope = this;
  6654. var loader = new THREE.XHRLoader( scope.manager );
  6655. loader.setCrossOrigin( this.crossOrigin );
  6656. loader.load( url, function ( text ) {
  6657. scope.parse( JSON.parse( text ), onLoad, url );
  6658. } );
  6659. },
  6660. setCrossOrigin: function ( value ) {
  6661. this.crossOrigin = value;
  6662. },
  6663. addGeometryHandler: function ( typeID, loaderClass ) {
  6664. this.geometryHandlers[ typeID ] = { "loaderClass": loaderClass };
  6665. },
  6666. addHierarchyHandler: function ( typeID, loaderClass ) {
  6667. this.hierarchyHandlers[ typeID ] = { "loaderClass": loaderClass };
  6668. },
  6669. parse: function ( json, callbackFinished, url ) {
  6670. var scope = this;
  6671. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  6672. var geometry, material, camera, fog,
  6673. texture, images, color,
  6674. light, hex, intensity,
  6675. counter_models, counter_textures,
  6676. total_models, total_textures,
  6677. result;
  6678. var target_array = [];
  6679. var data = json;
  6680. // async geometry loaders
  6681. for ( var typeID in this.geometryHandlers ) {
  6682. var loaderClass = this.geometryHandlers[ typeID ][ "loaderClass" ];
  6683. this.geometryHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  6684. }
  6685. // async hierachy loaders
  6686. for ( var typeID in this.hierarchyHandlers ) {
  6687. var loaderClass = this.hierarchyHandlers[ typeID ][ "loaderClass" ];
  6688. this.hierarchyHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  6689. }
  6690. counter_models = 0;
  6691. counter_textures = 0;
  6692. result = {
  6693. scene: new THREE.Scene(),
  6694. geometries: {},
  6695. face_materials: {},
  6696. materials: {},
  6697. textures: {},
  6698. objects: {},
  6699. cameras: {},
  6700. lights: {},
  6701. fogs: {},
  6702. empties: {},
  6703. groups: {}
  6704. };
  6705. if ( data.transform ) {
  6706. var position = data.transform.position,
  6707. rotation = data.transform.rotation,
  6708. scale = data.transform.scale;
  6709. if ( position ) {
  6710. result.scene.position.fromArray( position );
  6711. }
  6712. if ( rotation ) {
  6713. result.scene.rotation.fromArray( rotation );
  6714. }
  6715. if ( scale ) {
  6716. result.scene.scale.fromArray( scale );
  6717. }
  6718. if ( position || rotation || scale ) {
  6719. result.scene.updateMatrix();
  6720. result.scene.updateMatrixWorld();
  6721. }
  6722. }
  6723. function get_url( source_url, url_type ) {
  6724. if ( url_type == "relativeToHTML" ) {
  6725. return source_url;
  6726. } else {
  6727. return urlBase + "/" + source_url;
  6728. }
  6729. };
  6730. // toplevel loader function, delegates to handle_children
  6731. function handle_objects() {
  6732. handle_children( result.scene, data.objects );
  6733. }
  6734. // handle all the children from the loaded json and attach them to given parent
  6735. function handle_children( parent, children ) {
  6736. var mat, dst, pos, rot, scl, quat;
  6737. for ( var objID in children ) {
  6738. // check by id if child has already been handled,
  6739. // if not, create new object
  6740. var object = result.objects[ objID ];
  6741. var objJSON = children[ objID ];
  6742. if ( object === undefined ) {
  6743. // meshes
  6744. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  6745. if ( objJSON.loading === undefined ) {
  6746. var reservedTypes = {
  6747. "type": 1, "url": 1, "material": 1,
  6748. "position": 1, "rotation": 1, "scale" : 1,
  6749. "visible": 1, "children": 1, "userData": 1,
  6750. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1
  6751. };
  6752. var loaderParameters = {};
  6753. for ( var parType in objJSON ) {
  6754. if ( ! ( parType in reservedTypes ) ) {
  6755. loaderParameters[ parType ] = objJSON[ parType ];
  6756. }
  6757. }
  6758. material = result.materials[ objJSON.material ];
  6759. objJSON.loading = true;
  6760. var loader = scope.hierarchyHandlers[ objJSON.type ][ "loaderObject" ];
  6761. // ColladaLoader
  6762. if ( loader.options ) {
  6763. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  6764. // UTF8Loader
  6765. // OBJLoader
  6766. } else {
  6767. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  6768. }
  6769. }
  6770. } else if ( objJSON.geometry !== undefined ) {
  6771. geometry = result.geometries[ objJSON.geometry ];
  6772. // geometry already loaded
  6773. if ( geometry ) {
  6774. var needsTangents = false;
  6775. material = result.materials[ objJSON.material ];
  6776. needsTangents = material instanceof THREE.ShaderMaterial;
  6777. pos = objJSON.position;
  6778. rot = objJSON.rotation;
  6779. scl = objJSON.scale;
  6780. mat = objJSON.matrix;
  6781. quat = objJSON.quaternion;
  6782. // use materials from the model file
  6783. // if there is no material specified in the object
  6784. if ( ! objJSON.material ) {
  6785. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6786. }
  6787. // use materials from the model file
  6788. // if there is just empty face material
  6789. // (must create new material as each model has its own face material)
  6790. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  6791. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6792. }
  6793. if ( material instanceof THREE.MeshFaceMaterial ) {
  6794. for ( var i = 0; i < material.materials.length; i ++ ) {
  6795. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  6796. }
  6797. }
  6798. if ( needsTangents ) {
  6799. geometry.computeTangents();
  6800. }
  6801. if ( objJSON.skin ) {
  6802. object = new THREE.SkinnedMesh( geometry, material );
  6803. } else if ( objJSON.morph ) {
  6804. object = new THREE.MorphAnimMesh( geometry, material );
  6805. if ( objJSON.duration !== undefined ) {
  6806. object.duration = objJSON.duration;
  6807. }
  6808. if ( objJSON.time !== undefined ) {
  6809. object.time = objJSON.time;
  6810. }
  6811. if ( objJSON.mirroredLoop !== undefined ) {
  6812. object.mirroredLoop = objJSON.mirroredLoop;
  6813. }
  6814. if ( material.morphNormals ) {
  6815. geometry.computeMorphNormals();
  6816. }
  6817. } else {
  6818. object = new THREE.Mesh( geometry, material );
  6819. }
  6820. object.name = objID;
  6821. if ( mat ) {
  6822. object.matrixAutoUpdate = false;
  6823. object.matrix.set(
  6824. mat[0], mat[1], mat[2], mat[3],
  6825. mat[4], mat[5], mat[6], mat[7],
  6826. mat[8], mat[9], mat[10], mat[11],
  6827. mat[12], mat[13], mat[14], mat[15]
  6828. );
  6829. } else {
  6830. object.position.fromArray( pos );
  6831. if ( quat ) {
  6832. object.quaternion.fromArray( quat );
  6833. } else {
  6834. object.rotation.fromArray( rot );
  6835. }
  6836. object.scale.fromArray( scl );
  6837. }
  6838. object.visible = objJSON.visible;
  6839. object.castShadow = objJSON.castShadow;
  6840. object.receiveShadow = objJSON.receiveShadow;
  6841. parent.add( object );
  6842. result.objects[ objID ] = object;
  6843. }
  6844. // lights
  6845. } else if ( objJSON.type === "DirectionalLight" || objJSON.type === "PointLight" || objJSON.type === "AmbientLight" ) {
  6846. hex = ( objJSON.color !== undefined ) ? objJSON.color : 0xffffff;
  6847. intensity = ( objJSON.intensity !== undefined ) ? objJSON.intensity : 1;
  6848. if ( objJSON.type === "DirectionalLight" ) {
  6849. pos = objJSON.direction;
  6850. light = new THREE.DirectionalLight( hex, intensity );
  6851. light.position.fromArray( pos );
  6852. if ( objJSON.target ) {
  6853. target_array.push( { "object": light, "targetName" : objJSON.target } );
  6854. // kill existing default target
  6855. // otherwise it gets added to scene when parent gets added
  6856. light.target = null;
  6857. }
  6858. } else if ( objJSON.type === "PointLight" ) {
  6859. pos = objJSON.position;
  6860. dst = objJSON.distance;
  6861. light = new THREE.PointLight( hex, intensity, dst );
  6862. light.position.fromArray( pos );
  6863. } else if ( objJSON.type === "AmbientLight" ) {
  6864. light = new THREE.AmbientLight( hex );
  6865. }
  6866. parent.add( light );
  6867. light.name = objID;
  6868. result.lights[ objID ] = light;
  6869. result.objects[ objID ] = light;
  6870. // cameras
  6871. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  6872. pos = objJSON.position;
  6873. rot = objJSON.rotation;
  6874. quat = objJSON.quaternion;
  6875. if ( objJSON.type === "PerspectiveCamera" ) {
  6876. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  6877. } else if ( objJSON.type === "OrthographicCamera" ) {
  6878. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  6879. }
  6880. camera.name = objID;
  6881. camera.position.fromArray( pos );
  6882. if ( quat !== undefined ) {
  6883. camera.quaternion.fromArray( quat );
  6884. } else if ( rot !== undefined ) {
  6885. camera.rotation.fromArray( rot );
  6886. }
  6887. parent.add( camera );
  6888. result.cameras[ objID ] = camera;
  6889. result.objects[ objID ] = camera;
  6890. // pure Object3D
  6891. } else {
  6892. pos = objJSON.position;
  6893. rot = objJSON.rotation;
  6894. scl = objJSON.scale;
  6895. quat = objJSON.quaternion;
  6896. object = new THREE.Object3D();
  6897. object.name = objID;
  6898. object.position.fromArray( pos );
  6899. if ( quat ) {
  6900. object.quaternion.fromArray( quat );
  6901. } else {
  6902. object.rotation.fromArray( rot );
  6903. }
  6904. object.scale.fromArray( scl );
  6905. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  6906. parent.add( object );
  6907. result.objects[ objID ] = object;
  6908. result.empties[ objID ] = object;
  6909. }
  6910. if ( object ) {
  6911. if ( objJSON.userData !== undefined ) {
  6912. for ( var key in objJSON.userData ) {
  6913. var value = objJSON.userData[ key ];
  6914. object.userData[ key ] = value;
  6915. }
  6916. }
  6917. if ( objJSON.groups !== undefined ) {
  6918. for ( var i = 0; i < objJSON.groups.length; i ++ ) {
  6919. var groupID = objJSON.groups[ i ];
  6920. if ( result.groups[ groupID ] === undefined ) {
  6921. result.groups[ groupID ] = [];
  6922. }
  6923. result.groups[ groupID ].push( objID );
  6924. }
  6925. }
  6926. }
  6927. }
  6928. if ( object !== undefined && objJSON.children !== undefined ) {
  6929. handle_children( object, objJSON.children );
  6930. }
  6931. }
  6932. };
  6933. function handle_mesh( geo, mat, id ) {
  6934. result.geometries[ id ] = geo;
  6935. result.face_materials[ id ] = mat;
  6936. handle_objects();
  6937. };
  6938. function handle_hierarchy( node, id, parent, material, obj ) {
  6939. var p = obj.position;
  6940. var r = obj.rotation;
  6941. var q = obj.quaternion;
  6942. var s = obj.scale;
  6943. node.position.fromArray( p );
  6944. if ( q ) {
  6945. node.quaternion.fromArray( q );
  6946. } else {
  6947. node.rotation.fromArray( r );
  6948. }
  6949. node.scale.fromArray( s );
  6950. // override children materials
  6951. // if object material was specified in JSON explicitly
  6952. if ( material ) {
  6953. node.traverse( function ( child ) {
  6954. child.material = material;
  6955. } );
  6956. }
  6957. // override children visibility
  6958. // with root node visibility as specified in JSON
  6959. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  6960. node.traverse( function ( child ) {
  6961. child.visible = visible;
  6962. } );
  6963. parent.add( node );
  6964. node.name = id;
  6965. result.objects[ id ] = node;
  6966. handle_objects();
  6967. };
  6968. function create_callback_geometry( id ) {
  6969. return function ( geo, mat ) {
  6970. geo.name = id;
  6971. handle_mesh( geo, mat, id );
  6972. counter_models -= 1;
  6973. scope.onLoadComplete();
  6974. async_callback_gate();
  6975. }
  6976. };
  6977. function create_callback_hierachy( id, parent, material, obj ) {
  6978. return function ( event ) {
  6979. var result;
  6980. // loaders which use EventDispatcher
  6981. if ( event.content ) {
  6982. result = event.content;
  6983. // ColladaLoader
  6984. } else if ( event.dae ) {
  6985. result = event.scene;
  6986. // UTF8Loader
  6987. } else {
  6988. result = event;
  6989. }
  6990. handle_hierarchy( result, id, parent, material, obj );
  6991. counter_models -= 1;
  6992. scope.onLoadComplete();
  6993. async_callback_gate();
  6994. }
  6995. };
  6996. function create_callback_embed( id ) {
  6997. return function ( geo, mat ) {
  6998. geo.name = id;
  6999. result.geometries[ id ] = geo;
  7000. result.face_materials[ id ] = mat;
  7001. }
  7002. };
  7003. function async_callback_gate() {
  7004. var progress = {
  7005. totalModels : total_models,
  7006. totalTextures : total_textures,
  7007. loadedModels : total_models - counter_models,
  7008. loadedTextures : total_textures - counter_textures
  7009. };
  7010. scope.callbackProgress( progress, result );
  7011. scope.onLoadProgress();
  7012. if ( counter_models === 0 && counter_textures === 0 ) {
  7013. finalize();
  7014. callbackFinished( result );
  7015. }
  7016. };
  7017. function finalize() {
  7018. // take care of targets which could be asynchronously loaded objects
  7019. for ( var i = 0; i < target_array.length; i ++ ) {
  7020. var ta = target_array[ i ];
  7021. var target = result.objects[ ta.targetName ];
  7022. if ( target ) {
  7023. ta.object.target = target;
  7024. } else {
  7025. // if there was error and target of specified name doesn't exist in the scene file
  7026. // create instead dummy target
  7027. // (target must be added to scene explicitly as parent is already added)
  7028. ta.object.target = new THREE.Object3D();
  7029. result.scene.add( ta.object.target );
  7030. }
  7031. ta.object.target.userData.targetInverse = ta.object;
  7032. }
  7033. };
  7034. var callbackTexture = function ( count ) {
  7035. counter_textures -= count;
  7036. async_callback_gate();
  7037. scope.onLoadComplete();
  7038. };
  7039. // must use this instead of just directly calling callbackTexture
  7040. // because of closure in the calling context loop
  7041. var generateTextureCallback = function ( count ) {
  7042. return function () {
  7043. callbackTexture( count );
  7044. };
  7045. };
  7046. function traverse_json_hierarchy( objJSON, callback ) {
  7047. callback( objJSON );
  7048. if ( objJSON.children !== undefined ) {
  7049. for ( var objChildID in objJSON.children ) {
  7050. traverse_json_hierarchy( objJSON.children[ objChildID ], callback );
  7051. }
  7052. }
  7053. };
  7054. // first go synchronous elements
  7055. // fogs
  7056. var fogID, fogJSON;
  7057. for ( fogID in data.fogs ) {
  7058. fogJSON = data.fogs[ fogID ];
  7059. if ( fogJSON.type === "linear" ) {
  7060. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  7061. } else if ( fogJSON.type === "exp2" ) {
  7062. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  7063. }
  7064. color = fogJSON.color;
  7065. fog.color.setRGB( color[0], color[1], color[2] );
  7066. result.fogs[ fogID ] = fog;
  7067. }
  7068. // now come potentially asynchronous elements
  7069. // geometries
  7070. // count how many geometries will be loaded asynchronously
  7071. var geoID, geoJSON;
  7072. for ( geoID in data.geometries ) {
  7073. geoJSON = data.geometries[ geoID ];
  7074. if ( geoJSON.type in this.geometryHandlers ) {
  7075. counter_models += 1;
  7076. scope.onLoadStart();
  7077. }
  7078. }
  7079. // count how many hierarchies will be loaded asynchronously
  7080. for ( var objID in data.objects ) {
  7081. traverse_json_hierarchy( data.objects[ objID ], function ( objJSON ) {
  7082. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  7083. counter_models += 1;
  7084. scope.onLoadStart();
  7085. }
  7086. });
  7087. }
  7088. total_models = counter_models;
  7089. for ( geoID in data.geometries ) {
  7090. geoJSON = data.geometries[ geoID ];
  7091. if ( geoJSON.type === "cube" ) {
  7092. geometry = new THREE.CubeGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  7093. geometry.name = geoID;
  7094. result.geometries[ geoID ] = geometry;
  7095. } else if ( geoJSON.type === "plane" ) {
  7096. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  7097. geometry.name = geoID;
  7098. result.geometries[ geoID ] = geometry;
  7099. } else if ( geoJSON.type === "sphere" ) {
  7100. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  7101. geometry.name = geoID;
  7102. result.geometries[ geoID ] = geometry;
  7103. } else if ( geoJSON.type === "cylinder" ) {
  7104. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  7105. geometry.name = geoID;
  7106. result.geometries[ geoID ] = geometry;
  7107. } else if ( geoJSON.type === "torus" ) {
  7108. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  7109. geometry.name = geoID;
  7110. result.geometries[ geoID ] = geometry;
  7111. } else if ( geoJSON.type === "icosahedron" ) {
  7112. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  7113. geometry.name = geoID;
  7114. result.geometries[ geoID ] = geometry;
  7115. } else if ( geoJSON.type in this.geometryHandlers ) {
  7116. var loaderParameters = {};
  7117. for ( var parType in geoJSON ) {
  7118. if ( parType !== "type" && parType !== "url" ) {
  7119. loaderParameters[ parType ] = geoJSON[ parType ];
  7120. }
  7121. }
  7122. var loader = this.geometryHandlers[ geoJSON.type ][ "loaderObject" ];
  7123. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  7124. } else if ( geoJSON.type === "embedded" ) {
  7125. var modelJson = data.embeds[ geoJSON.id ],
  7126. texture_path = "";
  7127. // pass metadata along to jsonLoader so it knows the format version
  7128. modelJson.metadata = data.metadata;
  7129. if ( modelJson ) {
  7130. var jsonLoader = this.geometryHandlers[ "ascii" ][ "loaderObject" ];
  7131. var model = jsonLoader.parse( modelJson, texture_path );
  7132. create_callback_embed( geoID )( model.geometry, model.materials );
  7133. }
  7134. }
  7135. }
  7136. // textures
  7137. // count how many textures will be loaded asynchronously
  7138. var textureID, textureJSON;
  7139. for ( textureID in data.textures ) {
  7140. textureJSON = data.textures[ textureID ];
  7141. if ( textureJSON.url instanceof Array ) {
  7142. counter_textures += textureJSON.url.length;
  7143. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  7144. scope.onLoadStart();
  7145. }
  7146. } else {
  7147. counter_textures += 1;
  7148. scope.onLoadStart();
  7149. }
  7150. }
  7151. total_textures = counter_textures;
  7152. for ( textureID in data.textures ) {
  7153. textureJSON = data.textures[ textureID ];
  7154. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  7155. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  7156. }
  7157. if ( textureJSON.url instanceof Array ) {
  7158. var count = textureJSON.url.length;
  7159. var url_array = [];
  7160. for( var i = 0; i < count; i ++ ) {
  7161. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  7162. }
  7163. var isCompressed = /\.dds$/i.test( url_array[ 0 ] );
  7164. if ( isCompressed ) {
  7165. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  7166. } else {
  7167. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  7168. }
  7169. } else {
  7170. var isCompressed = /\.dds$/i.test( textureJSON.url );
  7171. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  7172. var textureCallback = generateTextureCallback( 1 );
  7173. if ( isCompressed ) {
  7174. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  7175. } else {
  7176. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  7177. }
  7178. if ( THREE[ textureJSON.minFilter ] !== undefined )
  7179. texture.minFilter = THREE[ textureJSON.minFilter ];
  7180. if ( THREE[ textureJSON.magFilter ] !== undefined )
  7181. texture.magFilter = THREE[ textureJSON.magFilter ];
  7182. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  7183. if ( textureJSON.repeat ) {
  7184. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  7185. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  7186. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  7187. }
  7188. if ( textureJSON.offset ) {
  7189. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  7190. }
  7191. // handle wrap after repeat so that default repeat can be overriden
  7192. if ( textureJSON.wrap ) {
  7193. var wrapMap = {
  7194. "repeat": THREE.RepeatWrapping,
  7195. "mirror": THREE.MirroredRepeatWrapping
  7196. }
  7197. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  7198. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  7199. }
  7200. }
  7201. result.textures[ textureID ] = texture;
  7202. }
  7203. // materials
  7204. var matID, matJSON;
  7205. var parID;
  7206. for ( matID in data.materials ) {
  7207. matJSON = data.materials[ matID ];
  7208. for ( parID in matJSON.parameters ) {
  7209. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  7210. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  7211. } else if ( parID === "shading" ) {
  7212. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  7213. } else if ( parID === "side" ) {
  7214. if ( matJSON.parameters[ parID ] == "double" ) {
  7215. matJSON.parameters[ parID ] = THREE.DoubleSide;
  7216. } else if ( matJSON.parameters[ parID ] == "back" ) {
  7217. matJSON.parameters[ parID ] = THREE.BackSide;
  7218. } else {
  7219. matJSON.parameters[ parID ] = THREE.FrontSide;
  7220. }
  7221. } else if ( parID === "blending" ) {
  7222. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  7223. } else if ( parID === "combine" ) {
  7224. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  7225. } else if ( parID === "vertexColors" ) {
  7226. if ( matJSON.parameters[ parID ] == "face" ) {
  7227. matJSON.parameters[ parID ] = THREE.FaceColors;
  7228. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  7229. } else if ( matJSON.parameters[ parID ] ) {
  7230. matJSON.parameters[ parID ] = THREE.VertexColors;
  7231. }
  7232. } else if ( parID === "wrapRGB" ) {
  7233. var v3 = matJSON.parameters[ parID ];
  7234. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  7235. }
  7236. }
  7237. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  7238. matJSON.parameters.transparent = true;
  7239. }
  7240. if ( matJSON.parameters.normalMap ) {
  7241. var shader = THREE.ShaderLib[ "normalmap" ];
  7242. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  7243. var diffuse = matJSON.parameters.color;
  7244. var specular = matJSON.parameters.specular;
  7245. var ambient = matJSON.parameters.ambient;
  7246. var shininess = matJSON.parameters.shininess;
  7247. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  7248. if ( matJSON.parameters.normalScale ) {
  7249. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  7250. }
  7251. if ( matJSON.parameters.map ) {
  7252. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  7253. uniforms[ "enableDiffuse" ].value = true;
  7254. }
  7255. if ( matJSON.parameters.envMap ) {
  7256. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  7257. uniforms[ "enableReflection" ].value = true;
  7258. uniforms[ "uReflectivity" ].value = matJSON.parameters.reflectivity;
  7259. }
  7260. if ( matJSON.parameters.lightMap ) {
  7261. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  7262. uniforms[ "enableAO" ].value = true;
  7263. }
  7264. if ( matJSON.parameters.specularMap ) {
  7265. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  7266. uniforms[ "enableSpecular" ].value = true;
  7267. }
  7268. if ( matJSON.parameters.displacementMap ) {
  7269. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  7270. uniforms[ "enableDisplacement" ].value = true;
  7271. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  7272. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  7273. }
  7274. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  7275. uniforms[ "uSpecularColor" ].value.setHex( specular );
  7276. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  7277. uniforms[ "uShininess" ].value = shininess;
  7278. if ( matJSON.parameters.opacity ) {
  7279. uniforms[ "uOpacity" ].value = matJSON.parameters.opacity;
  7280. }
  7281. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  7282. material = new THREE.ShaderMaterial( parameters );
  7283. } else {
  7284. material = new THREE[ matJSON.type ]( matJSON.parameters );
  7285. }
  7286. material.name = matID;
  7287. result.materials[ matID ] = material;
  7288. }
  7289. // second pass through all materials to initialize MeshFaceMaterials
  7290. // that could be referring to other materials out of order
  7291. for ( matID in data.materials ) {
  7292. matJSON = data.materials[ matID ];
  7293. if ( matJSON.parameters.materials ) {
  7294. var materialArray = [];
  7295. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  7296. var label = matJSON.parameters.materials[ i ];
  7297. materialArray.push( result.materials[ label ] );
  7298. }
  7299. result.materials[ matID ].materials = materialArray;
  7300. }
  7301. }
  7302. // objects ( synchronous init of procedural primitives )
  7303. handle_objects();
  7304. // defaults
  7305. if ( result.cameras && data.defaults.camera ) {
  7306. result.currentCamera = result.cameras[ data.defaults.camera ];
  7307. }
  7308. if ( result.fogs && data.defaults.fog ) {
  7309. result.scene.fog = result.fogs[ data.defaults.fog ];
  7310. }
  7311. // synchronous callback
  7312. scope.callbackSync( result );
  7313. // just in case there are no async elements
  7314. async_callback_gate();
  7315. }
  7316. }
  7317. /**
  7318. * @author mrdoob / http://mrdoob.com/
  7319. */
  7320. THREE.TextureLoader = function ( manager ) {
  7321. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7322. };
  7323. THREE.TextureLoader.prototype = {
  7324. constructor: THREE.TextureLoader,
  7325. load: function ( url, onLoad, onProgress, onError ) {
  7326. var scope = this;
  7327. var loader = new THREE.ImageLoader( scope.manager );
  7328. loader.setCrossOrigin( this.crossOrigin );
  7329. loader.load( url, function ( image ) {
  7330. var texture = new THREE.Texture( image );
  7331. texture.needsUpdate = true;
  7332. if ( onLoad !== undefined ) {
  7333. onLoad( texture );
  7334. }
  7335. } );
  7336. },
  7337. setCrossOrigin: function ( value ) {
  7338. this.crossOrigin = value;
  7339. }
  7340. };
  7341. /**
  7342. * @author mrdoob / http://mrdoob.com/
  7343. * @author alteredq / http://alteredqualia.com/
  7344. */
  7345. THREE.Material = function () {
  7346. this.id = THREE.Math.generateUUID();
  7347. this.name = '';
  7348. this.side = THREE.FrontSide;
  7349. this.opacity = 1;
  7350. this.transparent = false;
  7351. this.blending = THREE.NormalBlending;
  7352. this.blendSrc = THREE.SrcAlphaFactor;
  7353. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  7354. this.blendEquation = THREE.AddEquation;
  7355. this.depthTest = true;
  7356. this.depthWrite = true;
  7357. this.polygonOffset = false;
  7358. this.polygonOffsetFactor = 0;
  7359. this.polygonOffsetUnits = 0;
  7360. this.alphaTest = 0;
  7361. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  7362. this.visible = true;
  7363. this.needsUpdate = true;
  7364. };
  7365. THREE.Material.prototype = {
  7366. constructor: THREE.Material,
  7367. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  7368. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  7369. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  7370. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  7371. setValues: function ( values ) {
  7372. if ( values === undefined ) return;
  7373. for ( var key in values ) {
  7374. var newValue = values[ key ];
  7375. if ( newValue === undefined ) {
  7376. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  7377. continue;
  7378. }
  7379. if ( key in this ) {
  7380. var currentValue = this[ key ];
  7381. if ( currentValue instanceof THREE.Color ) {
  7382. currentValue.set( newValue );
  7383. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  7384. currentValue.copy( newValue );
  7385. } else if ( key == 'overdraw') {
  7386. // ensure overdraw is backwards-compatable with legacy boolean type
  7387. this[ key ] = Number(newValue);
  7388. } else {
  7389. this[ key ] = newValue;
  7390. }
  7391. }
  7392. }
  7393. },
  7394. clone: function ( material ) {
  7395. if ( material === undefined ) material = new THREE.Material();
  7396. material.name = this.name;
  7397. material.side = this.side;
  7398. material.opacity = this.opacity;
  7399. material.transparent = this.transparent;
  7400. material.blending = this.blending;
  7401. material.blendSrc = this.blendSrc;
  7402. material.blendDst = this.blendDst;
  7403. material.blendEquation = this.blendEquation;
  7404. material.depthTest = this.depthTest;
  7405. material.depthWrite = this.depthWrite;
  7406. material.polygonOffset = this.polygonOffset;
  7407. material.polygonOffsetFactor = this.polygonOffsetFactor;
  7408. material.polygonOffsetUnits = this.polygonOffsetUnits;
  7409. material.alphaTest = this.alphaTest;
  7410. material.overdraw = this.overdraw;
  7411. material.visible = this.visible;
  7412. return material;
  7413. },
  7414. dispose: function () {
  7415. this.dispatchEvent( { type: 'dispose' } );
  7416. }
  7417. };
  7418. /**
  7419. * @author mrdoob / http://mrdoob.com/
  7420. * @author alteredq / http://alteredqualia.com/
  7421. *
  7422. * parameters = {
  7423. * color: <hex>,
  7424. * opacity: <float>,
  7425. *
  7426. * blending: THREE.NormalBlending,
  7427. * depthTest: <bool>,
  7428. * depthWrite: <bool>,
  7429. *
  7430. * linewidth: <float>,
  7431. * linecap: "round",
  7432. * linejoin: "round",
  7433. *
  7434. * vertexColors: <bool>
  7435. *
  7436. * fog: <bool>
  7437. * }
  7438. */
  7439. THREE.LineBasicMaterial = function ( parameters ) {
  7440. THREE.Material.call( this );
  7441. this.color = new THREE.Color( 0xffffff );
  7442. this.linewidth = 1;
  7443. this.linecap = 'round';
  7444. this.linejoin = 'round';
  7445. this.vertexColors = false;
  7446. this.fog = true;
  7447. this.setValues( parameters );
  7448. };
  7449. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7450. THREE.LineBasicMaterial.prototype.clone = function () {
  7451. var material = new THREE.LineBasicMaterial();
  7452. THREE.Material.prototype.clone.call( this, material );
  7453. material.color.copy( this.color );
  7454. material.linewidth = this.linewidth;
  7455. material.linecap = this.linecap;
  7456. material.linejoin = this.linejoin;
  7457. material.vertexColors = this.vertexColors;
  7458. material.fog = this.fog;
  7459. return material;
  7460. };
  7461. /**
  7462. * @author alteredq / http://alteredqualia.com/
  7463. *
  7464. * parameters = {
  7465. * color: <hex>,
  7466. * opacity: <float>,
  7467. *
  7468. * blending: THREE.NormalBlending,
  7469. * depthTest: <bool>,
  7470. * depthWrite: <bool>,
  7471. *
  7472. * linewidth: <float>,
  7473. *
  7474. * scale: <float>,
  7475. * dashSize: <float>,
  7476. * gapSize: <float>,
  7477. *
  7478. * vertexColors: <bool>
  7479. *
  7480. * fog: <bool>
  7481. * }
  7482. */
  7483. THREE.LineDashedMaterial = function ( parameters ) {
  7484. THREE.Material.call( this );
  7485. this.color = new THREE.Color( 0xffffff );
  7486. this.linewidth = 1;
  7487. this.scale = 1;
  7488. this.dashSize = 3;
  7489. this.gapSize = 1;
  7490. this.vertexColors = false;
  7491. this.fog = true;
  7492. this.setValues( parameters );
  7493. };
  7494. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  7495. THREE.LineDashedMaterial.prototype.clone = function () {
  7496. var material = new THREE.LineDashedMaterial();
  7497. THREE.Material.prototype.clone.call( this, material );
  7498. material.color.copy( this.color );
  7499. material.linewidth = this.linewidth;
  7500. material.scale = this.scale;
  7501. material.dashSize = this.dashSize;
  7502. material.gapSize = this.gapSize;
  7503. material.vertexColors = this.vertexColors;
  7504. material.fog = this.fog;
  7505. return material;
  7506. };
  7507. /**
  7508. * @author mrdoob / http://mrdoob.com/
  7509. * @author alteredq / http://alteredqualia.com/
  7510. *
  7511. * parameters = {
  7512. * color: <hex>,
  7513. * opacity: <float>,
  7514. * map: new THREE.Texture( <Image> ),
  7515. *
  7516. * lightMap: new THREE.Texture( <Image> ),
  7517. *
  7518. * specularMap: new THREE.Texture( <Image> ),
  7519. *
  7520. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7521. * combine: THREE.Multiply,
  7522. * reflectivity: <float>,
  7523. * refractionRatio: <float>,
  7524. *
  7525. * shading: THREE.SmoothShading,
  7526. * blending: THREE.NormalBlending,
  7527. * depthTest: <bool>,
  7528. * depthWrite: <bool>,
  7529. *
  7530. * wireframe: <boolean>,
  7531. * wireframeLinewidth: <float>,
  7532. *
  7533. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7534. *
  7535. * skinning: <bool>,
  7536. * morphTargets: <bool>,
  7537. *
  7538. * fog: <bool>
  7539. * }
  7540. */
  7541. THREE.MeshBasicMaterial = function ( parameters ) {
  7542. THREE.Material.call( this );
  7543. this.color = new THREE.Color( 0xffffff ); // emissive
  7544. this.map = null;
  7545. this.lightMap = null;
  7546. this.specularMap = null;
  7547. this.envMap = null;
  7548. this.combine = THREE.MultiplyOperation;
  7549. this.reflectivity = 1;
  7550. this.refractionRatio = 0.98;
  7551. this.fog = true;
  7552. this.shading = THREE.SmoothShading;
  7553. this.wireframe = false;
  7554. this.wireframeLinewidth = 1;
  7555. this.wireframeLinecap = 'round';
  7556. this.wireframeLinejoin = 'round';
  7557. this.vertexColors = THREE.NoColors;
  7558. this.skinning = false;
  7559. this.morphTargets = false;
  7560. this.setValues( parameters );
  7561. };
  7562. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7563. THREE.MeshBasicMaterial.prototype.clone = function () {
  7564. var material = new THREE.MeshBasicMaterial();
  7565. THREE.Material.prototype.clone.call( this, material );
  7566. material.color.copy( this.color );
  7567. material.map = this.map;
  7568. material.lightMap = this.lightMap;
  7569. material.specularMap = this.specularMap;
  7570. material.envMap = this.envMap;
  7571. material.combine = this.combine;
  7572. material.reflectivity = this.reflectivity;
  7573. material.refractionRatio = this.refractionRatio;
  7574. material.fog = this.fog;
  7575. material.shading = this.shading;
  7576. material.wireframe = this.wireframe;
  7577. material.wireframeLinewidth = this.wireframeLinewidth;
  7578. material.wireframeLinecap = this.wireframeLinecap;
  7579. material.wireframeLinejoin = this.wireframeLinejoin;
  7580. material.vertexColors = this.vertexColors;
  7581. material.skinning = this.skinning;
  7582. material.morphTargets = this.morphTargets;
  7583. return material;
  7584. };
  7585. /**
  7586. * @author mrdoob / http://mrdoob.com/
  7587. * @author alteredq / http://alteredqualia.com/
  7588. *
  7589. * parameters = {
  7590. * color: <hex>,
  7591. * ambient: <hex>,
  7592. * emissive: <hex>,
  7593. * opacity: <float>,
  7594. *
  7595. * map: new THREE.Texture( <Image> ),
  7596. *
  7597. * lightMap: new THREE.Texture( <Image> ),
  7598. *
  7599. * specularMap: new THREE.Texture( <Image> ),
  7600. *
  7601. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7602. * combine: THREE.Multiply,
  7603. * reflectivity: <float>,
  7604. * refractionRatio: <float>,
  7605. *
  7606. * shading: THREE.SmoothShading,
  7607. * blending: THREE.NormalBlending,
  7608. * depthTest: <bool>,
  7609. * depthWrite: <bool>,
  7610. *
  7611. * wireframe: <boolean>,
  7612. * wireframeLinewidth: <float>,
  7613. *
  7614. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7615. *
  7616. * skinning: <bool>,
  7617. * morphTargets: <bool>,
  7618. * morphNormals: <bool>,
  7619. *
  7620. * fog: <bool>
  7621. * }
  7622. */
  7623. THREE.MeshLambertMaterial = function ( parameters ) {
  7624. THREE.Material.call( this );
  7625. this.color = new THREE.Color( 0xffffff ); // diffuse
  7626. this.ambient = new THREE.Color( 0xffffff );
  7627. this.emissive = new THREE.Color( 0x000000 );
  7628. this.wrapAround = false;
  7629. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7630. this.map = null;
  7631. this.lightMap = null;
  7632. this.specularMap = null;
  7633. this.envMap = null;
  7634. this.combine = THREE.MultiplyOperation;
  7635. this.reflectivity = 1;
  7636. this.refractionRatio = 0.98;
  7637. this.fog = true;
  7638. this.shading = THREE.SmoothShading;
  7639. this.wireframe = false;
  7640. this.wireframeLinewidth = 1;
  7641. this.wireframeLinecap = 'round';
  7642. this.wireframeLinejoin = 'round';
  7643. this.vertexColors = THREE.NoColors;
  7644. this.skinning = false;
  7645. this.morphTargets = false;
  7646. this.morphNormals = false;
  7647. this.setValues( parameters );
  7648. };
  7649. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  7650. THREE.MeshLambertMaterial.prototype.clone = function () {
  7651. var material = new THREE.MeshLambertMaterial();
  7652. THREE.Material.prototype.clone.call( this, material );
  7653. material.color.copy( this.color );
  7654. material.ambient.copy( this.ambient );
  7655. material.emissive.copy( this.emissive );
  7656. material.wrapAround = this.wrapAround;
  7657. material.wrapRGB.copy( this.wrapRGB );
  7658. material.map = this.map;
  7659. material.lightMap = this.lightMap;
  7660. material.specularMap = this.specularMap;
  7661. material.envMap = this.envMap;
  7662. material.combine = this.combine;
  7663. material.reflectivity = this.reflectivity;
  7664. material.refractionRatio = this.refractionRatio;
  7665. material.fog = this.fog;
  7666. material.shading = this.shading;
  7667. material.wireframe = this.wireframe;
  7668. material.wireframeLinewidth = this.wireframeLinewidth;
  7669. material.wireframeLinecap = this.wireframeLinecap;
  7670. material.wireframeLinejoin = this.wireframeLinejoin;
  7671. material.vertexColors = this.vertexColors;
  7672. material.skinning = this.skinning;
  7673. material.morphTargets = this.morphTargets;
  7674. material.morphNormals = this.morphNormals;
  7675. return material;
  7676. };
  7677. /**
  7678. * @author mrdoob / http://mrdoob.com/
  7679. * @author alteredq / http://alteredqualia.com/
  7680. *
  7681. * parameters = {
  7682. * color: <hex>,
  7683. * ambient: <hex>,
  7684. * emissive: <hex>,
  7685. * specular: <hex>,
  7686. * shininess: <float>,
  7687. * opacity: <float>,
  7688. *
  7689. * map: new THREE.Texture( <Image> ),
  7690. *
  7691. * lightMap: new THREE.Texture( <Image> ),
  7692. *
  7693. * bumpMap: new THREE.Texture( <Image> ),
  7694. * bumpScale: <float>,
  7695. *
  7696. * normalMap: new THREE.Texture( <Image> ),
  7697. * normalScale: <Vector2>,
  7698. *
  7699. * specularMap: new THREE.Texture( <Image> ),
  7700. *
  7701. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7702. * combine: THREE.Multiply,
  7703. * reflectivity: <float>,
  7704. * refractionRatio: <float>,
  7705. *
  7706. * shading: THREE.SmoothShading,
  7707. * blending: THREE.NormalBlending,
  7708. * depthTest: <bool>,
  7709. * depthWrite: <bool>,
  7710. *
  7711. * wireframe: <boolean>,
  7712. * wireframeLinewidth: <float>,
  7713. *
  7714. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7715. *
  7716. * skinning: <bool>,
  7717. * morphTargets: <bool>,
  7718. * morphNormals: <bool>,
  7719. *
  7720. * fog: <bool>
  7721. * }
  7722. */
  7723. THREE.MeshPhongMaterial = function ( parameters ) {
  7724. THREE.Material.call( this );
  7725. this.color = new THREE.Color( 0xffffff ); // diffuse
  7726. this.ambient = new THREE.Color( 0xffffff );
  7727. this.emissive = new THREE.Color( 0x000000 );
  7728. this.specular = new THREE.Color( 0x111111 );
  7729. this.shininess = 30;
  7730. this.metal = false;
  7731. this.perPixel = true;
  7732. this.wrapAround = false;
  7733. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7734. this.map = null;
  7735. this.lightMap = null;
  7736. this.bumpMap = null;
  7737. this.bumpScale = 1;
  7738. this.normalMap = null;
  7739. this.normalScale = new THREE.Vector2( 1, 1 );
  7740. this.specularMap = null;
  7741. this.envMap = null;
  7742. this.combine = THREE.MultiplyOperation;
  7743. this.reflectivity = 1;
  7744. this.refractionRatio = 0.98;
  7745. this.fog = true;
  7746. this.shading = THREE.SmoothShading;
  7747. this.wireframe = false;
  7748. this.wireframeLinewidth = 1;
  7749. this.wireframeLinecap = 'round';
  7750. this.wireframeLinejoin = 'round';
  7751. this.vertexColors = THREE.NoColors;
  7752. this.skinning = false;
  7753. this.morphTargets = false;
  7754. this.morphNormals = false;
  7755. this.setValues( parameters );
  7756. };
  7757. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  7758. THREE.MeshPhongMaterial.prototype.clone = function () {
  7759. var material = new THREE.MeshPhongMaterial();
  7760. THREE.Material.prototype.clone.call( this, material );
  7761. material.color.copy( this.color );
  7762. material.ambient.copy( this.ambient );
  7763. material.emissive.copy( this.emissive );
  7764. material.specular.copy( this.specular );
  7765. material.shininess = this.shininess;
  7766. material.metal = this.metal;
  7767. material.perPixel = this.perPixel;
  7768. material.wrapAround = this.wrapAround;
  7769. material.wrapRGB.copy( this.wrapRGB );
  7770. material.map = this.map;
  7771. material.lightMap = this.lightMap;
  7772. material.bumpMap = this.bumpMap;
  7773. material.bumpScale = this.bumpScale;
  7774. material.normalMap = this.normalMap;
  7775. material.normalScale.copy( this.normalScale );
  7776. material.specularMap = this.specularMap;
  7777. material.envMap = this.envMap;
  7778. material.combine = this.combine;
  7779. material.reflectivity = this.reflectivity;
  7780. material.refractionRatio = this.refractionRatio;
  7781. material.fog = this.fog;
  7782. material.shading = this.shading;
  7783. material.wireframe = this.wireframe;
  7784. material.wireframeLinewidth = this.wireframeLinewidth;
  7785. material.wireframeLinecap = this.wireframeLinecap;
  7786. material.wireframeLinejoin = this.wireframeLinejoin;
  7787. material.vertexColors = this.vertexColors;
  7788. material.skinning = this.skinning;
  7789. material.morphTargets = this.morphTargets;
  7790. material.morphNormals = this.morphNormals;
  7791. return material;
  7792. };
  7793. /**
  7794. * @author mrdoob / http://mrdoob.com/
  7795. * @author alteredq / http://alteredqualia.com/
  7796. *
  7797. * parameters = {
  7798. * opacity: <float>,
  7799. *
  7800. * blending: THREE.NormalBlending,
  7801. * depthTest: <bool>,
  7802. * depthWrite: <bool>,
  7803. *
  7804. * wireframe: <boolean>,
  7805. * wireframeLinewidth: <float>
  7806. * }
  7807. */
  7808. THREE.MeshDepthMaterial = function ( parameters ) {
  7809. THREE.Material.call( this );
  7810. this.wireframe = false;
  7811. this.wireframeLinewidth = 1;
  7812. this.setValues( parameters );
  7813. };
  7814. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  7815. THREE.MeshDepthMaterial.prototype.clone = function () {
  7816. var material = new THREE.MeshDepthMaterial();
  7817. THREE.Material.prototype.clone.call( this, material );
  7818. material.wireframe = this.wireframe;
  7819. material.wireframeLinewidth = this.wireframeLinewidth;
  7820. return material;
  7821. };
  7822. /**
  7823. * @author mrdoob / http://mrdoob.com/
  7824. *
  7825. * parameters = {
  7826. * opacity: <float>,
  7827. *
  7828. * shading: THREE.FlatShading,
  7829. * blending: THREE.NormalBlending,
  7830. * depthTest: <bool>,
  7831. * depthWrite: <bool>,
  7832. *
  7833. * wireframe: <boolean>,
  7834. * wireframeLinewidth: <float>
  7835. * }
  7836. */
  7837. THREE.MeshNormalMaterial = function ( parameters ) {
  7838. THREE.Material.call( this, parameters );
  7839. this.shading = THREE.FlatShading;
  7840. this.wireframe = false;
  7841. this.wireframeLinewidth = 1;
  7842. this.morphTargets = false;
  7843. this.setValues( parameters );
  7844. };
  7845. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  7846. THREE.MeshNormalMaterial.prototype.clone = function () {
  7847. var material = new THREE.MeshNormalMaterial();
  7848. THREE.Material.prototype.clone.call( this, material );
  7849. material.shading = this.shading;
  7850. material.wireframe = this.wireframe;
  7851. material.wireframeLinewidth = this.wireframeLinewidth;
  7852. return material;
  7853. };
  7854. /**
  7855. * @author mrdoob / http://mrdoob.com/
  7856. */
  7857. THREE.MeshFaceMaterial = function ( materials ) {
  7858. this.materials = materials instanceof Array ? materials : [];
  7859. };
  7860. THREE.MeshFaceMaterial.prototype.clone = function () {
  7861. return new THREE.MeshFaceMaterial( this.materials.slice( 0 ) );
  7862. };
  7863. /**
  7864. * @author mrdoob / http://mrdoob.com/
  7865. * @author alteredq / http://alteredqualia.com/
  7866. *
  7867. * parameters = {
  7868. * color: <hex>,
  7869. * opacity: <float>,
  7870. * map: new THREE.Texture( <Image> ),
  7871. *
  7872. * size: <float>,
  7873. *
  7874. * blending: THREE.NormalBlending,
  7875. * depthTest: <bool>,
  7876. * depthWrite: <bool>,
  7877. *
  7878. * vertexColors: <bool>,
  7879. *
  7880. * fog: <bool>
  7881. * }
  7882. */
  7883. THREE.ParticleBasicMaterial = function ( parameters ) {
  7884. THREE.Material.call( this );
  7885. this.color = new THREE.Color( 0xffffff );
  7886. this.map = null;
  7887. this.size = 1;
  7888. this.sizeAttenuation = true;
  7889. this.vertexColors = false;
  7890. this.fog = true;
  7891. this.setValues( parameters );
  7892. };
  7893. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7894. THREE.ParticleBasicMaterial.prototype.clone = function () {
  7895. var material = new THREE.ParticleBasicMaterial();
  7896. THREE.Material.prototype.clone.call( this, material );
  7897. material.color.copy( this.color );
  7898. material.map = this.map;
  7899. material.size = this.size;
  7900. material.sizeAttenuation = this.sizeAttenuation;
  7901. material.vertexColors = this.vertexColors;
  7902. material.fog = this.fog;
  7903. return material;
  7904. };
  7905. /**
  7906. * @author mrdoob / http://mrdoob.com/
  7907. *
  7908. * parameters = {
  7909. * color: <hex>,
  7910. * program: <function>,
  7911. * opacity: <float>,
  7912. * blending: THREE.NormalBlending
  7913. * }
  7914. */
  7915. THREE.ParticleCanvasMaterial = function ( parameters ) {
  7916. THREE.Material.call( this );
  7917. this.color = new THREE.Color( 0xffffff );
  7918. this.program = function ( context, color ) {};
  7919. this.setValues( parameters );
  7920. };
  7921. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  7922. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  7923. var material = new THREE.ParticleCanvasMaterial();
  7924. THREE.Material.prototype.clone.call( this, material );
  7925. material.color.copy( this.color );
  7926. material.program = this.program;
  7927. return material;
  7928. };
  7929. /**
  7930. * @author alteredq / http://alteredqualia.com/
  7931. *
  7932. * parameters = {
  7933. * fragmentShader: <string>,
  7934. * vertexShader: <string>,
  7935. *
  7936. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  7937. *
  7938. * defines: { "label" : "value" },
  7939. *
  7940. * shading: THREE.SmoothShading,
  7941. * blending: THREE.NormalBlending,
  7942. * depthTest: <bool>,
  7943. * depthWrite: <bool>,
  7944. *
  7945. * wireframe: <boolean>,
  7946. * wireframeLinewidth: <float>,
  7947. *
  7948. * lights: <bool>,
  7949. *
  7950. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7951. *
  7952. * skinning: <bool>,
  7953. * morphTargets: <bool>,
  7954. * morphNormals: <bool>,
  7955. *
  7956. * fog: <bool>
  7957. * }
  7958. */
  7959. THREE.ShaderMaterial = function ( parameters ) {
  7960. THREE.Material.call( this );
  7961. this.fragmentShader = "void main() {}";
  7962. this.vertexShader = "void main() {}";
  7963. this.uniforms = {};
  7964. this.defines = {};
  7965. this.attributes = null;
  7966. this.shading = THREE.SmoothShading;
  7967. this.linewidth = 1;
  7968. this.wireframe = false;
  7969. this.wireframeLinewidth = 1;
  7970. this.fog = false; // set to use scene fog
  7971. this.lights = false; // set to use scene lights
  7972. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  7973. this.skinning = false; // set to use skinning attribute streams
  7974. this.morphTargets = false; // set to use morph targets
  7975. this.morphNormals = false; // set to use morph normals
  7976. this.setValues( parameters );
  7977. };
  7978. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  7979. THREE.ShaderMaterial.prototype.clone = function () {
  7980. var material = new THREE.ShaderMaterial();
  7981. THREE.Material.prototype.clone.call( this, material );
  7982. material.fragmentShader = this.fragmentShader;
  7983. material.vertexShader = this.vertexShader;
  7984. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  7985. material.attributes = this.attributes;
  7986. material.defines = this.defines;
  7987. material.shading = this.shading;
  7988. material.wireframe = this.wireframe;
  7989. material.wireframeLinewidth = this.wireframeLinewidth;
  7990. material.fog = this.fog;
  7991. material.lights = this.lights;
  7992. material.vertexColors = this.vertexColors;
  7993. material.skinning = this.skinning;
  7994. material.morphTargets = this.morphTargets;
  7995. material.morphNormals = this.morphNormals;
  7996. return material;
  7997. };
  7998. /**
  7999. * @author alteredq / http://alteredqualia.com/
  8000. *
  8001. * parameters = {
  8002. * color: <hex>,
  8003. * opacity: <float>,
  8004. * map: new THREE.Texture( <Image> ),
  8005. *
  8006. * blending: THREE.NormalBlending,
  8007. * depthTest: <bool>,
  8008. * depthWrite: <bool>,
  8009. *
  8010. * useScreenCoordinates: <bool>,
  8011. * sizeAttenuation: <bool>,
  8012. * scaleByViewport: <bool>,
  8013. * alignment: THREE.SpriteAlignment.center,
  8014. *
  8015. * uvOffset: new THREE.Vector2(),
  8016. * uvScale: new THREE.Vector2(),
  8017. *
  8018. * fog: <bool>
  8019. * }
  8020. */
  8021. THREE.SpriteMaterial = function ( parameters ) {
  8022. THREE.Material.call( this );
  8023. // defaults
  8024. this.color = new THREE.Color( 0xffffff );
  8025. this.map = new THREE.Texture();
  8026. this.useScreenCoordinates = true;
  8027. this.depthTest = !this.useScreenCoordinates;
  8028. this.sizeAttenuation = !this.useScreenCoordinates;
  8029. this.scaleByViewport = !this.sizeAttenuation;
  8030. this.alignment = THREE.SpriteAlignment.center.clone();
  8031. this.fog = false;
  8032. this.uvOffset = new THREE.Vector2( 0, 0 );
  8033. this.uvScale = new THREE.Vector2( 1, 1 );
  8034. // set parameters
  8035. this.setValues( parameters );
  8036. // override coupled defaults if not specified explicitly by parameters
  8037. parameters = parameters || {};
  8038. if ( parameters.depthTest === undefined ) this.depthTest = !this.useScreenCoordinates;
  8039. if ( parameters.sizeAttenuation === undefined ) this.sizeAttenuation = !this.useScreenCoordinates;
  8040. if ( parameters.scaleByViewport === undefined ) this.scaleByViewport = !this.sizeAttenuation;
  8041. };
  8042. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  8043. THREE.SpriteMaterial.prototype.clone = function () {
  8044. var material = new THREE.SpriteMaterial();
  8045. THREE.Material.prototype.clone.call( this, material );
  8046. material.color.copy( this.color );
  8047. material.map = this.map;
  8048. material.useScreenCoordinates = this.useScreenCoordinates;
  8049. material.sizeAttenuation = this.sizeAttenuation;
  8050. material.scaleByViewport = this.scaleByViewport;
  8051. material.alignment.copy( this.alignment );
  8052. material.uvOffset.copy( this.uvOffset );
  8053. material.uvScale.copy( this.uvScale );
  8054. material.fog = this.fog;
  8055. return material;
  8056. };
  8057. // Alignment enums
  8058. THREE.SpriteAlignment = {};
  8059. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  8060. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  8061. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  8062. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  8063. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  8064. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  8065. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  8066. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  8067. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  8068. /**
  8069. * @author mrdoob / http://mrdoob.com/
  8070. * @author alteredq / http://alteredqualia.com/
  8071. * @author szimek / https://github.com/szimek/
  8072. */
  8073. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8074. this.id = THREE.Math.generateUUID();
  8075. this.name = '';
  8076. this.image = image;
  8077. this.mipmaps = [];
  8078. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  8079. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  8080. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  8081. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  8082. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  8083. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  8084. this.format = format !== undefined ? format : THREE.RGBAFormat;
  8085. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  8086. this.offset = new THREE.Vector2( 0, 0 );
  8087. this.repeat = new THREE.Vector2( 1, 1 );
  8088. this.generateMipmaps = true;
  8089. this.premultiplyAlpha = false;
  8090. this.flipY = true;
  8091. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  8092. this.needsUpdate = false;
  8093. this.onUpdate = null;
  8094. };
  8095. THREE.Texture.prototype = {
  8096. constructor: THREE.Texture,
  8097. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  8098. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  8099. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  8100. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  8101. clone: function ( texture ) {
  8102. if ( texture === undefined ) texture = new THREE.Texture();
  8103. texture.image = this.image;
  8104. texture.mipmaps = this.mipmaps.slice(0);
  8105. texture.mapping = this.mapping;
  8106. texture.wrapS = this.wrapS;
  8107. texture.wrapT = this.wrapT;
  8108. texture.magFilter = this.magFilter;
  8109. texture.minFilter = this.minFilter;
  8110. texture.anisotropy = this.anisotropy;
  8111. texture.format = this.format;
  8112. texture.type = this.type;
  8113. texture.offset.copy( this.offset );
  8114. texture.repeat.copy( this.repeat );
  8115. texture.generateMipmaps = this.generateMipmaps;
  8116. texture.premultiplyAlpha = this.premultiplyAlpha;
  8117. texture.flipY = this.flipY;
  8118. texture.unpackAlignment = this.unpackAlignment;
  8119. return texture;
  8120. },
  8121. dispose: function () {
  8122. this.dispatchEvent( { type: 'dispose' } );
  8123. }
  8124. };
  8125. /**
  8126. * @author alteredq / http://alteredqualia.com/
  8127. */
  8128. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8129. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8130. this.image = { width: width, height: height };
  8131. this.mipmaps = mipmaps;
  8132. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  8133. };
  8134. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  8135. THREE.CompressedTexture.prototype.clone = function () {
  8136. var texture = new THREE.CompressedTexture();
  8137. THREE.Texture.prototype.clone.call( this, texture );
  8138. return texture;
  8139. };
  8140. /**
  8141. * @author alteredq / http://alteredqualia.com/
  8142. */
  8143. THREE.DataTexture = function ( data, 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 = { data: data, width: width, height: height };
  8146. };
  8147. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  8148. THREE.DataTexture.prototype.clone = function () {
  8149. var texture = new THREE.DataTexture();
  8150. THREE.Texture.prototype.clone.call( this, texture );
  8151. return texture;
  8152. };
  8153. /**
  8154. * @author mrdoob / http://mrdoob.com/
  8155. */
  8156. THREE.Particle = function ( material ) {
  8157. THREE.Object3D.call( this );
  8158. this.material = material;
  8159. };
  8160. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  8161. THREE.Particle.prototype.clone = function ( object ) {
  8162. if ( object === undefined ) object = new THREE.Particle( this.material );
  8163. THREE.Object3D.prototype.clone.call( this, object );
  8164. return object;
  8165. };
  8166. /**
  8167. * @author alteredq / http://alteredqualia.com/
  8168. */
  8169. THREE.ParticleSystem = function ( geometry, material ) {
  8170. THREE.Object3D.call( this );
  8171. this.geometry = geometry;
  8172. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  8173. this.sortParticles = false;
  8174. if ( this.geometry ) {
  8175. // calc bound radius
  8176. if( this.geometry.boundingSphere === null ) {
  8177. this.geometry.computeBoundingSphere();
  8178. }
  8179. }
  8180. this.frustumCulled = false;
  8181. };
  8182. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  8183. THREE.ParticleSystem.prototype.clone = function ( object ) {
  8184. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  8185. object.sortParticles = this.sortParticles;
  8186. THREE.Object3D.prototype.clone.call( this, object );
  8187. return object;
  8188. };
  8189. /**
  8190. * @author mrdoob / http://mrdoob.com/
  8191. */
  8192. THREE.Line = function ( geometry, material, type ) {
  8193. THREE.Object3D.call( this );
  8194. this.geometry = geometry;
  8195. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  8196. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  8197. if ( this.geometry ) {
  8198. if ( ! this.geometry.boundingSphere ) {
  8199. this.geometry.computeBoundingSphere();
  8200. }
  8201. }
  8202. };
  8203. THREE.LineStrip = 0;
  8204. THREE.LinePieces = 1;
  8205. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  8206. THREE.Line.prototype.clone = function ( object ) {
  8207. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  8208. THREE.Object3D.prototype.clone.call( this, object );
  8209. return object;
  8210. };
  8211. /**
  8212. * @author mrdoob / http://mrdoob.com/
  8213. * @author alteredq / http://alteredqualia.com/
  8214. * @author mikael emtinger / http://gomo.se/
  8215. * @author jonobr1 / http://jonobr1.com/
  8216. */
  8217. THREE.Mesh = function ( geometry, material ) {
  8218. THREE.Object3D.call( this );
  8219. this.geometry = null;
  8220. this.material = null;
  8221. this.setGeometry( geometry );
  8222. this.setMaterial( material );
  8223. };
  8224. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  8225. THREE.Mesh.prototype.setGeometry = function ( geometry ) {
  8226. if ( geometry !== undefined ) {
  8227. this.geometry = geometry;
  8228. if ( this.geometry.boundingSphere === null ) {
  8229. this.geometry.computeBoundingSphere();
  8230. }
  8231. this.updateMorphTargets();
  8232. }
  8233. };
  8234. THREE.Mesh.prototype.setMaterial = function ( material ) {
  8235. if ( material !== undefined ) {
  8236. this.material = material;
  8237. } else {
  8238. this.material = new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  8239. }
  8240. };
  8241. THREE.Mesh.prototype.updateMorphTargets = function () {
  8242. if ( this.geometry.morphTargets.length > 0 ) {
  8243. this.morphTargetBase = -1;
  8244. this.morphTargetForcedOrder = [];
  8245. this.morphTargetInfluences = [];
  8246. this.morphTargetDictionary = {};
  8247. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  8248. this.morphTargetInfluences.push( 0 );
  8249. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  8250. }
  8251. }
  8252. };
  8253. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  8254. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  8255. return this.morphTargetDictionary[ name ];
  8256. }
  8257. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  8258. return 0;
  8259. };
  8260. THREE.Mesh.prototype.clone = function ( object ) {
  8261. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  8262. THREE.Object3D.prototype.clone.call( this, object );
  8263. return object;
  8264. };
  8265. /**
  8266. * @author mikael emtinger / http://gomo.se/
  8267. * @author alteredq / http://alteredqualia.com/
  8268. */
  8269. THREE.Bone = function( belongsToSkin ) {
  8270. THREE.Object3D.call( this );
  8271. this.skin = belongsToSkin;
  8272. this.skinMatrix = new THREE.Matrix4();
  8273. };
  8274. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  8275. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  8276. // update local
  8277. if ( this.matrixAutoUpdate ) {
  8278. forceUpdate |= this.updateMatrix();
  8279. }
  8280. // update skin matrix
  8281. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  8282. if( parentSkinMatrix ) {
  8283. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  8284. } else {
  8285. this.skinMatrix.copy( this.matrix );
  8286. }
  8287. this.matrixWorldNeedsUpdate = false;
  8288. forceUpdate = true;
  8289. }
  8290. // update children
  8291. var child, i, l = this.children.length;
  8292. for ( i = 0; i < l; i ++ ) {
  8293. this.children[ i ].update( this.skinMatrix, forceUpdate );
  8294. }
  8295. };
  8296. /**
  8297. * @author mikael emtinger / http://gomo.se/
  8298. * @author alteredq / http://alteredqualia.com/
  8299. */
  8300. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  8301. THREE.Mesh.call( this, geometry, material );
  8302. //
  8303. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  8304. // init bones
  8305. this.identityMatrix = new THREE.Matrix4();
  8306. this.bones = [];
  8307. this.boneMatrices = [];
  8308. var b, bone, gbone, p, q, s;
  8309. if ( this.geometry && this.geometry.bones !== undefined ) {
  8310. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  8311. gbone = this.geometry.bones[ b ];
  8312. p = gbone.pos;
  8313. q = gbone.rotq;
  8314. s = gbone.scl;
  8315. bone = this.addBone();
  8316. bone.name = gbone.name;
  8317. bone.position.set( p[0], p[1], p[2] );
  8318. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  8319. if ( s !== undefined ) {
  8320. bone.scale.set( s[0], s[1], s[2] );
  8321. } else {
  8322. bone.scale.set( 1, 1, 1 );
  8323. }
  8324. }
  8325. for ( b = 0; b < this.bones.length; b ++ ) {
  8326. gbone = this.geometry.bones[ b ];
  8327. bone = this.bones[ b ];
  8328. if ( gbone.parent === -1 ) {
  8329. this.add( bone );
  8330. } else {
  8331. this.bones[ gbone.parent ].add( bone );
  8332. }
  8333. }
  8334. //
  8335. var nBones = this.bones.length;
  8336. if ( this.useVertexTexture ) {
  8337. // layout (1 matrix = 4 pixels)
  8338. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  8339. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  8340. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  8341. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  8342. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  8343. var size;
  8344. if ( nBones > 256 )
  8345. size = 64;
  8346. else if ( nBones > 64 )
  8347. size = 32;
  8348. else if ( nBones > 16 )
  8349. size = 16;
  8350. else
  8351. size = 8;
  8352. this.boneTextureWidth = size;
  8353. this.boneTextureHeight = size;
  8354. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  8355. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  8356. this.boneTexture.minFilter = THREE.NearestFilter;
  8357. this.boneTexture.magFilter = THREE.NearestFilter;
  8358. this.boneTexture.generateMipmaps = false;
  8359. this.boneTexture.flipY = false;
  8360. } else {
  8361. this.boneMatrices = new Float32Array( 16 * nBones );
  8362. }
  8363. this.pose();
  8364. }
  8365. };
  8366. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  8367. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  8368. if ( bone === undefined ) {
  8369. bone = new THREE.Bone( this );
  8370. }
  8371. this.bones.push( bone );
  8372. return bone;
  8373. };
  8374. THREE.SkinnedMesh.prototype.updateMatrixWorld = function () {
  8375. var offsetMatrix = new THREE.Matrix4();
  8376. return function ( force ) {
  8377. this.matrixAutoUpdate && this.updateMatrix();
  8378. // update matrixWorld
  8379. if ( this.matrixWorldNeedsUpdate || force ) {
  8380. if ( this.parent ) {
  8381. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  8382. } else {
  8383. this.matrixWorld.copy( this.matrix );
  8384. }
  8385. this.matrixWorldNeedsUpdate = false;
  8386. force = true;
  8387. }
  8388. // update children
  8389. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  8390. var child = this.children[ i ];
  8391. if ( child instanceof THREE.Bone ) {
  8392. child.update( this.identityMatrix, false );
  8393. } else {
  8394. child.updateMatrixWorld( true );
  8395. }
  8396. }
  8397. // make a snapshot of the bones' rest position
  8398. if ( this.boneInverses == undefined ) {
  8399. this.boneInverses = [];
  8400. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  8401. var inverse = new THREE.Matrix4();
  8402. inverse.getInverse( this.bones[ b ].skinMatrix );
  8403. this.boneInverses.push( inverse );
  8404. }
  8405. }
  8406. // flatten bone matrices to array
  8407. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  8408. // compute the offset between the current and the original transform;
  8409. // TODO: we could get rid of this multiplication step if the skinMatrix
  8410. // was already representing the offset; however, this requires some
  8411. // major changes to the animation system
  8412. offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  8413. offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  8414. }
  8415. if ( this.useVertexTexture ) {
  8416. this.boneTexture.needsUpdate = true;
  8417. }
  8418. };
  8419. }();
  8420. THREE.SkinnedMesh.prototype.pose = function () {
  8421. this.updateMatrixWorld( true );
  8422. this.normalizeSkinWeights();
  8423. };
  8424. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  8425. if ( this.geometry instanceof THREE.Geometry ) {
  8426. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  8427. var sw = this.geometry.skinWeights[ i ];
  8428. var scale = 1.0 / sw.lengthManhattan();
  8429. if ( scale !== Infinity ) {
  8430. sw.multiplyScalar( scale );
  8431. } else {
  8432. sw.set( 1 ); // this will be normalized by the shader anyway
  8433. }
  8434. }
  8435. } else {
  8436. // skinning weights assumed to be normalized for THREE.BufferGeometry
  8437. }
  8438. };
  8439. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  8440. if ( object === undefined ) {
  8441. object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  8442. }
  8443. THREE.Mesh.prototype.clone.call( this, object );
  8444. return object;
  8445. };
  8446. /**
  8447. * @author alteredq / http://alteredqualia.com/
  8448. */
  8449. THREE.MorphAnimMesh = function ( geometry, material ) {
  8450. THREE.Mesh.call( this, geometry, material );
  8451. // API
  8452. this.duration = 1000; // milliseconds
  8453. this.mirroredLoop = false;
  8454. this.time = 0;
  8455. // internals
  8456. this.lastKeyframe = 0;
  8457. this.currentKeyframe = 0;
  8458. this.direction = 1;
  8459. this.directionBackwards = false;
  8460. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  8461. };
  8462. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  8463. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  8464. this.startKeyframe = start;
  8465. this.endKeyframe = end;
  8466. this.length = this.endKeyframe - this.startKeyframe + 1;
  8467. };
  8468. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  8469. this.direction = 1;
  8470. this.directionBackwards = false;
  8471. };
  8472. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  8473. this.direction = -1;
  8474. this.directionBackwards = true;
  8475. };
  8476. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  8477. var geometry = this.geometry;
  8478. if ( ! geometry.animations ) geometry.animations = {};
  8479. var firstAnimation, animations = geometry.animations;
  8480. var pattern = /([a-z]+)(\d+)/;
  8481. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  8482. var morph = geometry.morphTargets[ i ];
  8483. var parts = morph.name.match( pattern );
  8484. if ( parts && parts.length > 1 ) {
  8485. var label = parts[ 1 ];
  8486. var num = parts[ 2 ];
  8487. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  8488. var animation = animations[ label ];
  8489. if ( i < animation.start ) animation.start = i;
  8490. if ( i > animation.end ) animation.end = i;
  8491. if ( ! firstAnimation ) firstAnimation = label;
  8492. }
  8493. }
  8494. geometry.firstAnimation = firstAnimation;
  8495. };
  8496. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  8497. if ( ! this.geometry.animations ) this.geometry.animations = {};
  8498. this.geometry.animations[ label ] = { start: start, end: end };
  8499. };
  8500. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  8501. var animation = this.geometry.animations[ label ];
  8502. if ( animation ) {
  8503. this.setFrameRange( animation.start, animation.end );
  8504. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  8505. this.time = 0;
  8506. } else {
  8507. console.warn( "animation[" + label + "] undefined" );
  8508. }
  8509. };
  8510. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  8511. var frameTime = this.duration / this.length;
  8512. this.time += this.direction * delta;
  8513. if ( this.mirroredLoop ) {
  8514. if ( this.time > this.duration || this.time < 0 ) {
  8515. this.direction *= -1;
  8516. if ( this.time > this.duration ) {
  8517. this.time = this.duration;
  8518. this.directionBackwards = true;
  8519. }
  8520. if ( this.time < 0 ) {
  8521. this.time = 0;
  8522. this.directionBackwards = false;
  8523. }
  8524. }
  8525. } else {
  8526. this.time = this.time % this.duration;
  8527. if ( this.time < 0 ) this.time += this.duration;
  8528. }
  8529. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  8530. if ( keyframe !== this.currentKeyframe ) {
  8531. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  8532. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  8533. this.morphTargetInfluences[ keyframe ] = 0;
  8534. this.lastKeyframe = this.currentKeyframe;
  8535. this.currentKeyframe = keyframe;
  8536. }
  8537. var mix = ( this.time % frameTime ) / frameTime;
  8538. if ( this.directionBackwards ) {
  8539. mix = 1 - mix;
  8540. }
  8541. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  8542. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  8543. };
  8544. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  8545. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  8546. object.duration = this.duration;
  8547. object.mirroredLoop = this.mirroredLoop;
  8548. object.time = this.time;
  8549. object.lastKeyframe = this.lastKeyframe;
  8550. object.currentKeyframe = this.currentKeyframe;
  8551. object.direction = this.direction;
  8552. object.directionBackwards = this.directionBackwards;
  8553. THREE.Mesh.prototype.clone.call( this, object );
  8554. return object;
  8555. };
  8556. /**
  8557. * @author alteredq / http://alteredqualia.com/
  8558. */
  8559. THREE.Ribbon = function ( geometry, material ) {
  8560. THREE.Object3D.call( this );
  8561. this.geometry = geometry;
  8562. this.material = material;
  8563. };
  8564. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  8565. THREE.Ribbon.prototype.clone = function ( object ) {
  8566. if ( object === undefined ) object = new THREE.Ribbon( this.geometry, this.material );
  8567. THREE.Object3D.prototype.clone.call( this, object );
  8568. return object;
  8569. };
  8570. /**
  8571. * @author mikael emtinger / http://gomo.se/
  8572. * @author alteredq / http://alteredqualia.com/
  8573. * @author mrdoob / http://mrdoob.com/
  8574. */
  8575. THREE.LOD = function () {
  8576. THREE.Object3D.call( this );
  8577. this.objects = [];
  8578. };
  8579. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  8580. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  8581. if ( distance === undefined ) distance = 0;
  8582. distance = Math.abs( distance );
  8583. for ( var l = 0; l < this.objects.length; l ++ ) {
  8584. if ( distance < this.objects[ l ].distance ) {
  8585. break;
  8586. }
  8587. }
  8588. this.objects.splice( l, 0, { distance: distance, object: object } );
  8589. this.add( object );
  8590. };
  8591. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  8592. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  8593. if ( distance < this.objects[ i ].distance ) {
  8594. break;
  8595. }
  8596. }
  8597. return this.objects[ i - 1 ].object;
  8598. };
  8599. THREE.LOD.prototype.update = function () {
  8600. var v1 = new THREE.Vector3();
  8601. var v2 = new THREE.Vector3();
  8602. return function ( camera ) {
  8603. if ( this.objects.length > 1 ) {
  8604. v1.getPositionFromMatrix( camera.matrixWorld );
  8605. v2.getPositionFromMatrix( this.matrixWorld );
  8606. var distance = v1.distanceTo( v2 );
  8607. this.objects[ 0 ].object.visible = true;
  8608. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  8609. if ( distance >= this.objects[ i ].distance ) {
  8610. this.objects[ i - 1 ].object.visible = false;
  8611. this.objects[ i ].object.visible = true;
  8612. } else {
  8613. break;
  8614. }
  8615. }
  8616. for( ; i < l; i ++ ) {
  8617. this.objects[ i ].object.visible = false;
  8618. }
  8619. }
  8620. };
  8621. }();
  8622. THREE.LOD.prototype.clone = function () {
  8623. // TODO
  8624. };
  8625. /**
  8626. * @author mikael emtinger / http://gomo.se/
  8627. * @author alteredq / http://alteredqualia.com/
  8628. */
  8629. THREE.Sprite = function ( material ) {
  8630. THREE.Object3D.call( this );
  8631. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  8632. this.rotation3d = this.rotation;
  8633. this.rotation = 0;
  8634. };
  8635. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  8636. /*
  8637. * Custom update matrix
  8638. */
  8639. THREE.Sprite.prototype.updateMatrix = function () {
  8640. this.rotation3d.set( 0, 0, this.rotation, this.rotation3d.order );
  8641. this.quaternion.setFromEuler( this.rotation3d );
  8642. this.matrix.compose( this.position, this.quaternion, this.scale );
  8643. this.matrixWorldNeedsUpdate = true;
  8644. };
  8645. THREE.Sprite.prototype.clone = function ( object ) {
  8646. if ( object === undefined ) object = new THREE.Sprite( this.material );
  8647. THREE.Object3D.prototype.clone.call( this, object );
  8648. return object;
  8649. };
  8650. /**
  8651. * @author mrdoob / http://mrdoob.com/
  8652. */
  8653. THREE.Scene = function () {
  8654. THREE.Object3D.call( this );
  8655. this.fog = null;
  8656. this.overrideMaterial = null;
  8657. this.autoUpdate = true; // checked by the renderer
  8658. this.matrixAutoUpdate = false;
  8659. this.__objects = [];
  8660. this.__lights = [];
  8661. this.__objectsAdded = [];
  8662. this.__objectsRemoved = [];
  8663. };
  8664. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  8665. THREE.Scene.prototype.__addObject = function ( object ) {
  8666. if ( object instanceof THREE.Light ) {
  8667. if ( this.__lights.indexOf( object ) === - 1 ) {
  8668. this.__lights.push( object );
  8669. }
  8670. if ( object.target && object.target.parent === undefined ) {
  8671. this.add( object.target );
  8672. }
  8673. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  8674. if ( this.__objects.indexOf( object ) === - 1 ) {
  8675. this.__objects.push( object );
  8676. this.__objectsAdded.push( object );
  8677. // check if previously removed
  8678. var i = this.__objectsRemoved.indexOf( object );
  8679. if ( i !== -1 ) {
  8680. this.__objectsRemoved.splice( i, 1 );
  8681. }
  8682. }
  8683. }
  8684. for ( var c = 0; c < object.children.length; c ++ ) {
  8685. this.__addObject( object.children[ c ] );
  8686. }
  8687. };
  8688. THREE.Scene.prototype.__removeObject = function ( object ) {
  8689. if ( object instanceof THREE.Light ) {
  8690. var i = this.__lights.indexOf( object );
  8691. if ( i !== -1 ) {
  8692. this.__lights.splice( i, 1 );
  8693. }
  8694. } else if ( !( object instanceof THREE.Camera ) ) {
  8695. var i = this.__objects.indexOf( object );
  8696. if( i !== -1 ) {
  8697. this.__objects.splice( i, 1 );
  8698. this.__objectsRemoved.push( object );
  8699. // check if previously added
  8700. var ai = this.__objectsAdded.indexOf( object );
  8701. if ( ai !== -1 ) {
  8702. this.__objectsAdded.splice( ai, 1 );
  8703. }
  8704. }
  8705. }
  8706. for ( var c = 0; c < object.children.length; c ++ ) {
  8707. this.__removeObject( object.children[ c ] );
  8708. }
  8709. };
  8710. THREE.Scene.prototype.clone = function ( object ) {
  8711. if ( object === undefined ) object = new THREE.Scene();
  8712. THREE.Object3D.prototype.clone.call(this, object);
  8713. if ( this.fog !== null ) object.fog = this.fog.clone();
  8714. if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone();
  8715. object.autoUpdate = this.autoUpdate;
  8716. object.matrixAutoUpdate = this.matrixAutoUpdate;
  8717. return object;
  8718. };
  8719. /**
  8720. * @author mrdoob / http://mrdoob.com/
  8721. * @author alteredq / http://alteredqualia.com/
  8722. */
  8723. THREE.Fog = function ( hex, near, far ) {
  8724. this.name = '';
  8725. this.color = new THREE.Color( hex );
  8726. this.near = ( near !== undefined ) ? near : 1;
  8727. this.far = ( far !== undefined ) ? far : 1000;
  8728. };
  8729. THREE.Fog.prototype.clone = function () {
  8730. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  8731. };
  8732. /**
  8733. * @author mrdoob / http://mrdoob.com/
  8734. * @author alteredq / http://alteredqualia.com/
  8735. */
  8736. THREE.FogExp2 = function ( hex, density ) {
  8737. this.name = '';
  8738. this.color = new THREE.Color( hex );
  8739. this.density = ( density !== undefined ) ? density : 0.00025;
  8740. };
  8741. THREE.FogExp2.prototype.clone = function () {
  8742. return new THREE.FogExp2( this.color.getHex(), this.density );
  8743. };
  8744. /**
  8745. * @author mrdoob / http://mrdoob.com/
  8746. */
  8747. THREE.CanvasRenderer = function ( parameters ) {
  8748. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  8749. var smoothstep = THREE.Math.smoothstep;
  8750. parameters = parameters || {};
  8751. var _this = this,
  8752. _renderData, _elements, _lights,
  8753. _projector = new THREE.Projector(),
  8754. _canvas = parameters.canvas !== undefined
  8755. ? parameters.canvas
  8756. : document.createElement( 'canvas' ),
  8757. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  8758. _context = _canvas.getContext( '2d' ),
  8759. _clearColor = new THREE.Color( 0x000000 ),
  8760. _clearAlpha = 0,
  8761. _contextGlobalAlpha = 1,
  8762. _contextGlobalCompositeOperation = 0,
  8763. _contextStrokeStyle = null,
  8764. _contextFillStyle = null,
  8765. _contextLineWidth = null,
  8766. _contextLineCap = null,
  8767. _contextLineJoin = null,
  8768. _contextDashSize = null,
  8769. _contextGapSize = 0,
  8770. _camera,
  8771. _v1, _v2, _v3, _v4,
  8772. _v5 = new THREE.RenderableVertex(),
  8773. _v6 = new THREE.RenderableVertex(),
  8774. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  8775. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  8776. _color = new THREE.Color(),
  8777. _color1 = new THREE.Color(),
  8778. _color2 = new THREE.Color(),
  8779. _color3 = new THREE.Color(),
  8780. _color4 = new THREE.Color(),
  8781. _diffuseColor = new THREE.Color(),
  8782. _emissiveColor = new THREE.Color(),
  8783. _lightColor = new THREE.Color(),
  8784. _patterns = {}, _imagedatas = {},
  8785. _near, _far,
  8786. _image, _uvs,
  8787. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  8788. _clipBox = new THREE.Box2(),
  8789. _clearBox = new THREE.Box2(),
  8790. _elemBox = new THREE.Box2(),
  8791. _ambientLight = new THREE.Color(),
  8792. _directionalLights = new THREE.Color(),
  8793. _pointLights = new THREE.Color(),
  8794. _vector3 = new THREE.Vector3(), // Needed for PointLight
  8795. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  8796. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  8797. _pixelMap = document.createElement( 'canvas' );
  8798. _pixelMap.width = _pixelMap.height = 2;
  8799. _pixelMapContext = _pixelMap.getContext( '2d' );
  8800. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  8801. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  8802. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  8803. _pixelMapData = _pixelMapImage.data;
  8804. _gradientMap = document.createElement( 'canvas' );
  8805. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  8806. _gradientMapContext = _gradientMap.getContext( '2d' );
  8807. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  8808. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  8809. _gradientMapQuality --; // Fix UVs
  8810. // dash+gap fallbacks for Firefox and everything else
  8811. if ( _context.setLineDash === undefined ) {
  8812. if ( _context.mozDash !== undefined ) {
  8813. _context.setLineDash = function ( values ) {
  8814. _context.mozDash = values[ 0 ] !== null ? values : null;
  8815. }
  8816. } else {
  8817. _context.setLineDash = function () {}
  8818. }
  8819. }
  8820. this.domElement = _canvas;
  8821. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  8822. ? parameters.devicePixelRatio
  8823. : window.devicePixelRatio !== undefined
  8824. ? window.devicePixelRatio
  8825. : 1;
  8826. this.autoClear = true;
  8827. this.sortObjects = true;
  8828. this.sortElements = true;
  8829. this.info = {
  8830. render: {
  8831. vertices: 0,
  8832. faces: 0
  8833. }
  8834. }
  8835. // WebGLRenderer compatibility
  8836. this.supportsVertexTextures = function () {};
  8837. this.setFaceCulling = function () {};
  8838. this.setSize = function ( width, height, updateStyle ) {
  8839. _canvasWidth = width * this.devicePixelRatio;
  8840. _canvasHeight = height * this.devicePixelRatio;
  8841. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  8842. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  8843. _canvas.width = _canvasWidth;
  8844. _canvas.height = _canvasHeight;
  8845. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  8846. _canvas.style.width = width + 'px';
  8847. _canvas.style.height = height + 'px';
  8848. }
  8849. _clipBox.set(
  8850. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8851. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8852. );
  8853. _clearBox.set(
  8854. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8855. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8856. );
  8857. _contextGlobalAlpha = 1;
  8858. _contextGlobalCompositeOperation = 0;
  8859. _contextStrokeStyle = null;
  8860. _contextFillStyle = null;
  8861. _contextLineWidth = null;
  8862. _contextLineCap = null;
  8863. _contextLineJoin = null;
  8864. };
  8865. this.setClearColor = function ( color, alpha ) {
  8866. _clearColor.set( color );
  8867. _clearAlpha = alpha !== undefined ? alpha : 1;
  8868. _clearBox.set(
  8869. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8870. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8871. );
  8872. };
  8873. this.setClearColorHex = function ( hex, alpha ) {
  8874. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  8875. this.setClearColor( hex, alpha );
  8876. };
  8877. this.getMaxAnisotropy = function () {
  8878. return 0;
  8879. };
  8880. this.clear = function () {
  8881. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8882. if ( _clearBox.empty() === false ) {
  8883. _clearBox.intersect( _clipBox );
  8884. _clearBox.expandByScalar( 2 );
  8885. if ( _clearAlpha < 1 ) {
  8886. _context.clearRect(
  8887. _clearBox.min.x | 0,
  8888. _clearBox.min.y | 0,
  8889. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  8890. ( _clearBox.max.y - _clearBox.min.y ) | 0
  8891. );
  8892. }
  8893. if ( _clearAlpha > 0 ) {
  8894. setBlending( THREE.NormalBlending );
  8895. setOpacity( 1 );
  8896. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearAlpha + ')' );
  8897. _context.fillRect(
  8898. _clearBox.min.x | 0,
  8899. _clearBox.min.y | 0,
  8900. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  8901. ( _clearBox.max.y - _clearBox.min.y ) | 0
  8902. );
  8903. }
  8904. _clearBox.makeEmpty();
  8905. }
  8906. };
  8907. this.render = function ( scene, camera ) {
  8908. if ( camera instanceof THREE.Camera === false ) {
  8909. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  8910. return;
  8911. }
  8912. if ( this.autoClear === true ) this.clear();
  8913. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8914. _this.info.render.vertices = 0;
  8915. _this.info.render.faces = 0;
  8916. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  8917. _elements = _renderData.elements;
  8918. _lights = _renderData.lights;
  8919. _camera = camera;
  8920. /* DEBUG
  8921. setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
  8922. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  8923. */
  8924. calculateLights();
  8925. for ( var e = 0, el = _elements.length; e < el; e++ ) {
  8926. var element = _elements[ e ];
  8927. var material = element.material;
  8928. if ( material === undefined || material.visible === false ) continue;
  8929. _elemBox.makeEmpty();
  8930. if ( element instanceof THREE.RenderableParticle ) {
  8931. _v1 = element;
  8932. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  8933. renderParticle( _v1, element, material );
  8934. } else if ( element instanceof THREE.RenderableLine ) {
  8935. _v1 = element.v1; _v2 = element.v2;
  8936. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8937. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8938. _elemBox.setFromPoints( [
  8939. _v1.positionScreen,
  8940. _v2.positionScreen
  8941. ] );
  8942. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8943. renderLine( _v1, _v2, element, material );
  8944. }
  8945. } else if ( element instanceof THREE.RenderableFace3 ) {
  8946. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  8947. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  8948. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  8949. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  8950. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8951. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8952. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8953. if ( material.overdraw > 0 ) {
  8954. expand( _v1.positionScreen, _v2.positionScreen, material.overdraw );
  8955. expand( _v2.positionScreen, _v3.positionScreen, material.overdraw );
  8956. expand( _v3.positionScreen, _v1.positionScreen, material.overdraw );
  8957. }
  8958. _elemBox.setFromPoints( [
  8959. _v1.positionScreen,
  8960. _v2.positionScreen,
  8961. _v3.positionScreen
  8962. ] );
  8963. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8964. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material );
  8965. }
  8966. } else if ( element instanceof THREE.RenderableFace4 ) {
  8967. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  8968. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  8969. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  8970. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  8971. if ( _v4.positionScreen.z < -1 || _v4.positionScreen.z > 1 ) continue;
  8972. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8973. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8974. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8975. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  8976. _v5.positionScreen.copy( _v2.positionScreen );
  8977. _v6.positionScreen.copy( _v4.positionScreen );
  8978. if ( material.overdraw > 0 ) {
  8979. expand( _v1.positionScreen, _v2.positionScreen, material.overdraw );
  8980. expand( _v2.positionScreen, _v4.positionScreen, material.overdraw );
  8981. expand( _v4.positionScreen, _v1.positionScreen, material.overdraw );
  8982. expand( _v3.positionScreen, _v5.positionScreen, material.overdraw );
  8983. expand( _v3.positionScreen, _v6.positionScreen, material.overdraw );
  8984. }
  8985. _elemBox.setFromPoints( [
  8986. _v1.positionScreen,
  8987. _v2.positionScreen,
  8988. _v3.positionScreen,
  8989. _v4.positionScreen
  8990. ] );
  8991. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8992. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material );
  8993. }
  8994. }
  8995. /* DEBUG
  8996. setLineWidth( 1 );
  8997. setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
  8998. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  8999. */
  9000. _clearBox.union( _elemBox );
  9001. }
  9002. /* DEBUG
  9003. setLineWidth( 1 );
  9004. setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
  9005. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  9006. */
  9007. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  9008. };
  9009. //
  9010. function calculateLights() {
  9011. _ambientLight.setRGB( 0, 0, 0 );
  9012. _directionalLights.setRGB( 0, 0, 0 );
  9013. _pointLights.setRGB( 0, 0, 0 );
  9014. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9015. var light = _lights[ l ];
  9016. var lightColor = light.color;
  9017. if ( light instanceof THREE.AmbientLight ) {
  9018. _ambientLight.add( lightColor );
  9019. } else if ( light instanceof THREE.DirectionalLight ) {
  9020. // for particles
  9021. _directionalLights.add( lightColor );
  9022. } else if ( light instanceof THREE.PointLight ) {
  9023. // for particles
  9024. _pointLights.add( lightColor );
  9025. }
  9026. }
  9027. }
  9028. function calculateLight( position, normal, color ) {
  9029. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9030. var light = _lights[ l ];
  9031. _lightColor.copy( light.color );
  9032. if ( light instanceof THREE.DirectionalLight ) {
  9033. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld ).normalize();
  9034. var amount = normal.dot( lightPosition );
  9035. if ( amount <= 0 ) continue;
  9036. amount *= light.intensity;
  9037. color.add( _lightColor.multiplyScalar( amount ) );
  9038. } else if ( light instanceof THREE.PointLight ) {
  9039. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld );
  9040. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  9041. if ( amount <= 0 ) continue;
  9042. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  9043. if ( amount == 0 ) continue;
  9044. amount *= light.intensity;
  9045. color.add( _lightColor.multiplyScalar( amount ) );
  9046. }
  9047. }
  9048. }
  9049. function renderParticle( v1, element, material ) {
  9050. setOpacity( material.opacity );
  9051. setBlending( material.blending );
  9052. var width, height, scaleX, scaleY,
  9053. bitmap, bitmapWidth, bitmapHeight;
  9054. if ( material instanceof THREE.ParticleBasicMaterial ) {
  9055. if ( material.map === null ) {
  9056. scaleX = element.object.scale.x;
  9057. scaleY = element.object.scale.y;
  9058. // TODO: Be able to disable this
  9059. scaleX *= element.scale.x * _canvasWidthHalf;
  9060. scaleY *= element.scale.y * _canvasHeightHalf;
  9061. _elemBox.min.set( v1.x - scaleX, v1.y - scaleY );
  9062. _elemBox.max.set( v1.x + scaleX, v1.y + scaleY );
  9063. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  9064. _elemBox.makeEmpty();
  9065. return;
  9066. }
  9067. setFillStyle( material.color.getStyle() );
  9068. _context.save();
  9069. _context.translate( v1.x, v1.y );
  9070. _context.rotate( - element.rotation );
  9071. _context.scale( scaleX, scaleY );
  9072. _context.fillRect( -1, -1, 2, 2 );
  9073. _context.restore();
  9074. } else {
  9075. bitmap = material.map.image;
  9076. bitmapWidth = bitmap.width >> 1;
  9077. bitmapHeight = bitmap.height >> 1;
  9078. scaleX = element.scale.x * _canvasWidthHalf;
  9079. scaleY = element.scale.y * _canvasHeightHalf;
  9080. width = scaleX * bitmapWidth;
  9081. height = scaleY * bitmapHeight;
  9082. // TODO: Rotations break this...
  9083. _elemBox.min.set( v1.x - width, v1.y - height );
  9084. _elemBox.max.set( v1.x + width, v1.y + height );
  9085. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  9086. _elemBox.makeEmpty();
  9087. return;
  9088. }
  9089. _context.save();
  9090. _context.translate( v1.x, v1.y );
  9091. _context.rotate( - element.rotation );
  9092. _context.scale( scaleX, - scaleY );
  9093. _context.translate( - bitmapWidth, - bitmapHeight );
  9094. _context.drawImage( bitmap, 0, 0 );
  9095. _context.restore();
  9096. }
  9097. /* DEBUG
  9098. setStrokeStyle( 'rgb(255,255,0)' );
  9099. _context.beginPath();
  9100. _context.moveTo( v1.x - 10, v1.y );
  9101. _context.lineTo( v1.x + 10, v1.y );
  9102. _context.moveTo( v1.x, v1.y - 10 );
  9103. _context.lineTo( v1.x, v1.y + 10 );
  9104. _context.stroke();
  9105. */
  9106. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  9107. width = element.scale.x * _canvasWidthHalf;
  9108. height = element.scale.y * _canvasHeightHalf;
  9109. _elemBox.min.set( v1.x - width, v1.y - height );
  9110. _elemBox.max.set( v1.x + width, v1.y + height );
  9111. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  9112. _elemBox.makeEmpty();
  9113. return;
  9114. }
  9115. setStrokeStyle( material.color.getStyle() );
  9116. setFillStyle( material.color.getStyle() );
  9117. _context.save();
  9118. _context.translate( v1.x, v1.y );
  9119. _context.rotate( - element.rotation );
  9120. _context.scale( width, height );
  9121. material.program( _context );
  9122. _context.restore();
  9123. }
  9124. }
  9125. function renderLine( v1, v2, element, material ) {
  9126. setOpacity( material.opacity );
  9127. setBlending( material.blending );
  9128. _context.beginPath();
  9129. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  9130. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  9131. if ( material instanceof THREE.LineBasicMaterial ) {
  9132. setLineWidth( material.linewidth );
  9133. setLineCap( material.linecap );
  9134. setLineJoin( material.linejoin );
  9135. if ( material.vertexColors !== THREE.VertexColors ) {
  9136. setStrokeStyle( material.color.getStyle() );
  9137. } else {
  9138. var colorStyle1 = element.vertexColors[0].getStyle();
  9139. var colorStyle2 = element.vertexColors[1].getStyle();
  9140. if ( colorStyle1 === colorStyle2 ) {
  9141. setStrokeStyle( colorStyle1 );
  9142. } else {
  9143. try {
  9144. var grad = _context.createLinearGradient(
  9145. v1.positionScreen.x,
  9146. v1.positionScreen.y,
  9147. v2.positionScreen.x,
  9148. v2.positionScreen.y
  9149. );
  9150. grad.addColorStop( 0, colorStyle1 );
  9151. grad.addColorStop( 1, colorStyle2 );
  9152. } catch ( exception ) {
  9153. grad = colorStyle1;
  9154. }
  9155. setStrokeStyle( grad );
  9156. }
  9157. }
  9158. _context.stroke();
  9159. _elemBox.expandByScalar( material.linewidth * 2 );
  9160. } else if ( material instanceof THREE.LineDashedMaterial ) {
  9161. setLineWidth( material.linewidth );
  9162. setLineCap( material.linecap );
  9163. setLineJoin( material.linejoin );
  9164. setStrokeStyle( material.color.getStyle() );
  9165. setDashAndGap( material.dashSize, material.gapSize );
  9166. _context.stroke();
  9167. _elemBox.expandByScalar( material.linewidth * 2 );
  9168. setDashAndGap( null, null );
  9169. }
  9170. }
  9171. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material ) {
  9172. _this.info.render.vertices += 3;
  9173. _this.info.render.faces ++;
  9174. setOpacity( material.opacity );
  9175. setBlending( material.blending );
  9176. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  9177. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  9178. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  9179. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  9180. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) {
  9181. _diffuseColor.copy( material.color );
  9182. _emissiveColor.copy( material.emissive );
  9183. if ( material.vertexColors === THREE.FaceColors ) {
  9184. _diffuseColor.multiply( element.color );
  9185. }
  9186. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  9187. _color1.copy( _ambientLight );
  9188. _color2.copy( _ambientLight );
  9189. _color3.copy( _ambientLight );
  9190. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  9191. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  9192. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color3 );
  9193. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  9194. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  9195. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  9196. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9197. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9198. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9199. } else {
  9200. _color.copy( _ambientLight );
  9201. calculateLight( element.centroidModel, element.normalModel, _color );
  9202. _color.multiply( _diffuseColor ).add( _emissiveColor );
  9203. material.wireframe === true
  9204. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9205. : fillPath( _color );
  9206. }
  9207. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  9208. if ( material.map !== null ) {
  9209. if ( material.map.mapping instanceof THREE.UVMapping ) {
  9210. _uvs = element.uvs[ 0 ];
  9211. 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 );
  9212. }
  9213. } else if ( material.envMap !== null ) {
  9214. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  9215. _vector3.copy( element.vertexNormalsModelView[ uv1 ] );
  9216. _uv1x = 0.5 * _vector3.x + 0.5;
  9217. _uv1y = 0.5 * _vector3.y + 0.5;
  9218. _vector3.copy( element.vertexNormalsModelView[ uv2 ] );
  9219. _uv2x = 0.5 * _vector3.x + 0.5;
  9220. _uv2y = 0.5 * _vector3.y + 0.5;
  9221. _vector3.copy( element.vertexNormalsModelView[ uv3 ] );
  9222. _uv3x = 0.5 * _vector3.x + 0.5;
  9223. _uv3y = 0.5 * _vector3.y + 0.5;
  9224. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  9225. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  9226. }*/
  9227. } else {
  9228. _color.copy( material.color );
  9229. if ( material.vertexColors === THREE.FaceColors ) {
  9230. _color.multiply( element.color );
  9231. }
  9232. material.wireframe === true
  9233. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9234. : fillPath( _color );
  9235. }
  9236. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  9237. _near = _camera.near;
  9238. _far = _camera.far;
  9239. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  9240. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  9241. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  9242. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9243. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9244. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9245. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  9246. var normal;
  9247. if ( material.shading == THREE.FlatShading ) {
  9248. normal = element.normalModelView;
  9249. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9250. material.wireframe === true
  9251. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9252. : fillPath( _color );
  9253. } else if ( material.shading == THREE.SmoothShading ) {
  9254. normal = element.vertexNormalsModelView[ uv1 ];
  9255. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9256. normal = element.vertexNormalsModelView[ uv2 ];
  9257. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9258. normal = element.vertexNormalsModelView[ uv3 ];
  9259. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9260. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9261. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9262. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9263. }
  9264. }
  9265. }
  9266. function renderFace4( v1, v2, v3, v4, v5, v6, element, material ) {
  9267. _this.info.render.vertices += 4;
  9268. _this.info.render.faces ++;
  9269. setOpacity( material.opacity );
  9270. setBlending( material.blending );
  9271. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  9272. // Let renderFace3() handle this
  9273. renderFace3( v1, v2, v4, 0, 1, 3, element, material );
  9274. renderFace3( v5, v3, v6, 1, 2, 3, element, material );
  9275. return;
  9276. }
  9277. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  9278. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  9279. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  9280. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  9281. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  9282. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  9283. if ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  9284. _diffuseColor.copy( material.color );
  9285. _emissiveColor.copy( material.emissive );
  9286. if ( material.vertexColors === THREE.FaceColors ) {
  9287. _diffuseColor.multiply( element.color );
  9288. }
  9289. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  9290. _color1.copy( _ambientLight );
  9291. _color2.copy( _ambientLight );
  9292. _color3.copy( _ambientLight );
  9293. _color4.copy( _ambientLight );
  9294. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  9295. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  9296. calculateLight( element.v4.positionWorld, element.vertexNormalsModel[ 3 ], _color3 );
  9297. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color4 );
  9298. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  9299. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  9300. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  9301. _color4.multiply( _diffuseColor ).add( _emissiveColor );
  9302. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9303. // TODO: UVs are incorrect, v4->v3?
  9304. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  9305. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  9306. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  9307. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  9308. } else {
  9309. _color.copy( _ambientLight );
  9310. calculateLight( element.centroidModel, element.normalModel, _color );
  9311. _color.multiply( _diffuseColor ).add( _emissiveColor );
  9312. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  9313. material.wireframe === true
  9314. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9315. : fillPath( _color );
  9316. }
  9317. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  9318. _color.copy( material.color );
  9319. if ( material.vertexColors === THREE.FaceColors ) {
  9320. _color.multiply( element.color );
  9321. }
  9322. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  9323. material.wireframe === true
  9324. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9325. : fillPath( _color );
  9326. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  9327. var normal;
  9328. if ( material.shading == THREE.FlatShading ) {
  9329. normal = element.normalModelView;
  9330. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9331. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  9332. material.wireframe === true
  9333. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9334. : fillPath( _color );
  9335. } else if ( material.shading == THREE.SmoothShading ) {
  9336. normal = element.vertexNormalsModelView[ 0 ];
  9337. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9338. normal = element.vertexNormalsModelView[ 1 ];
  9339. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9340. normal = element.vertexNormalsModelView[ 3 ];
  9341. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9342. normal = element.vertexNormalsModelView[ 2 ];
  9343. _color4.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9344. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9345. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  9346. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  9347. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  9348. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  9349. }
  9350. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  9351. _near = _camera.near;
  9352. _far = _camera.far;
  9353. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  9354. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  9355. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z * v4.positionScreen.w, _near, _far );
  9356. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  9357. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9358. // TODO: UVs are incorrect, v4->v3?
  9359. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  9360. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  9361. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  9362. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  9363. }
  9364. }
  9365. //
  9366. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  9367. _context.beginPath();
  9368. _context.moveTo( x0, y0 );
  9369. _context.lineTo( x1, y1 );
  9370. _context.lineTo( x2, y2 );
  9371. _context.closePath();
  9372. }
  9373. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  9374. _context.beginPath();
  9375. _context.moveTo( x0, y0 );
  9376. _context.lineTo( x1, y1 );
  9377. _context.lineTo( x2, y2 );
  9378. _context.lineTo( x3, y3 );
  9379. _context.closePath();
  9380. }
  9381. function strokePath( color, linewidth, linecap, linejoin ) {
  9382. setLineWidth( linewidth );
  9383. setLineCap( linecap );
  9384. setLineJoin( linejoin );
  9385. setStrokeStyle( color.getStyle() );
  9386. _context.stroke();
  9387. _elemBox.expandByScalar( linewidth * 2 );
  9388. }
  9389. function fillPath( color ) {
  9390. setFillStyle( color.getStyle() );
  9391. _context.fill();
  9392. }
  9393. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  9394. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  9395. if ( texture.needsUpdate === true ) {
  9396. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  9397. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  9398. _patterns[ texture.id ] = _context.createPattern(
  9399. texture.image, repeatX === true && repeatY === true
  9400. ? 'repeat'
  9401. : repeatX === true && repeatY === false
  9402. ? 'repeat-x'
  9403. : repeatX === false && repeatY === true
  9404. ? 'repeat-y'
  9405. : 'no-repeat'
  9406. );
  9407. texture.needsUpdate = false;
  9408. }
  9409. _patterns[ texture.id ] === undefined
  9410. ? setFillStyle( 'rgba(0,0,0,1)' )
  9411. : setFillStyle( _patterns[ texture.id ] );
  9412. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9413. var a, b, c, d, e, f, det, idet,
  9414. offsetX = texture.offset.x / texture.repeat.x,
  9415. offsetY = texture.offset.y / texture.repeat.y,
  9416. width = texture.image.width * texture.repeat.x,
  9417. height = texture.image.height * texture.repeat.y;
  9418. u0 = ( u0 + offsetX ) * width;
  9419. v0 = ( 1.0 - v0 + offsetY ) * height;
  9420. u1 = ( u1 + offsetX ) * width;
  9421. v1 = ( 1.0 - v1 + offsetY ) * height;
  9422. u2 = ( u2 + offsetX ) * width;
  9423. v2 = ( 1.0 - v2 + offsetY ) * height;
  9424. x1 -= x0; y1 -= y0;
  9425. x2 -= x0; y2 -= y0;
  9426. u1 -= u0; v1 -= v0;
  9427. u2 -= u0; v2 -= v0;
  9428. det = u1 * v2 - u2 * v1;
  9429. if ( det === 0 ) {
  9430. if ( _imagedatas[ texture.id ] === undefined ) {
  9431. var canvas = document.createElement( 'canvas' )
  9432. canvas.width = texture.image.width;
  9433. canvas.height = texture.image.height;
  9434. var context = canvas.getContext( '2d' );
  9435. context.drawImage( texture.image, 0, 0 );
  9436. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  9437. }
  9438. var data = _imagedatas[ texture.id ];
  9439. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  9440. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  9441. fillPath( _color );
  9442. return;
  9443. }
  9444. idet = 1 / det;
  9445. a = ( v2 * x1 - v1 * x2 ) * idet;
  9446. b = ( v2 * y1 - v1 * y2 ) * idet;
  9447. c = ( u1 * x2 - u2 * x1 ) * idet;
  9448. d = ( u1 * y2 - u2 * y1 ) * idet;
  9449. e = x0 - a * u0 - c * v0;
  9450. f = y0 - b * u0 - d * v0;
  9451. _context.save();
  9452. _context.transform( a, b, c, d, e, f );
  9453. _context.fill();
  9454. _context.restore();
  9455. }
  9456. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  9457. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9458. var a, b, c, d, e, f, det, idet,
  9459. width = image.width - 1,
  9460. height = image.height - 1;
  9461. u0 *= width; v0 *= height;
  9462. u1 *= width; v1 *= height;
  9463. u2 *= width; v2 *= height;
  9464. x1 -= x0; y1 -= y0;
  9465. x2 -= x0; y2 -= y0;
  9466. u1 -= u0; v1 -= v0;
  9467. u2 -= u0; v2 -= v0;
  9468. det = u1 * v2 - u2 * v1;
  9469. idet = 1 / det;
  9470. a = ( v2 * x1 - v1 * x2 ) * idet;
  9471. b = ( v2 * y1 - v1 * y2 ) * idet;
  9472. c = ( u1 * x2 - u2 * x1 ) * idet;
  9473. d = ( u1 * y2 - u2 * y1 ) * idet;
  9474. e = x0 - a * u0 - c * v0;
  9475. f = y0 - b * u0 - d * v0;
  9476. _context.save();
  9477. _context.transform( a, b, c, d, e, f );
  9478. _context.clip();
  9479. _context.drawImage( image, 0, 0 );
  9480. _context.restore();
  9481. }
  9482. function getGradientTexture( color1, color2, color3, color4 ) {
  9483. // http://mrdoob.com/blog/post/710
  9484. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  9485. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  9486. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  9487. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  9488. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  9489. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  9490. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  9491. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  9492. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  9493. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  9494. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  9495. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  9496. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  9497. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  9498. return _gradientMap;
  9499. }
  9500. // Hide anti-alias gaps
  9501. function expand( v1, v2, pixels ) {
  9502. var x = v2.x - v1.x, y = v2.y - v1.y,
  9503. det = x * x + y * y, idet;
  9504. if ( det === 0 ) return;
  9505. idet = pixels / Math.sqrt( det );
  9506. x *= idet; y *= idet;
  9507. v2.x += x; v2.y += y;
  9508. v1.x -= x; v1.y -= y;
  9509. }
  9510. // Context cached methods.
  9511. function setOpacity( value ) {
  9512. if ( _contextGlobalAlpha !== value ) {
  9513. _context.globalAlpha = value;
  9514. _contextGlobalAlpha = value;
  9515. }
  9516. }
  9517. function setBlending( value ) {
  9518. if ( _contextGlobalCompositeOperation !== value ) {
  9519. if ( value === THREE.NormalBlending ) {
  9520. _context.globalCompositeOperation = 'source-over';
  9521. } else if ( value === THREE.AdditiveBlending ) {
  9522. _context.globalCompositeOperation = 'lighter';
  9523. } else if ( value === THREE.SubtractiveBlending ) {
  9524. _context.globalCompositeOperation = 'darker';
  9525. }
  9526. _contextGlobalCompositeOperation = value;
  9527. }
  9528. }
  9529. function setLineWidth( value ) {
  9530. if ( _contextLineWidth !== value ) {
  9531. _context.lineWidth = value;
  9532. _contextLineWidth = value;
  9533. }
  9534. }
  9535. function setLineCap( value ) {
  9536. // "butt", "round", "square"
  9537. if ( _contextLineCap !== value ) {
  9538. _context.lineCap = value;
  9539. _contextLineCap = value;
  9540. }
  9541. }
  9542. function setLineJoin( value ) {
  9543. // "round", "bevel", "miter"
  9544. if ( _contextLineJoin !== value ) {
  9545. _context.lineJoin = value;
  9546. _contextLineJoin = value;
  9547. }
  9548. }
  9549. function setStrokeStyle( value ) {
  9550. if ( _contextStrokeStyle !== value ) {
  9551. _context.strokeStyle = value;
  9552. _contextStrokeStyle = value;
  9553. }
  9554. }
  9555. function setFillStyle( value ) {
  9556. if ( _contextFillStyle !== value ) {
  9557. _context.fillStyle = value;
  9558. _contextFillStyle = value;
  9559. }
  9560. }
  9561. function setDashAndGap( dashSizeValue, gapSizeValue ) {
  9562. if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) {
  9563. _context.setLineDash( [ dashSizeValue, gapSizeValue ] );
  9564. _contextDashSize = dashSizeValue;
  9565. _contextGapSize = gapSizeValue;
  9566. }
  9567. }
  9568. };
  9569. /**
  9570. * @author alteredq / http://alteredqualia.com/
  9571. * @author mrdoob / http://mrdoob.com/
  9572. * @author mikael emtinger / http://gomo.se/
  9573. */
  9574. THREE.ShaderChunk = {
  9575. // FOG
  9576. fog_pars_fragment: [
  9577. "#ifdef USE_FOG",
  9578. "uniform vec3 fogColor;",
  9579. "#ifdef FOG_EXP2",
  9580. "uniform float fogDensity;",
  9581. "#else",
  9582. "uniform float fogNear;",
  9583. "uniform float fogFar;",
  9584. "#endif",
  9585. "#endif"
  9586. ].join("\n"),
  9587. fog_fragment: [
  9588. "#ifdef USE_FOG",
  9589. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  9590. "#ifdef FOG_EXP2",
  9591. "const float LOG2 = 1.442695;",
  9592. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  9593. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  9594. "#else",
  9595. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  9596. "#endif",
  9597. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  9598. "#endif"
  9599. ].join("\n"),
  9600. // ENVIRONMENT MAP
  9601. envmap_pars_fragment: [
  9602. "#ifdef USE_ENVMAP",
  9603. "uniform float reflectivity;",
  9604. "uniform samplerCube envMap;",
  9605. "uniform float flipEnvMap;",
  9606. "uniform int combine;",
  9607. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9608. "uniform bool useRefract;",
  9609. "uniform float refractionRatio;",
  9610. "#else",
  9611. "varying vec3 vReflect;",
  9612. "#endif",
  9613. "#endif"
  9614. ].join("\n"),
  9615. envmap_fragment: [
  9616. "#ifdef USE_ENVMAP",
  9617. "vec3 reflectVec;",
  9618. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9619. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  9620. "if ( useRefract ) {",
  9621. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  9622. "} else { ",
  9623. "reflectVec = reflect( cameraToVertex, normal );",
  9624. "}",
  9625. "#else",
  9626. "reflectVec = vReflect;",
  9627. "#endif",
  9628. "#ifdef DOUBLE_SIDED",
  9629. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9630. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9631. "#else",
  9632. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9633. "#endif",
  9634. "#ifdef GAMMA_INPUT",
  9635. "cubeColor.xyz *= cubeColor.xyz;",
  9636. "#endif",
  9637. "if ( combine == 1 ) {",
  9638. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  9639. "} else if ( combine == 2 ) {",
  9640. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  9641. "} else {",
  9642. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  9643. "}",
  9644. "#endif"
  9645. ].join("\n"),
  9646. envmap_pars_vertex: [
  9647. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9648. "varying vec3 vReflect;",
  9649. "uniform float refractionRatio;",
  9650. "uniform bool useRefract;",
  9651. "#endif"
  9652. ].join("\n"),
  9653. worldpos_vertex : [
  9654. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  9655. "#ifdef USE_SKINNING",
  9656. "vec4 worldPosition = modelMatrix * skinned;",
  9657. "#endif",
  9658. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9659. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  9660. "#endif",
  9661. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9662. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  9663. "#endif",
  9664. "#endif"
  9665. ].join("\n"),
  9666. envmap_vertex : [
  9667. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9668. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  9669. "worldNormal = normalize( worldNormal );",
  9670. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  9671. "if ( useRefract ) {",
  9672. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  9673. "} else {",
  9674. "vReflect = reflect( cameraToVertex, worldNormal );",
  9675. "}",
  9676. "#endif"
  9677. ].join("\n"),
  9678. // COLOR MAP (particles)
  9679. map_particle_pars_fragment: [
  9680. "#ifdef USE_MAP",
  9681. "uniform sampler2D map;",
  9682. "#endif"
  9683. ].join("\n"),
  9684. map_particle_fragment: [
  9685. "#ifdef USE_MAP",
  9686. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  9687. "#endif"
  9688. ].join("\n"),
  9689. // COLOR MAP (triangles)
  9690. map_pars_vertex: [
  9691. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9692. "varying vec2 vUv;",
  9693. "uniform vec4 offsetRepeat;",
  9694. "#endif"
  9695. ].join("\n"),
  9696. map_pars_fragment: [
  9697. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9698. "varying vec2 vUv;",
  9699. "#endif",
  9700. "#ifdef USE_MAP",
  9701. "uniform sampler2D map;",
  9702. "#endif"
  9703. ].join("\n"),
  9704. map_vertex: [
  9705. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9706. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  9707. "#endif"
  9708. ].join("\n"),
  9709. map_fragment: [
  9710. "#ifdef USE_MAP",
  9711. "vec4 texelColor = texture2D( map, vUv );",
  9712. "#ifdef GAMMA_INPUT",
  9713. "texelColor.xyz *= texelColor.xyz;",
  9714. "#endif",
  9715. "gl_FragColor = gl_FragColor * texelColor;",
  9716. "#endif"
  9717. ].join("\n"),
  9718. // LIGHT MAP
  9719. lightmap_pars_fragment: [
  9720. "#ifdef USE_LIGHTMAP",
  9721. "varying vec2 vUv2;",
  9722. "uniform sampler2D lightMap;",
  9723. "#endif"
  9724. ].join("\n"),
  9725. lightmap_pars_vertex: [
  9726. "#ifdef USE_LIGHTMAP",
  9727. "varying vec2 vUv2;",
  9728. "#endif"
  9729. ].join("\n"),
  9730. lightmap_fragment: [
  9731. "#ifdef USE_LIGHTMAP",
  9732. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  9733. "#endif"
  9734. ].join("\n"),
  9735. lightmap_vertex: [
  9736. "#ifdef USE_LIGHTMAP",
  9737. "vUv2 = uv2;",
  9738. "#endif"
  9739. ].join("\n"),
  9740. // BUMP MAP
  9741. bumpmap_pars_fragment: [
  9742. "#ifdef USE_BUMPMAP",
  9743. "uniform sampler2D bumpMap;",
  9744. "uniform float bumpScale;",
  9745. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  9746. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  9747. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  9748. "vec2 dHdxy_fwd() {",
  9749. "vec2 dSTdx = dFdx( vUv );",
  9750. "vec2 dSTdy = dFdy( vUv );",
  9751. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  9752. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  9753. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  9754. "return vec2( dBx, dBy );",
  9755. "}",
  9756. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  9757. "vec3 vSigmaX = dFdx( surf_pos );",
  9758. "vec3 vSigmaY = dFdy( surf_pos );",
  9759. "vec3 vN = surf_norm;", // normalized
  9760. "vec3 R1 = cross( vSigmaY, vN );",
  9761. "vec3 R2 = cross( vN, vSigmaX );",
  9762. "float fDet = dot( vSigmaX, R1 );",
  9763. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  9764. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  9765. "}",
  9766. "#endif"
  9767. ].join("\n"),
  9768. // NORMAL MAP
  9769. normalmap_pars_fragment: [
  9770. "#ifdef USE_NORMALMAP",
  9771. "uniform sampler2D normalMap;",
  9772. "uniform vec2 normalScale;",
  9773. // Per-Pixel Tangent Space Normal Mapping
  9774. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  9775. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  9776. "vec3 q0 = dFdx( eye_pos.xyz );",
  9777. "vec3 q1 = dFdy( eye_pos.xyz );",
  9778. "vec2 st0 = dFdx( vUv.st );",
  9779. "vec2 st1 = dFdy( vUv.st );",
  9780. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  9781. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  9782. "vec3 N = normalize( surf_norm );",
  9783. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  9784. "mapN.xy = normalScale * mapN.xy;",
  9785. "mat3 tsn = mat3( S, T, N );",
  9786. "return normalize( tsn * mapN );",
  9787. "}",
  9788. "#endif"
  9789. ].join("\n"),
  9790. // SPECULAR MAP
  9791. specularmap_pars_fragment: [
  9792. "#ifdef USE_SPECULARMAP",
  9793. "uniform sampler2D specularMap;",
  9794. "#endif"
  9795. ].join("\n"),
  9796. specularmap_fragment: [
  9797. "float specularStrength;",
  9798. "#ifdef USE_SPECULARMAP",
  9799. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  9800. "specularStrength = texelSpecular.r;",
  9801. "#else",
  9802. "specularStrength = 1.0;",
  9803. "#endif"
  9804. ].join("\n"),
  9805. // LIGHTS LAMBERT
  9806. lights_lambert_pars_vertex: [
  9807. "uniform vec3 ambient;",
  9808. "uniform vec3 diffuse;",
  9809. "uniform vec3 emissive;",
  9810. "uniform vec3 ambientLightColor;",
  9811. "#if MAX_DIR_LIGHTS > 0",
  9812. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9813. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9814. "#endif",
  9815. "#if MAX_HEMI_LIGHTS > 0",
  9816. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9817. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9818. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9819. "#endif",
  9820. "#if MAX_POINT_LIGHTS > 0",
  9821. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9822. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9823. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9824. "#endif",
  9825. "#if MAX_SPOT_LIGHTS > 0",
  9826. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9827. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9828. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9829. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9830. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9831. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9832. "#endif",
  9833. "#ifdef WRAP_AROUND",
  9834. "uniform vec3 wrapRGB;",
  9835. "#endif"
  9836. ].join("\n"),
  9837. lights_lambert_vertex: [
  9838. "vLightFront = vec3( 0.0 );",
  9839. "#ifdef DOUBLE_SIDED",
  9840. "vLightBack = vec3( 0.0 );",
  9841. "#endif",
  9842. "transformedNormal = normalize( transformedNormal );",
  9843. "#if MAX_DIR_LIGHTS > 0",
  9844. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9845. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9846. "vec3 dirVector = normalize( lDirection.xyz );",
  9847. "float dotProduct = dot( transformedNormal, dirVector );",
  9848. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9849. "#ifdef DOUBLE_SIDED",
  9850. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9851. "#ifdef WRAP_AROUND",
  9852. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9853. "#endif",
  9854. "#endif",
  9855. "#ifdef WRAP_AROUND",
  9856. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9857. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  9858. "#ifdef DOUBLE_SIDED",
  9859. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  9860. "#endif",
  9861. "#endif",
  9862. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  9863. "#ifdef DOUBLE_SIDED",
  9864. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  9865. "#endif",
  9866. "}",
  9867. "#endif",
  9868. "#if MAX_POINT_LIGHTS > 0",
  9869. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9870. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9871. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9872. "float lDistance = 1.0;",
  9873. "if ( pointLightDistance[ i ] > 0.0 )",
  9874. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9875. "lVector = normalize( lVector );",
  9876. "float dotProduct = dot( transformedNormal, lVector );",
  9877. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9878. "#ifdef DOUBLE_SIDED",
  9879. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9880. "#ifdef WRAP_AROUND",
  9881. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9882. "#endif",
  9883. "#endif",
  9884. "#ifdef WRAP_AROUND",
  9885. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9886. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  9887. "#ifdef DOUBLE_SIDED",
  9888. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  9889. "#endif",
  9890. "#endif",
  9891. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  9892. "#ifdef DOUBLE_SIDED",
  9893. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  9894. "#endif",
  9895. "}",
  9896. "#endif",
  9897. "#if MAX_SPOT_LIGHTS > 0",
  9898. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9899. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9900. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9901. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  9902. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9903. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9904. "float lDistance = 1.0;",
  9905. "if ( spotLightDistance[ i ] > 0.0 )",
  9906. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9907. "lVector = normalize( lVector );",
  9908. "float dotProduct = dot( transformedNormal, lVector );",
  9909. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9910. "#ifdef DOUBLE_SIDED",
  9911. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9912. "#ifdef WRAP_AROUND",
  9913. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9914. "#endif",
  9915. "#endif",
  9916. "#ifdef WRAP_AROUND",
  9917. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9918. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  9919. "#ifdef DOUBLE_SIDED",
  9920. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  9921. "#endif",
  9922. "#endif",
  9923. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  9924. "#ifdef DOUBLE_SIDED",
  9925. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  9926. "#endif",
  9927. "}",
  9928. "}",
  9929. "#endif",
  9930. "#if MAX_HEMI_LIGHTS > 0",
  9931. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9932. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9933. "vec3 lVector = normalize( lDirection.xyz );",
  9934. "float dotProduct = dot( transformedNormal, lVector );",
  9935. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9936. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  9937. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9938. "#ifdef DOUBLE_SIDED",
  9939. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  9940. "#endif",
  9941. "}",
  9942. "#endif",
  9943. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  9944. "#ifdef DOUBLE_SIDED",
  9945. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  9946. "#endif"
  9947. ].join("\n"),
  9948. // LIGHTS PHONG
  9949. lights_phong_pars_vertex: [
  9950. "#ifndef PHONG_PER_PIXEL",
  9951. "#if MAX_POINT_LIGHTS > 0",
  9952. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9953. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9954. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9955. "#endif",
  9956. "#if MAX_SPOT_LIGHTS > 0",
  9957. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9958. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9959. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9960. "#endif",
  9961. "#endif",
  9962. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9963. "varying vec3 vWorldPosition;",
  9964. "#endif"
  9965. ].join("\n"),
  9966. lights_phong_vertex: [
  9967. "#ifndef PHONG_PER_PIXEL",
  9968. "#if MAX_POINT_LIGHTS > 0",
  9969. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9970. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9971. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9972. "float lDistance = 1.0;",
  9973. "if ( pointLightDistance[ i ] > 0.0 )",
  9974. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9975. "vPointLight[ i ] = vec4( lVector, lDistance );",
  9976. "}",
  9977. "#endif",
  9978. "#if MAX_SPOT_LIGHTS > 0",
  9979. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9980. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9981. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9982. "float lDistance = 1.0;",
  9983. "if ( spotLightDistance[ i ] > 0.0 )",
  9984. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9985. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  9986. "}",
  9987. "#endif",
  9988. "#endif",
  9989. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9990. "vWorldPosition = worldPosition.xyz;",
  9991. "#endif"
  9992. ].join("\n"),
  9993. lights_phong_pars_fragment: [
  9994. "uniform vec3 ambientLightColor;",
  9995. "#if MAX_DIR_LIGHTS > 0",
  9996. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9997. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9998. "#endif",
  9999. "#if MAX_HEMI_LIGHTS > 0",
  10000. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10001. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10002. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10003. "#endif",
  10004. "#if MAX_POINT_LIGHTS > 0",
  10005. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10006. "#ifdef PHONG_PER_PIXEL",
  10007. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10008. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10009. "#else",
  10010. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  10011. "#endif",
  10012. "#endif",
  10013. "#if MAX_SPOT_LIGHTS > 0",
  10014. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10015. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10016. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10017. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10018. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10019. "#ifdef PHONG_PER_PIXEL",
  10020. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10021. "#else",
  10022. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  10023. "#endif",
  10024. "#endif",
  10025. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10026. "varying vec3 vWorldPosition;",
  10027. "#endif",
  10028. "#ifdef WRAP_AROUND",
  10029. "uniform vec3 wrapRGB;",
  10030. "#endif",
  10031. "varying vec3 vViewPosition;",
  10032. "varying vec3 vNormal;"
  10033. ].join("\n"),
  10034. lights_phong_fragment: [
  10035. "vec3 normal = normalize( vNormal );",
  10036. "vec3 viewPosition = normalize( vViewPosition );",
  10037. "#ifdef DOUBLE_SIDED",
  10038. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  10039. "#endif",
  10040. "#ifdef USE_NORMALMAP",
  10041. "normal = perturbNormal2Arb( -vViewPosition, normal );",
  10042. "#elif defined( USE_BUMPMAP )",
  10043. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  10044. "#endif",
  10045. "#if MAX_POINT_LIGHTS > 0",
  10046. "vec3 pointDiffuse = vec3( 0.0 );",
  10047. "vec3 pointSpecular = vec3( 0.0 );",
  10048. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10049. "#ifdef PHONG_PER_PIXEL",
  10050. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10051. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10052. "float lDistance = 1.0;",
  10053. "if ( pointLightDistance[ i ] > 0.0 )",
  10054. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10055. "lVector = normalize( lVector );",
  10056. "#else",
  10057. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  10058. "float lDistance = vPointLight[ i ].w;",
  10059. "#endif",
  10060. // diffuse
  10061. "float dotProduct = dot( normal, lVector );",
  10062. "#ifdef WRAP_AROUND",
  10063. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  10064. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10065. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  10066. "#else",
  10067. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  10068. "#endif",
  10069. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  10070. // specular
  10071. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  10072. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  10073. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  10074. "#ifdef PHYSICALLY_BASED_SHADING",
  10075. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10076. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10077. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  10078. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  10079. "#else",
  10080. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  10081. "#endif",
  10082. "}",
  10083. "#endif",
  10084. "#if MAX_SPOT_LIGHTS > 0",
  10085. "vec3 spotDiffuse = vec3( 0.0 );",
  10086. "vec3 spotSpecular = vec3( 0.0 );",
  10087. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10088. "#ifdef PHONG_PER_PIXEL",
  10089. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10090. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10091. "float lDistance = 1.0;",
  10092. "if ( spotLightDistance[ i ] > 0.0 )",
  10093. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10094. "lVector = normalize( lVector );",
  10095. "#else",
  10096. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  10097. "float lDistance = vSpotLight[ i ].w;",
  10098. "#endif",
  10099. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  10100. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10101. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10102. // diffuse
  10103. "float dotProduct = dot( normal, lVector );",
  10104. "#ifdef WRAP_AROUND",
  10105. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  10106. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10107. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  10108. "#else",
  10109. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  10110. "#endif",
  10111. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  10112. // specular
  10113. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  10114. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  10115. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  10116. "#ifdef PHYSICALLY_BASED_SHADING",
  10117. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10118. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10119. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  10120. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  10121. "#else",
  10122. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  10123. "#endif",
  10124. "}",
  10125. "}",
  10126. "#endif",
  10127. "#if MAX_DIR_LIGHTS > 0",
  10128. "vec3 dirDiffuse = vec3( 0.0 );",
  10129. "vec3 dirSpecular = vec3( 0.0 );" ,
  10130. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10131. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10132. "vec3 dirVector = normalize( lDirection.xyz );",
  10133. // diffuse
  10134. "float dotProduct = dot( normal, dirVector );",
  10135. "#ifdef WRAP_AROUND",
  10136. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  10137. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10138. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  10139. "#else",
  10140. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  10141. "#endif",
  10142. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  10143. // specular
  10144. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  10145. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  10146. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  10147. "#ifdef PHYSICALLY_BASED_SHADING",
  10148. /*
  10149. // fresnel term from skin shader
  10150. "const float F0 = 0.128;",
  10151. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  10152. "float exponential = pow( base, 5.0 );",
  10153. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  10154. */
  10155. /*
  10156. // fresnel term from fresnel shader
  10157. "const float mFresnelBias = 0.08;",
  10158. "const float mFresnelScale = 0.3;",
  10159. "const float mFresnelPower = 5.0;",
  10160. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  10161. */
  10162. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10163. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10164. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  10165. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  10166. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  10167. "#else",
  10168. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  10169. "#endif",
  10170. "}",
  10171. "#endif",
  10172. "#if MAX_HEMI_LIGHTS > 0",
  10173. "vec3 hemiDiffuse = vec3( 0.0 );",
  10174. "vec3 hemiSpecular = vec3( 0.0 );" ,
  10175. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10176. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10177. "vec3 lVector = normalize( lDirection.xyz );",
  10178. // diffuse
  10179. "float dotProduct = dot( normal, lVector );",
  10180. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10181. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10182. "hemiDiffuse += diffuse * hemiColor;",
  10183. // specular (sky light)
  10184. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  10185. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  10186. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  10187. // specular (ground light)
  10188. "vec3 lVectorGround = -lVector;",
  10189. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  10190. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  10191. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  10192. "#ifdef PHYSICALLY_BASED_SHADING",
  10193. "float dotProductGround = dot( normal, lVectorGround );",
  10194. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10195. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10196. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  10197. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  10198. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  10199. "#else",
  10200. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  10201. "#endif",
  10202. "}",
  10203. "#endif",
  10204. "vec3 totalDiffuse = vec3( 0.0 );",
  10205. "vec3 totalSpecular = vec3( 0.0 );",
  10206. "#if MAX_DIR_LIGHTS > 0",
  10207. "totalDiffuse += dirDiffuse;",
  10208. "totalSpecular += dirSpecular;",
  10209. "#endif",
  10210. "#if MAX_HEMI_LIGHTS > 0",
  10211. "totalDiffuse += hemiDiffuse;",
  10212. "totalSpecular += hemiSpecular;",
  10213. "#endif",
  10214. "#if MAX_POINT_LIGHTS > 0",
  10215. "totalDiffuse += pointDiffuse;",
  10216. "totalSpecular += pointSpecular;",
  10217. "#endif",
  10218. "#if MAX_SPOT_LIGHTS > 0",
  10219. "totalDiffuse += spotDiffuse;",
  10220. "totalSpecular += spotSpecular;",
  10221. "#endif",
  10222. "#ifdef METAL",
  10223. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  10224. "#else",
  10225. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  10226. "#endif"
  10227. ].join("\n"),
  10228. // VERTEX COLORS
  10229. color_pars_fragment: [
  10230. "#ifdef USE_COLOR",
  10231. "varying vec3 vColor;",
  10232. "#endif"
  10233. ].join("\n"),
  10234. color_fragment: [
  10235. "#ifdef USE_COLOR",
  10236. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  10237. "#endif"
  10238. ].join("\n"),
  10239. color_pars_vertex: [
  10240. "#ifdef USE_COLOR",
  10241. "varying vec3 vColor;",
  10242. "#endif"
  10243. ].join("\n"),
  10244. color_vertex: [
  10245. "#ifdef USE_COLOR",
  10246. "#ifdef GAMMA_INPUT",
  10247. "vColor = color * color;",
  10248. "#else",
  10249. "vColor = color;",
  10250. "#endif",
  10251. "#endif"
  10252. ].join("\n"),
  10253. // SKINNING
  10254. skinning_pars_vertex: [
  10255. "#ifdef USE_SKINNING",
  10256. "#ifdef BONE_TEXTURE",
  10257. "uniform sampler2D boneTexture;",
  10258. "mat4 getBoneMatrix( const in float i ) {",
  10259. "float j = i * 4.0;",
  10260. "float x = mod( j, N_BONE_PIXEL_X );",
  10261. "float y = floor( j / N_BONE_PIXEL_X );",
  10262. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  10263. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  10264. "y = dy * ( y + 0.5 );",
  10265. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  10266. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  10267. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  10268. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  10269. "mat4 bone = mat4( v1, v2, v3, v4 );",
  10270. "return bone;",
  10271. "}",
  10272. "#else",
  10273. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  10274. "mat4 getBoneMatrix( const in float i ) {",
  10275. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  10276. "return bone;",
  10277. "}",
  10278. "#endif",
  10279. "#endif"
  10280. ].join("\n"),
  10281. skinbase_vertex: [
  10282. "#ifdef USE_SKINNING",
  10283. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  10284. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  10285. "#endif"
  10286. ].join("\n"),
  10287. skinning_vertex: [
  10288. "#ifdef USE_SKINNING",
  10289. "#ifdef USE_MORPHTARGETS",
  10290. "vec4 skinVertex = vec4( morphed, 1.0 );",
  10291. "#else",
  10292. "vec4 skinVertex = vec4( position, 1.0 );",
  10293. "#endif",
  10294. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10295. "skinned += boneMatY * skinVertex * skinWeight.y;",
  10296. "#endif"
  10297. ].join("\n"),
  10298. // MORPHING
  10299. morphtarget_pars_vertex: [
  10300. "#ifdef USE_MORPHTARGETS",
  10301. "#ifndef USE_MORPHNORMALS",
  10302. "uniform float morphTargetInfluences[ 8 ];",
  10303. "#else",
  10304. "uniform float morphTargetInfluences[ 4 ];",
  10305. "#endif",
  10306. "#endif"
  10307. ].join("\n"),
  10308. morphtarget_vertex: [
  10309. "#ifdef USE_MORPHTARGETS",
  10310. "vec3 morphed = vec3( 0.0 );",
  10311. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  10312. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  10313. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  10314. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  10315. "#ifndef USE_MORPHNORMALS",
  10316. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  10317. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  10318. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  10319. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  10320. "#endif",
  10321. "morphed += position;",
  10322. "#endif"
  10323. ].join("\n"),
  10324. default_vertex : [
  10325. "vec4 mvPosition;",
  10326. "#ifdef USE_SKINNING",
  10327. "mvPosition = modelViewMatrix * skinned;",
  10328. "#endif",
  10329. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  10330. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  10331. "#endif",
  10332. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  10333. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10334. "#endif",
  10335. "gl_Position = projectionMatrix * mvPosition;"
  10336. ].join("\n"),
  10337. morphnormal_vertex: [
  10338. "#ifdef USE_MORPHNORMALS",
  10339. "vec3 morphedNormal = vec3( 0.0 );",
  10340. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  10341. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  10342. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  10343. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  10344. "morphedNormal += normal;",
  10345. "#endif"
  10346. ].join("\n"),
  10347. skinnormal_vertex: [
  10348. "#ifdef USE_SKINNING",
  10349. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  10350. "skinMatrix += skinWeight.y * boneMatY;",
  10351. "#ifdef USE_MORPHNORMALS",
  10352. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  10353. "#else",
  10354. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  10355. "#endif",
  10356. "#endif"
  10357. ].join("\n"),
  10358. defaultnormal_vertex: [
  10359. "vec3 objectNormal;",
  10360. "#ifdef USE_SKINNING",
  10361. "objectNormal = skinnedNormal.xyz;",
  10362. "#endif",
  10363. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  10364. "objectNormal = morphedNormal;",
  10365. "#endif",
  10366. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  10367. "objectNormal = normal;",
  10368. "#endif",
  10369. "#ifdef FLIP_SIDED",
  10370. "objectNormal = -objectNormal;",
  10371. "#endif",
  10372. "vec3 transformedNormal = normalMatrix * objectNormal;"
  10373. ].join("\n"),
  10374. // SHADOW MAP
  10375. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  10376. // http://spidergl.org/example.php?id=6
  10377. // http://fabiensanglard.net/shadowmapping
  10378. shadowmap_pars_fragment: [
  10379. "#ifdef USE_SHADOWMAP",
  10380. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  10381. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  10382. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  10383. "uniform float shadowBias[ MAX_SHADOWS ];",
  10384. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10385. "float unpackDepth( const in vec4 rgba_depth ) {",
  10386. "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 );",
  10387. "float depth = dot( rgba_depth, bit_shift );",
  10388. "return depth;",
  10389. "}",
  10390. "#endif"
  10391. ].join("\n"),
  10392. shadowmap_fragment: [
  10393. "#ifdef USE_SHADOWMAP",
  10394. "#ifdef SHADOWMAP_DEBUG",
  10395. "vec3 frustumColors[3];",
  10396. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  10397. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  10398. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  10399. "#endif",
  10400. "#ifdef SHADOWMAP_CASCADE",
  10401. "int inFrustumCount = 0;",
  10402. "#endif",
  10403. "float fDepth;",
  10404. "vec3 shadowColor = vec3( 1.0 );",
  10405. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10406. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  10407. // "if ( something && something )" breaks ATI OpenGL shader compiler
  10408. // "if ( all( something, something ) )" using this instead
  10409. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  10410. "bool inFrustum = all( inFrustumVec );",
  10411. // don't shadow pixels outside of light frustum
  10412. // use just first frustum (for cascades)
  10413. // don't shadow pixels behind far plane of light frustum
  10414. "#ifdef SHADOWMAP_CASCADE",
  10415. "inFrustumCount += int( inFrustum );",
  10416. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  10417. "#else",
  10418. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  10419. "#endif",
  10420. "bool frustumTest = all( frustumTestVec );",
  10421. "if ( frustumTest ) {",
  10422. "shadowCoord.z += shadowBias[ i ];",
  10423. "#if defined( SHADOWMAP_TYPE_PCF )",
  10424. // Percentage-close filtering
  10425. // (9 pixel kernel)
  10426. // http://fabiensanglard.net/shadowmappingPCF/
  10427. "float shadow = 0.0;",
  10428. /*
  10429. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  10430. // must enroll loop manually
  10431. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  10432. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  10433. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  10434. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  10435. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  10436. "float fDepth = unpackDepth( rgbaDepth );",
  10437. "if ( fDepth < shadowCoord.z )",
  10438. "shadow += 1.0;",
  10439. "}",
  10440. "shadow /= 9.0;",
  10441. */
  10442. "const float shadowDelta = 1.0 / 9.0;",
  10443. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10444. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10445. "float dx0 = -1.25 * xPixelOffset;",
  10446. "float dy0 = -1.25 * yPixelOffset;",
  10447. "float dx1 = 1.25 * xPixelOffset;",
  10448. "float dy1 = 1.25 * yPixelOffset;",
  10449. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10450. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10451. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10452. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10453. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10454. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10455. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10456. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10457. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10458. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10459. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10460. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10461. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10462. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10463. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10464. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10465. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10466. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10467. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10468. "#elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  10469. // Percentage-close filtering
  10470. // (9 pixel kernel)
  10471. // http://fabiensanglard.net/shadowmappingPCF/
  10472. "float shadow = 0.0;",
  10473. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10474. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10475. "float dx0 = -1.0 * xPixelOffset;",
  10476. "float dy0 = -1.0 * yPixelOffset;",
  10477. "float dx1 = 1.0 * xPixelOffset;",
  10478. "float dy1 = 1.0 * yPixelOffset;",
  10479. "mat3 shadowKernel;",
  10480. "mat3 depthKernel;",
  10481. "depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10482. "depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10483. "depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10484. "depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10485. "depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10486. "depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10487. "depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10488. "depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10489. "depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10490. "vec3 shadowZ = vec3( shadowCoord.z );",
  10491. "shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));",
  10492. "shadowKernel[0] *= vec3(0.25);",
  10493. "shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));",
  10494. "shadowKernel[1] *= vec3(0.25);",
  10495. "shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));",
  10496. "shadowKernel[2] *= vec3(0.25);",
  10497. "vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  10498. "shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  10499. "shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  10500. "vec4 shadowValues;",
  10501. "shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  10502. "shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  10503. "shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  10504. "shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  10505. "shadow = dot( shadowValues, vec4( 1.0 ) );",
  10506. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10507. "#else",
  10508. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  10509. "float fDepth = unpackDepth( rgbaDepth );",
  10510. "if ( fDepth < shadowCoord.z )",
  10511. // spot with multiple shadows is darker
  10512. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  10513. // spot with multiple shadows has the same color as single shadow spot
  10514. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  10515. "#endif",
  10516. "}",
  10517. "#ifdef SHADOWMAP_DEBUG",
  10518. "#ifdef SHADOWMAP_CASCADE",
  10519. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  10520. "#else",
  10521. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  10522. "#endif",
  10523. "#endif",
  10524. "}",
  10525. "#ifdef GAMMA_OUTPUT",
  10526. "shadowColor *= shadowColor;",
  10527. "#endif",
  10528. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  10529. "#endif"
  10530. ].join("\n"),
  10531. shadowmap_pars_vertex: [
  10532. "#ifdef USE_SHADOWMAP",
  10533. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10534. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  10535. "#endif"
  10536. ].join("\n"),
  10537. shadowmap_vertex: [
  10538. "#ifdef USE_SHADOWMAP",
  10539. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10540. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  10541. "}",
  10542. "#endif"
  10543. ].join("\n"),
  10544. // ALPHATEST
  10545. alphatest_fragment: [
  10546. "#ifdef ALPHATEST",
  10547. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  10548. "#endif"
  10549. ].join("\n"),
  10550. // LINEAR SPACE
  10551. linear_to_gamma_fragment: [
  10552. "#ifdef GAMMA_OUTPUT",
  10553. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  10554. "#endif"
  10555. ].join("\n")
  10556. };
  10557. THREE.UniformsUtils = {
  10558. merge: function ( uniforms ) {
  10559. var u, p, tmp, merged = {};
  10560. for ( u = 0; u < uniforms.length; u ++ ) {
  10561. tmp = this.clone( uniforms[ u ] );
  10562. for ( p in tmp ) {
  10563. merged[ p ] = tmp[ p ];
  10564. }
  10565. }
  10566. return merged;
  10567. },
  10568. clone: function ( uniforms_src ) {
  10569. var u, p, parameter, parameter_src, uniforms_dst = {};
  10570. for ( u in uniforms_src ) {
  10571. uniforms_dst[ u ] = {};
  10572. for ( p in uniforms_src[ u ] ) {
  10573. parameter_src = uniforms_src[ u ][ p ];
  10574. if ( parameter_src instanceof THREE.Color ||
  10575. parameter_src instanceof THREE.Vector2 ||
  10576. parameter_src instanceof THREE.Vector3 ||
  10577. parameter_src instanceof THREE.Vector4 ||
  10578. parameter_src instanceof THREE.Matrix4 ||
  10579. parameter_src instanceof THREE.Texture ) {
  10580. uniforms_dst[ u ][ p ] = parameter_src.clone();
  10581. } else if ( parameter_src instanceof Array ) {
  10582. uniforms_dst[ u ][ p ] = parameter_src.slice();
  10583. } else {
  10584. uniforms_dst[ u ][ p ] = parameter_src;
  10585. }
  10586. }
  10587. }
  10588. return uniforms_dst;
  10589. }
  10590. };
  10591. THREE.UniformsLib = {
  10592. common: {
  10593. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10594. "opacity" : { type: "f", value: 1.0 },
  10595. "map" : { type: "t", value: null },
  10596. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  10597. "lightMap" : { type: "t", value: null },
  10598. "specularMap" : { type: "t", value: null },
  10599. "envMap" : { type: "t", value: null },
  10600. "flipEnvMap" : { type: "f", value: -1 },
  10601. "useRefract" : { type: "i", value: 0 },
  10602. "reflectivity" : { type: "f", value: 1.0 },
  10603. "refractionRatio" : { type: "f", value: 0.98 },
  10604. "combine" : { type: "i", value: 0 },
  10605. "morphTargetInfluences" : { type: "f", value: 0 }
  10606. },
  10607. bump: {
  10608. "bumpMap" : { type: "t", value: null },
  10609. "bumpScale" : { type: "f", value: 1 }
  10610. },
  10611. normalmap: {
  10612. "normalMap" : { type: "t", value: null },
  10613. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  10614. },
  10615. fog : {
  10616. "fogDensity" : { type: "f", value: 0.00025 },
  10617. "fogNear" : { type: "f", value: 1 },
  10618. "fogFar" : { type: "f", value: 2000 },
  10619. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10620. },
  10621. lights: {
  10622. "ambientLightColor" : { type: "fv", value: [] },
  10623. "directionalLightDirection" : { type: "fv", value: [] },
  10624. "directionalLightColor" : { type: "fv", value: [] },
  10625. "hemisphereLightDirection" : { type: "fv", value: [] },
  10626. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  10627. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  10628. "pointLightColor" : { type: "fv", value: [] },
  10629. "pointLightPosition" : { type: "fv", value: [] },
  10630. "pointLightDistance" : { type: "fv1", value: [] },
  10631. "spotLightColor" : { type: "fv", value: [] },
  10632. "spotLightPosition" : { type: "fv", value: [] },
  10633. "spotLightDirection" : { type: "fv", value: [] },
  10634. "spotLightDistance" : { type: "fv1", value: [] },
  10635. "spotLightAngleCos" : { type: "fv1", value: [] },
  10636. "spotLightExponent" : { type: "fv1", value: [] }
  10637. },
  10638. particle: {
  10639. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10640. "opacity" : { type: "f", value: 1.0 },
  10641. "size" : { type: "f", value: 1.0 },
  10642. "scale" : { type: "f", value: 1.0 },
  10643. "map" : { type: "t", value: null },
  10644. "fogDensity" : { type: "f", value: 0.00025 },
  10645. "fogNear" : { type: "f", value: 1 },
  10646. "fogFar" : { type: "f", value: 2000 },
  10647. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10648. },
  10649. shadowmap: {
  10650. "shadowMap": { type: "tv", value: [] },
  10651. "shadowMapSize": { type: "v2v", value: [] },
  10652. "shadowBias" : { type: "fv1", value: [] },
  10653. "shadowDarkness": { type: "fv1", value: [] },
  10654. "shadowMatrix" : { type: "m4v", value: [] }
  10655. }
  10656. };
  10657. THREE.ShaderLib = {
  10658. 'basic': {
  10659. uniforms: THREE.UniformsUtils.merge( [
  10660. THREE.UniformsLib[ "common" ],
  10661. THREE.UniformsLib[ "fog" ],
  10662. THREE.UniformsLib[ "shadowmap" ]
  10663. ] ),
  10664. vertexShader: [
  10665. THREE.ShaderChunk[ "map_pars_vertex" ],
  10666. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10667. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10668. THREE.ShaderChunk[ "color_pars_vertex" ],
  10669. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10670. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10671. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10672. "void main() {",
  10673. THREE.ShaderChunk[ "map_vertex" ],
  10674. THREE.ShaderChunk[ "lightmap_vertex" ],
  10675. THREE.ShaderChunk[ "color_vertex" ],
  10676. THREE.ShaderChunk[ "skinbase_vertex" ],
  10677. "#ifdef USE_ENVMAP",
  10678. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10679. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10680. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10681. "#endif",
  10682. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10683. THREE.ShaderChunk[ "skinning_vertex" ],
  10684. THREE.ShaderChunk[ "default_vertex" ],
  10685. THREE.ShaderChunk[ "worldpos_vertex" ],
  10686. THREE.ShaderChunk[ "envmap_vertex" ],
  10687. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10688. "}"
  10689. ].join("\n"),
  10690. fragmentShader: [
  10691. "uniform vec3 diffuse;",
  10692. "uniform float opacity;",
  10693. THREE.ShaderChunk[ "color_pars_fragment" ],
  10694. THREE.ShaderChunk[ "map_pars_fragment" ],
  10695. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10696. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10697. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10698. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10699. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10700. "void main() {",
  10701. "gl_FragColor = vec4( diffuse, opacity );",
  10702. THREE.ShaderChunk[ "map_fragment" ],
  10703. THREE.ShaderChunk[ "alphatest_fragment" ],
  10704. THREE.ShaderChunk[ "specularmap_fragment" ],
  10705. THREE.ShaderChunk[ "lightmap_fragment" ],
  10706. THREE.ShaderChunk[ "color_fragment" ],
  10707. THREE.ShaderChunk[ "envmap_fragment" ],
  10708. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10709. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10710. THREE.ShaderChunk[ "fog_fragment" ],
  10711. "}"
  10712. ].join("\n")
  10713. },
  10714. 'lambert': {
  10715. uniforms: THREE.UniformsUtils.merge( [
  10716. THREE.UniformsLib[ "common" ],
  10717. THREE.UniformsLib[ "fog" ],
  10718. THREE.UniformsLib[ "lights" ],
  10719. THREE.UniformsLib[ "shadowmap" ],
  10720. {
  10721. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10722. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10723. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10724. }
  10725. ] ),
  10726. vertexShader: [
  10727. "#define LAMBERT",
  10728. "varying vec3 vLightFront;",
  10729. "#ifdef DOUBLE_SIDED",
  10730. "varying vec3 vLightBack;",
  10731. "#endif",
  10732. THREE.ShaderChunk[ "map_pars_vertex" ],
  10733. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10734. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10735. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  10736. THREE.ShaderChunk[ "color_pars_vertex" ],
  10737. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10738. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10739. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10740. "void main() {",
  10741. THREE.ShaderChunk[ "map_vertex" ],
  10742. THREE.ShaderChunk[ "lightmap_vertex" ],
  10743. THREE.ShaderChunk[ "color_vertex" ],
  10744. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10745. THREE.ShaderChunk[ "skinbase_vertex" ],
  10746. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10747. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10748. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10749. THREE.ShaderChunk[ "skinning_vertex" ],
  10750. THREE.ShaderChunk[ "default_vertex" ],
  10751. THREE.ShaderChunk[ "worldpos_vertex" ],
  10752. THREE.ShaderChunk[ "envmap_vertex" ],
  10753. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  10754. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10755. "}"
  10756. ].join("\n"),
  10757. fragmentShader: [
  10758. "uniform float opacity;",
  10759. "varying vec3 vLightFront;",
  10760. "#ifdef DOUBLE_SIDED",
  10761. "varying vec3 vLightBack;",
  10762. "#endif",
  10763. THREE.ShaderChunk[ "color_pars_fragment" ],
  10764. THREE.ShaderChunk[ "map_pars_fragment" ],
  10765. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10766. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10767. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10768. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10769. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10770. "void main() {",
  10771. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10772. THREE.ShaderChunk[ "map_fragment" ],
  10773. THREE.ShaderChunk[ "alphatest_fragment" ],
  10774. THREE.ShaderChunk[ "specularmap_fragment" ],
  10775. "#ifdef DOUBLE_SIDED",
  10776. //"float isFront = float( gl_FrontFacing );",
  10777. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  10778. "if ( gl_FrontFacing )",
  10779. "gl_FragColor.xyz *= vLightFront;",
  10780. "else",
  10781. "gl_FragColor.xyz *= vLightBack;",
  10782. "#else",
  10783. "gl_FragColor.xyz *= vLightFront;",
  10784. "#endif",
  10785. THREE.ShaderChunk[ "lightmap_fragment" ],
  10786. THREE.ShaderChunk[ "color_fragment" ],
  10787. THREE.ShaderChunk[ "envmap_fragment" ],
  10788. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10789. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10790. THREE.ShaderChunk[ "fog_fragment" ],
  10791. "}"
  10792. ].join("\n")
  10793. },
  10794. 'phong': {
  10795. uniforms: THREE.UniformsUtils.merge( [
  10796. THREE.UniformsLib[ "common" ],
  10797. THREE.UniformsLib[ "bump" ],
  10798. THREE.UniformsLib[ "normalmap" ],
  10799. THREE.UniformsLib[ "fog" ],
  10800. THREE.UniformsLib[ "lights" ],
  10801. THREE.UniformsLib[ "shadowmap" ],
  10802. {
  10803. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10804. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10805. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  10806. "shininess": { type: "f", value: 30 },
  10807. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10808. }
  10809. ] ),
  10810. vertexShader: [
  10811. "#define PHONG",
  10812. "varying vec3 vViewPosition;",
  10813. "varying vec3 vNormal;",
  10814. THREE.ShaderChunk[ "map_pars_vertex" ],
  10815. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10816. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10817. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  10818. THREE.ShaderChunk[ "color_pars_vertex" ],
  10819. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10820. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10821. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10822. "void main() {",
  10823. THREE.ShaderChunk[ "map_vertex" ],
  10824. THREE.ShaderChunk[ "lightmap_vertex" ],
  10825. THREE.ShaderChunk[ "color_vertex" ],
  10826. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10827. THREE.ShaderChunk[ "skinbase_vertex" ],
  10828. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10829. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10830. "vNormal = normalize( transformedNormal );",
  10831. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10832. THREE.ShaderChunk[ "skinning_vertex" ],
  10833. THREE.ShaderChunk[ "default_vertex" ],
  10834. "vViewPosition = -mvPosition.xyz;",
  10835. THREE.ShaderChunk[ "worldpos_vertex" ],
  10836. THREE.ShaderChunk[ "envmap_vertex" ],
  10837. THREE.ShaderChunk[ "lights_phong_vertex" ],
  10838. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10839. "}"
  10840. ].join("\n"),
  10841. fragmentShader: [
  10842. "uniform vec3 diffuse;",
  10843. "uniform float opacity;",
  10844. "uniform vec3 ambient;",
  10845. "uniform vec3 emissive;",
  10846. "uniform vec3 specular;",
  10847. "uniform float shininess;",
  10848. THREE.ShaderChunk[ "color_pars_fragment" ],
  10849. THREE.ShaderChunk[ "map_pars_fragment" ],
  10850. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10851. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10852. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10853. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  10854. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10855. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  10856. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  10857. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10858. "void main() {",
  10859. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10860. THREE.ShaderChunk[ "map_fragment" ],
  10861. THREE.ShaderChunk[ "alphatest_fragment" ],
  10862. THREE.ShaderChunk[ "specularmap_fragment" ],
  10863. THREE.ShaderChunk[ "lights_phong_fragment" ],
  10864. THREE.ShaderChunk[ "lightmap_fragment" ],
  10865. THREE.ShaderChunk[ "color_fragment" ],
  10866. THREE.ShaderChunk[ "envmap_fragment" ],
  10867. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10868. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10869. THREE.ShaderChunk[ "fog_fragment" ],
  10870. "}"
  10871. ].join("\n")
  10872. },
  10873. 'particle_basic': {
  10874. uniforms: THREE.UniformsUtils.merge( [
  10875. THREE.UniformsLib[ "particle" ],
  10876. THREE.UniformsLib[ "shadowmap" ]
  10877. ] ),
  10878. vertexShader: [
  10879. "uniform float size;",
  10880. "uniform float scale;",
  10881. THREE.ShaderChunk[ "color_pars_vertex" ],
  10882. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10883. "void main() {",
  10884. THREE.ShaderChunk[ "color_vertex" ],
  10885. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10886. "#ifdef USE_SIZEATTENUATION",
  10887. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  10888. "#else",
  10889. "gl_PointSize = size;",
  10890. "#endif",
  10891. "gl_Position = projectionMatrix * mvPosition;",
  10892. THREE.ShaderChunk[ "worldpos_vertex" ],
  10893. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10894. "}"
  10895. ].join("\n"),
  10896. fragmentShader: [
  10897. "uniform vec3 psColor;",
  10898. "uniform float opacity;",
  10899. THREE.ShaderChunk[ "color_pars_fragment" ],
  10900. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  10901. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10902. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10903. "void main() {",
  10904. "gl_FragColor = vec4( psColor, opacity );",
  10905. THREE.ShaderChunk[ "map_particle_fragment" ],
  10906. THREE.ShaderChunk[ "alphatest_fragment" ],
  10907. THREE.ShaderChunk[ "color_fragment" ],
  10908. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10909. THREE.ShaderChunk[ "fog_fragment" ],
  10910. "}"
  10911. ].join("\n")
  10912. },
  10913. 'dashed': {
  10914. uniforms: THREE.UniformsUtils.merge( [
  10915. THREE.UniformsLib[ "common" ],
  10916. THREE.UniformsLib[ "fog" ],
  10917. {
  10918. "scale": { type: "f", value: 1 },
  10919. "dashSize": { type: "f", value: 1 },
  10920. "totalSize": { type: "f", value: 2 }
  10921. }
  10922. ] ),
  10923. vertexShader: [
  10924. "uniform float scale;",
  10925. "attribute float lineDistance;",
  10926. "varying float vLineDistance;",
  10927. THREE.ShaderChunk[ "color_pars_vertex" ],
  10928. "void main() {",
  10929. THREE.ShaderChunk[ "color_vertex" ],
  10930. "vLineDistance = scale * lineDistance;",
  10931. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10932. "gl_Position = projectionMatrix * mvPosition;",
  10933. "}"
  10934. ].join("\n"),
  10935. fragmentShader: [
  10936. "uniform vec3 diffuse;",
  10937. "uniform float opacity;",
  10938. "uniform float dashSize;",
  10939. "uniform float totalSize;",
  10940. "varying float vLineDistance;",
  10941. THREE.ShaderChunk[ "color_pars_fragment" ],
  10942. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10943. "void main() {",
  10944. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  10945. "discard;",
  10946. "}",
  10947. "gl_FragColor = vec4( diffuse, opacity );",
  10948. THREE.ShaderChunk[ "color_fragment" ],
  10949. THREE.ShaderChunk[ "fog_fragment" ],
  10950. "}"
  10951. ].join("\n")
  10952. },
  10953. 'depth': {
  10954. uniforms: {
  10955. "mNear": { type: "f", value: 1.0 },
  10956. "mFar" : { type: "f", value: 2000.0 },
  10957. "opacity" : { type: "f", value: 1.0 }
  10958. },
  10959. vertexShader: [
  10960. "void main() {",
  10961. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  10962. "}"
  10963. ].join("\n"),
  10964. fragmentShader: [
  10965. "uniform float mNear;",
  10966. "uniform float mFar;",
  10967. "uniform float opacity;",
  10968. "void main() {",
  10969. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  10970. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  10971. "gl_FragColor = vec4( vec3( color ), opacity );",
  10972. "}"
  10973. ].join("\n")
  10974. },
  10975. 'normal': {
  10976. uniforms: {
  10977. "opacity" : { type: "f", value: 1.0 }
  10978. },
  10979. vertexShader: [
  10980. "varying vec3 vNormal;",
  10981. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10982. "void main() {",
  10983. "vNormal = normalize( normalMatrix * normal );",
  10984. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10985. THREE.ShaderChunk[ "default_vertex" ],
  10986. "}"
  10987. ].join("\n"),
  10988. fragmentShader: [
  10989. "uniform float opacity;",
  10990. "varying vec3 vNormal;",
  10991. "void main() {",
  10992. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  10993. "}"
  10994. ].join("\n")
  10995. },
  10996. /* -------------------------------------------------------------------------
  10997. // Normal map shader
  10998. // - Blinn-Phong
  10999. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  11000. // - point and directional lights (use with "lights: true" material option)
  11001. ------------------------------------------------------------------------- */
  11002. 'normalmap' : {
  11003. uniforms: THREE.UniformsUtils.merge( [
  11004. THREE.UniformsLib[ "fog" ],
  11005. THREE.UniformsLib[ "lights" ],
  11006. THREE.UniformsLib[ "shadowmap" ],
  11007. {
  11008. "enableAO" : { type: "i", value: 0 },
  11009. "enableDiffuse" : { type: "i", value: 0 },
  11010. "enableSpecular" : { type: "i", value: 0 },
  11011. "enableReflection": { type: "i", value: 0 },
  11012. "enableDisplacement": { type: "i", value: 0 },
  11013. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  11014. "tDiffuse" : { type: "t", value: null },
  11015. "tCube" : { type: "t", value: null },
  11016. "tNormal" : { type: "t", value: null },
  11017. "tSpecular" : { type: "t", value: null },
  11018. "tAO" : { type: "t", value: null },
  11019. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11020. "uDisplacementBias": { type: "f", value: 0.0 },
  11021. "uDisplacementScale": { type: "f", value: 1.0 },
  11022. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  11023. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  11024. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  11025. "uShininess": { type: "f", value: 30 },
  11026. "uOpacity": { type: "f", value: 1 },
  11027. "useRefract": { type: "i", value: 0 },
  11028. "uRefractionRatio": { type: "f", value: 0.98 },
  11029. "uReflectivity": { type: "f", value: 0.5 },
  11030. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  11031. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11032. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11033. }
  11034. ] ),
  11035. fragmentShader: [
  11036. "uniform vec3 uAmbientColor;",
  11037. "uniform vec3 uDiffuseColor;",
  11038. "uniform vec3 uSpecularColor;",
  11039. "uniform float uShininess;",
  11040. "uniform float uOpacity;",
  11041. "uniform bool enableDiffuse;",
  11042. "uniform bool enableSpecular;",
  11043. "uniform bool enableAO;",
  11044. "uniform bool enableReflection;",
  11045. "uniform sampler2D tDiffuse;",
  11046. "uniform sampler2D tNormal;",
  11047. "uniform sampler2D tSpecular;",
  11048. "uniform sampler2D tAO;",
  11049. "uniform samplerCube tCube;",
  11050. "uniform vec2 uNormalScale;",
  11051. "uniform bool useRefract;",
  11052. "uniform float uRefractionRatio;",
  11053. "uniform float uReflectivity;",
  11054. "varying vec3 vTangent;",
  11055. "varying vec3 vBinormal;",
  11056. "varying vec3 vNormal;",
  11057. "varying vec2 vUv;",
  11058. "uniform vec3 ambientLightColor;",
  11059. "#if MAX_DIR_LIGHTS > 0",
  11060. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  11061. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  11062. "#endif",
  11063. "#if MAX_HEMI_LIGHTS > 0",
  11064. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  11065. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  11066. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  11067. "#endif",
  11068. "#if MAX_POINT_LIGHTS > 0",
  11069. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  11070. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  11071. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  11072. "#endif",
  11073. "#if MAX_SPOT_LIGHTS > 0",
  11074. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  11075. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  11076. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  11077. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  11078. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  11079. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  11080. "#endif",
  11081. "#ifdef WRAP_AROUND",
  11082. "uniform vec3 wrapRGB;",
  11083. "#endif",
  11084. "varying vec3 vWorldPosition;",
  11085. "varying vec3 vViewPosition;",
  11086. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11087. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11088. "void main() {",
  11089. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  11090. "vec3 specularTex = vec3( 1.0 );",
  11091. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  11092. "normalTex.xy *= uNormalScale;",
  11093. "normalTex = normalize( normalTex );",
  11094. "if( enableDiffuse ) {",
  11095. "#ifdef GAMMA_INPUT",
  11096. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  11097. "texelColor.xyz *= texelColor.xyz;",
  11098. "gl_FragColor = gl_FragColor * texelColor;",
  11099. "#else",
  11100. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  11101. "#endif",
  11102. "}",
  11103. "if( enableAO ) {",
  11104. "#ifdef GAMMA_INPUT",
  11105. "vec4 aoColor = texture2D( tAO, vUv );",
  11106. "aoColor.xyz *= aoColor.xyz;",
  11107. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  11108. "#else",
  11109. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  11110. "#endif",
  11111. "}",
  11112. "if( enableSpecular )",
  11113. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  11114. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  11115. "vec3 finalNormal = tsb * normalTex;",
  11116. "#ifdef FLIP_SIDED",
  11117. "finalNormal = -finalNormal;",
  11118. "#endif",
  11119. "vec3 normal = normalize( finalNormal );",
  11120. "vec3 viewPosition = normalize( vViewPosition );",
  11121. // point lights
  11122. "#if MAX_POINT_LIGHTS > 0",
  11123. "vec3 pointDiffuse = vec3( 0.0 );",
  11124. "vec3 pointSpecular = vec3( 0.0 );",
  11125. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  11126. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  11127. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  11128. "float pointDistance = 1.0;",
  11129. "if ( pointLightDistance[ i ] > 0.0 )",
  11130. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  11131. "pointVector = normalize( pointVector );",
  11132. // diffuse
  11133. "#ifdef WRAP_AROUND",
  11134. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  11135. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  11136. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  11137. "#else",
  11138. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  11139. "#endif",
  11140. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  11141. // specular
  11142. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  11143. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  11144. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  11145. "#ifdef PHYSICALLY_BASED_SHADING",
  11146. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11147. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11148. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  11149. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  11150. "#else",
  11151. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  11152. "#endif",
  11153. "}",
  11154. "#endif",
  11155. // spot lights
  11156. "#if MAX_SPOT_LIGHTS > 0",
  11157. "vec3 spotDiffuse = vec3( 0.0 );",
  11158. "vec3 spotSpecular = vec3( 0.0 );",
  11159. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  11160. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  11161. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  11162. "float spotDistance = 1.0;",
  11163. "if ( spotLightDistance[ i ] > 0.0 )",
  11164. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  11165. "spotVector = normalize( spotVector );",
  11166. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  11167. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  11168. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  11169. // diffuse
  11170. "#ifdef WRAP_AROUND",
  11171. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  11172. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  11173. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  11174. "#else",
  11175. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  11176. "#endif",
  11177. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  11178. // specular
  11179. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  11180. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  11181. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  11182. "#ifdef PHYSICALLY_BASED_SHADING",
  11183. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11184. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11185. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  11186. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  11187. "#else",
  11188. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  11189. "#endif",
  11190. "}",
  11191. "}",
  11192. "#endif",
  11193. // directional lights
  11194. "#if MAX_DIR_LIGHTS > 0",
  11195. "vec3 dirDiffuse = vec3( 0.0 );",
  11196. "vec3 dirSpecular = vec3( 0.0 );",
  11197. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  11198. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  11199. "vec3 dirVector = normalize( lDirection.xyz );",
  11200. // diffuse
  11201. "#ifdef WRAP_AROUND",
  11202. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  11203. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  11204. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  11205. "#else",
  11206. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  11207. "#endif",
  11208. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  11209. // specular
  11210. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  11211. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  11212. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  11213. "#ifdef PHYSICALLY_BASED_SHADING",
  11214. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11215. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11216. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  11217. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  11218. "#else",
  11219. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  11220. "#endif",
  11221. "}",
  11222. "#endif",
  11223. // hemisphere lights
  11224. "#if MAX_HEMI_LIGHTS > 0",
  11225. "vec3 hemiDiffuse = vec3( 0.0 );",
  11226. "vec3 hemiSpecular = vec3( 0.0 );" ,
  11227. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  11228. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  11229. "vec3 lVector = normalize( lDirection.xyz );",
  11230. // diffuse
  11231. "float dotProduct = dot( normal, lVector );",
  11232. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  11233. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  11234. "hemiDiffuse += uDiffuseColor * hemiColor;",
  11235. // specular (sky light)
  11236. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  11237. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  11238. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  11239. // specular (ground light)
  11240. "vec3 lVectorGround = -lVector;",
  11241. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  11242. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  11243. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  11244. "#ifdef PHYSICALLY_BASED_SHADING",
  11245. "float dotProductGround = dot( normal, lVectorGround );",
  11246. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11247. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11248. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  11249. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  11250. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  11251. "#else",
  11252. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  11253. "#endif",
  11254. "}",
  11255. "#endif",
  11256. // all lights contribution summation
  11257. "vec3 totalDiffuse = vec3( 0.0 );",
  11258. "vec3 totalSpecular = vec3( 0.0 );",
  11259. "#if MAX_DIR_LIGHTS > 0",
  11260. "totalDiffuse += dirDiffuse;",
  11261. "totalSpecular += dirSpecular;",
  11262. "#endif",
  11263. "#if MAX_HEMI_LIGHTS > 0",
  11264. "totalDiffuse += hemiDiffuse;",
  11265. "totalSpecular += hemiSpecular;",
  11266. "#endif",
  11267. "#if MAX_POINT_LIGHTS > 0",
  11268. "totalDiffuse += pointDiffuse;",
  11269. "totalSpecular += pointSpecular;",
  11270. "#endif",
  11271. "#if MAX_SPOT_LIGHTS > 0",
  11272. "totalDiffuse += spotDiffuse;",
  11273. "totalSpecular += spotSpecular;",
  11274. "#endif",
  11275. "#ifdef METAL",
  11276. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  11277. "#else",
  11278. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  11279. "#endif",
  11280. "if ( enableReflection ) {",
  11281. "vec3 vReflect;",
  11282. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  11283. "if ( useRefract ) {",
  11284. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  11285. "} else {",
  11286. "vReflect = reflect( cameraToVertex, normal );",
  11287. "}",
  11288. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  11289. "#ifdef GAMMA_INPUT",
  11290. "cubeColor.xyz *= cubeColor.xyz;",
  11291. "#endif",
  11292. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  11293. "}",
  11294. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11295. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11296. THREE.ShaderChunk[ "fog_fragment" ],
  11297. "}"
  11298. ].join("\n"),
  11299. vertexShader: [
  11300. "attribute vec4 tangent;",
  11301. "uniform vec2 uOffset;",
  11302. "uniform vec2 uRepeat;",
  11303. "uniform bool enableDisplacement;",
  11304. "#ifdef VERTEX_TEXTURES",
  11305. "uniform sampler2D tDisplacement;",
  11306. "uniform float uDisplacementScale;",
  11307. "uniform float uDisplacementBias;",
  11308. "#endif",
  11309. "varying vec3 vTangent;",
  11310. "varying vec3 vBinormal;",
  11311. "varying vec3 vNormal;",
  11312. "varying vec2 vUv;",
  11313. "varying vec3 vWorldPosition;",
  11314. "varying vec3 vViewPosition;",
  11315. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11316. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11317. "void main() {",
  11318. THREE.ShaderChunk[ "skinbase_vertex" ],
  11319. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11320. // normal, tangent and binormal vectors
  11321. "#ifdef USE_SKINNING",
  11322. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  11323. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  11324. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  11325. "#else",
  11326. "vNormal = normalize( normalMatrix * normal );",
  11327. "vTangent = normalize( normalMatrix * tangent.xyz );",
  11328. "#endif",
  11329. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  11330. "vUv = uv * uRepeat + uOffset;",
  11331. // displacement mapping
  11332. "vec3 displacedPosition;",
  11333. "#ifdef VERTEX_TEXTURES",
  11334. "if ( enableDisplacement ) {",
  11335. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  11336. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  11337. "displacedPosition = position + normalize( normal ) * df;",
  11338. "} else {",
  11339. "#ifdef USE_SKINNING",
  11340. "vec4 skinVertex = vec4( position, 1.0 );",
  11341. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11342. "skinned += boneMatY * skinVertex * skinWeight.y;",
  11343. "displacedPosition = skinned.xyz;",
  11344. "#else",
  11345. "displacedPosition = position;",
  11346. "#endif",
  11347. "}",
  11348. "#else",
  11349. "#ifdef USE_SKINNING",
  11350. "vec4 skinVertex = vec4( position, 1.0 );",
  11351. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11352. "skinned += boneMatY * skinVertex * skinWeight.y;",
  11353. "displacedPosition = skinned.xyz;",
  11354. "#else",
  11355. "displacedPosition = position;",
  11356. "#endif",
  11357. "#endif",
  11358. //
  11359. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  11360. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  11361. "gl_Position = projectionMatrix * mvPosition;",
  11362. //
  11363. "vWorldPosition = worldPosition.xyz;",
  11364. "vViewPosition = -mvPosition.xyz;",
  11365. // shadows
  11366. "#ifdef USE_SHADOWMAP",
  11367. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  11368. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  11369. "}",
  11370. "#endif",
  11371. "}"
  11372. ].join("\n")
  11373. },
  11374. /* -------------------------------------------------------------------------
  11375. // Cube map shader
  11376. ------------------------------------------------------------------------- */
  11377. 'cube': {
  11378. uniforms: { "tCube": { type: "t", value: null },
  11379. "tFlip": { type: "f", value: -1 } },
  11380. vertexShader: [
  11381. "varying vec3 vWorldPosition;",
  11382. "void main() {",
  11383. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  11384. "vWorldPosition = worldPosition.xyz;",
  11385. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11386. "}"
  11387. ].join("\n"),
  11388. fragmentShader: [
  11389. "uniform samplerCube tCube;",
  11390. "uniform float tFlip;",
  11391. "varying vec3 vWorldPosition;",
  11392. "void main() {",
  11393. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  11394. "}"
  11395. ].join("\n")
  11396. },
  11397. // Depth encoding into RGBA texture
  11398. // based on SpiderGL shadow map example
  11399. // http://spidergl.org/example.php?id=6
  11400. // originally from
  11401. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  11402. // see also here:
  11403. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  11404. 'depthRGBA': {
  11405. uniforms: {},
  11406. vertexShader: [
  11407. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11408. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11409. "void main() {",
  11410. THREE.ShaderChunk[ "skinbase_vertex" ],
  11411. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11412. THREE.ShaderChunk[ "skinning_vertex" ],
  11413. THREE.ShaderChunk[ "default_vertex" ],
  11414. "}"
  11415. ].join("\n"),
  11416. fragmentShader: [
  11417. "vec4 pack_depth( const in float depth ) {",
  11418. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  11419. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  11420. "vec4 res = fract( depth * bit_shift );",
  11421. "res -= res.xxyz * bit_mask;",
  11422. "return res;",
  11423. "}",
  11424. "void main() {",
  11425. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  11426. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  11427. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  11428. //"gl_FragData[ 0 ] = pack_depth( z );",
  11429. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  11430. "}"
  11431. ].join("\n")
  11432. }
  11433. };
  11434. /**
  11435. * @author supereggbert / http://www.paulbrunt.co.uk/
  11436. * @author mrdoob / http://mrdoob.com/
  11437. * @author alteredq / http://alteredqualia.com/
  11438. * @author szimek / https://github.com/szimek/
  11439. */
  11440. THREE.WebGLRenderer = function ( parameters ) {
  11441. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  11442. parameters = parameters || {};
  11443. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  11444. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  11445. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  11446. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  11447. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  11448. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  11449. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  11450. _clearColor = new THREE.Color( 0x000000 ),
  11451. _clearAlpha = 0;
  11452. if ( parameters.clearColor !== undefined ) {
  11453. console.warn( 'DEPRECATED: clearColor in WebGLRenderer constructor parameters is being removed. Use .setClearColor() instead.' );
  11454. _clearColor.setHex( parameters.clearColor );
  11455. }
  11456. if ( parameters.clearAlpha !== undefined ) {
  11457. console.warn( 'DEPRECATED: clearAlpha in WebGLRenderer constructor parameters is being removed. Use .setClearColor() instead.' );
  11458. _clearAlpha = parameters.clearAlpha;
  11459. }
  11460. // public properties
  11461. this.domElement = _canvas;
  11462. this.context = null;
  11463. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  11464. ? parameters.devicePixelRatio
  11465. : window.devicePixelRatio !== undefined
  11466. ? window.devicePixelRatio
  11467. : 1;
  11468. // clearing
  11469. this.autoClear = true;
  11470. this.autoClearColor = true;
  11471. this.autoClearDepth = true;
  11472. this.autoClearStencil = true;
  11473. // scene graph
  11474. this.sortObjects = true;
  11475. this.autoUpdateObjects = true;
  11476. // physically based shading
  11477. this.gammaInput = false;
  11478. this.gammaOutput = false;
  11479. this.physicallyBasedShading = false;
  11480. // shadow map
  11481. this.shadowMapEnabled = false;
  11482. this.shadowMapAutoUpdate = true;
  11483. this.shadowMapType = THREE.PCFShadowMap;
  11484. this.shadowMapCullFace = THREE.CullFaceFront;
  11485. this.shadowMapDebug = false;
  11486. this.shadowMapCascade = false;
  11487. // morphs
  11488. this.maxMorphTargets = 8;
  11489. this.maxMorphNormals = 4;
  11490. // flags
  11491. this.autoScaleCubemaps = true;
  11492. // custom render plugins
  11493. this.renderPluginsPre = [];
  11494. this.renderPluginsPost = [];
  11495. // info
  11496. this.info = {
  11497. memory: {
  11498. programs: 0,
  11499. geometries: 0,
  11500. textures: 0
  11501. },
  11502. render: {
  11503. calls: 0,
  11504. vertices: 0,
  11505. faces: 0,
  11506. points: 0
  11507. }
  11508. };
  11509. // internal properties
  11510. var _this = this,
  11511. _programs = [],
  11512. _programs_counter = 0,
  11513. // internal state cache
  11514. _currentProgram = null,
  11515. _currentFramebuffer = null,
  11516. _currentMaterialId = -1,
  11517. _currentGeometryGroupHash = null,
  11518. _currentCamera = null,
  11519. _geometryGroupCounter = 0,
  11520. _usedTextureUnits = 0,
  11521. // GL state cache
  11522. _oldDoubleSided = -1,
  11523. _oldFlipSided = -1,
  11524. _oldBlending = -1,
  11525. _oldBlendEquation = -1,
  11526. _oldBlendSrc = -1,
  11527. _oldBlendDst = -1,
  11528. _oldDepthTest = -1,
  11529. _oldDepthWrite = -1,
  11530. _oldPolygonOffset = null,
  11531. _oldPolygonOffsetFactor = null,
  11532. _oldPolygonOffsetUnits = null,
  11533. _oldLineWidth = null,
  11534. _viewportX = 0,
  11535. _viewportY = 0,
  11536. _viewportWidth = 0,
  11537. _viewportHeight = 0,
  11538. _currentWidth = 0,
  11539. _currentHeight = 0,
  11540. _enabledAttributes = {},
  11541. // frustum
  11542. _frustum = new THREE.Frustum(),
  11543. // camera matrices cache
  11544. _projScreenMatrix = new THREE.Matrix4(),
  11545. _projScreenMatrixPS = new THREE.Matrix4(),
  11546. _vector3 = new THREE.Vector3(),
  11547. // light arrays cache
  11548. _direction = new THREE.Vector3(),
  11549. _lightsNeedUpdate = true,
  11550. _lights = {
  11551. ambient: [ 0, 0, 0 ],
  11552. directional: { length: 0, colors: new Array(), positions: new Array() },
  11553. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  11554. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  11555. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  11556. };
  11557. // initialize
  11558. var _gl;
  11559. var _glExtensionTextureFloat;
  11560. var _glExtensionTextureFloatLinear;
  11561. var _glExtensionStandardDerivatives;
  11562. var _glExtensionTextureFilterAnisotropic;
  11563. var _glExtensionCompressedTextureS3TC;
  11564. initGL();
  11565. setDefaultGLState();
  11566. this.context = _gl;
  11567. // GPU capabilities
  11568. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  11569. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  11570. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  11571. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  11572. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  11573. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  11574. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  11575. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  11576. //
  11577. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  11578. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  11579. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  11580. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  11581. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  11582. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  11583. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  11584. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  11585. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  11586. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  11587. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  11588. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  11589. // clamp precision to maximum available
  11590. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  11591. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  11592. if ( _precision === "highp" && ! highpAvailable ) {
  11593. if ( mediumpAvailable ) {
  11594. _precision = "mediump";
  11595. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  11596. } else {
  11597. _precision = "lowp";
  11598. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  11599. }
  11600. }
  11601. if ( _precision === "mediump" && ! mediumpAvailable ) {
  11602. _precision = "lowp";
  11603. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  11604. }
  11605. // API
  11606. this.getContext = function () {
  11607. return _gl;
  11608. };
  11609. this.supportsVertexTextures = function () {
  11610. return _supportsVertexTextures;
  11611. };
  11612. this.supportsFloatTextures = function () {
  11613. return _glExtensionTextureFloat;
  11614. };
  11615. this.supportsStandardDerivatives = function () {
  11616. return _glExtensionStandardDerivatives;
  11617. };
  11618. this.supportsCompressedTextureS3TC = function () {
  11619. return _glExtensionCompressedTextureS3TC;
  11620. };
  11621. this.getMaxAnisotropy = function () {
  11622. return _maxAnisotropy;
  11623. };
  11624. this.getPrecision = function () {
  11625. return _precision;
  11626. };
  11627. this.setSize = function ( width, height, updateStyle ) {
  11628. _canvas.width = width * this.devicePixelRatio;
  11629. _canvas.height = height * this.devicePixelRatio;
  11630. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  11631. _canvas.style.width = width + 'px';
  11632. _canvas.style.height = height + 'px';
  11633. }
  11634. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  11635. };
  11636. this.setViewport = function ( x, y, width, height ) {
  11637. _viewportX = x !== undefined ? x : 0;
  11638. _viewportY = y !== undefined ? y : 0;
  11639. _viewportWidth = width !== undefined ? width : _canvas.width;
  11640. _viewportHeight = height !== undefined ? height : _canvas.height;
  11641. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  11642. };
  11643. this.setScissor = function ( x, y, width, height ) {
  11644. _gl.scissor( x, y, width, height );
  11645. };
  11646. this.enableScissorTest = function ( enable ) {
  11647. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  11648. };
  11649. // Clearing
  11650. this.setClearColor = function ( color, alpha ) {
  11651. _clearColor.set( color );
  11652. _clearAlpha = alpha !== undefined ? alpha : 1;
  11653. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11654. };
  11655. this.setClearColorHex = function ( hex, alpha ) {
  11656. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  11657. this.setClearColor( hex, alpha );
  11658. };
  11659. this.getClearColor = function () {
  11660. return _clearColor;
  11661. };
  11662. this.getClearAlpha = function () {
  11663. return _clearAlpha;
  11664. };
  11665. this.clear = function ( color, depth, stencil ) {
  11666. var bits = 0;
  11667. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  11668. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  11669. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  11670. _gl.clear( bits );
  11671. };
  11672. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  11673. this.setRenderTarget( renderTarget );
  11674. this.clear( color, depth, stencil );
  11675. };
  11676. // Plugins
  11677. this.addPostPlugin = function ( plugin ) {
  11678. plugin.init( this );
  11679. this.renderPluginsPost.push( plugin );
  11680. };
  11681. this.addPrePlugin = function ( plugin ) {
  11682. plugin.init( this );
  11683. this.renderPluginsPre.push( plugin );
  11684. };
  11685. // Rendering
  11686. this.updateShadowMap = function ( scene, camera ) {
  11687. _currentProgram = null;
  11688. _oldBlending = -1;
  11689. _oldDepthTest = -1;
  11690. _oldDepthWrite = -1;
  11691. _currentGeometryGroupHash = -1;
  11692. _currentMaterialId = -1;
  11693. _lightsNeedUpdate = true;
  11694. _oldDoubleSided = -1;
  11695. _oldFlipSided = -1;
  11696. this.shadowMapPlugin.update( scene, camera );
  11697. };
  11698. // Internal functions
  11699. // Buffer allocation
  11700. function createParticleBuffers ( geometry ) {
  11701. geometry.__webglVertexBuffer = _gl.createBuffer();
  11702. geometry.__webglColorBuffer = _gl.createBuffer();
  11703. _this.info.memory.geometries ++;
  11704. };
  11705. function createLineBuffers ( geometry ) {
  11706. geometry.__webglVertexBuffer = _gl.createBuffer();
  11707. geometry.__webglColorBuffer = _gl.createBuffer();
  11708. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  11709. _this.info.memory.geometries ++;
  11710. };
  11711. function createRibbonBuffers ( geometry ) {
  11712. geometry.__webglVertexBuffer = _gl.createBuffer();
  11713. geometry.__webglColorBuffer = _gl.createBuffer();
  11714. geometry.__webglNormalBuffer = _gl.createBuffer();
  11715. _this.info.memory.geometries ++;
  11716. };
  11717. function createMeshBuffers ( geometryGroup ) {
  11718. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  11719. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  11720. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  11721. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  11722. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  11723. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  11724. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  11725. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  11726. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  11727. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  11728. var m, ml;
  11729. if ( geometryGroup.numMorphTargets ) {
  11730. geometryGroup.__webglMorphTargetsBuffers = [];
  11731. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11732. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  11733. }
  11734. }
  11735. if ( geometryGroup.numMorphNormals ) {
  11736. geometryGroup.__webglMorphNormalsBuffers = [];
  11737. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11738. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  11739. }
  11740. }
  11741. _this.info.memory.geometries ++;
  11742. };
  11743. // Events
  11744. var onGeometryDispose = function ( event ) {
  11745. var geometry = event.target;
  11746. geometry.removeEventListener( 'dispose', onGeometryDispose );
  11747. deallocateGeometry( geometry );
  11748. _this.info.memory.geometries --;
  11749. };
  11750. var onTextureDispose = function ( event ) {
  11751. var texture = event.target;
  11752. texture.removeEventListener( 'dispose', onTextureDispose );
  11753. deallocateTexture( texture );
  11754. _this.info.memory.textures --;
  11755. };
  11756. var onRenderTargetDispose = function ( event ) {
  11757. var renderTarget = event.target;
  11758. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  11759. deallocateRenderTarget( renderTarget );
  11760. _this.info.memory.textures --;
  11761. };
  11762. var onMaterialDispose = function ( event ) {
  11763. var material = event.target;
  11764. material.removeEventListener( 'dispose', onMaterialDispose );
  11765. deallocateMaterial( material );
  11766. };
  11767. // Buffer deallocation
  11768. var deallocateGeometry = function ( geometry ) {
  11769. geometry.__webglInit = undefined;
  11770. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  11771. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  11772. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  11773. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  11774. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  11775. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  11776. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  11777. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  11778. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  11779. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  11780. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  11781. // geometry groups
  11782. if ( geometry.geometryGroups !== undefined ) {
  11783. for ( var g in geometry.geometryGroups ) {
  11784. var geometryGroup = geometry.geometryGroups[ g ];
  11785. if ( geometryGroup.numMorphTargets !== undefined ) {
  11786. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11787. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  11788. }
  11789. }
  11790. if ( geometryGroup.numMorphNormals !== undefined ) {
  11791. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11792. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  11793. }
  11794. }
  11795. deleteCustomAttributesBuffers( geometryGroup );
  11796. }
  11797. }
  11798. deleteCustomAttributesBuffers( geometry );
  11799. };
  11800. var deallocateTexture = function ( texture ) {
  11801. if ( texture.image && texture.image.__webglTextureCube ) {
  11802. // cube texture
  11803. _gl.deleteTexture( texture.image.__webglTextureCube );
  11804. } else {
  11805. // 2D texture
  11806. if ( ! texture.__webglInit ) return;
  11807. texture.__webglInit = false;
  11808. _gl.deleteTexture( texture.__webglTexture );
  11809. }
  11810. };
  11811. var deallocateRenderTarget = function ( renderTarget ) {
  11812. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  11813. _gl.deleteTexture( renderTarget.__webglTexture );
  11814. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  11815. for ( var i = 0; i < 6; i ++ ) {
  11816. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  11817. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  11818. }
  11819. } else {
  11820. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  11821. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  11822. }
  11823. };
  11824. var deallocateMaterial = function ( material ) {
  11825. var program = material.program;
  11826. if ( program === undefined ) return;
  11827. material.program = undefined;
  11828. // only deallocate GL program if this was the last use of shared program
  11829. // assumed there is only single copy of any program in the _programs list
  11830. // (that's how it's constructed)
  11831. var i, il, programInfo;
  11832. var deleteProgram = false;
  11833. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11834. programInfo = _programs[ i ];
  11835. if ( programInfo.program === program ) {
  11836. programInfo.usedTimes --;
  11837. if ( programInfo.usedTimes === 0 ) {
  11838. deleteProgram = true;
  11839. }
  11840. break;
  11841. }
  11842. }
  11843. if ( deleteProgram === true ) {
  11844. // avoid using array.splice, this is costlier than creating new array from scratch
  11845. var newPrograms = [];
  11846. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11847. programInfo = _programs[ i ];
  11848. if ( programInfo.program !== program ) {
  11849. newPrograms.push( programInfo );
  11850. }
  11851. }
  11852. _programs = newPrograms;
  11853. _gl.deleteProgram( program );
  11854. _this.info.memory.programs --;
  11855. }
  11856. };
  11857. //
  11858. function deleteCustomAttributesBuffers( geometry ) {
  11859. if ( geometry.__webglCustomAttributesList ) {
  11860. for ( var id in geometry.__webglCustomAttributesList ) {
  11861. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  11862. }
  11863. }
  11864. };
  11865. // Buffer initialization
  11866. function initCustomAttributes ( geometry, object ) {
  11867. var nvertices = geometry.vertices.length;
  11868. var material = object.material;
  11869. if ( material.attributes ) {
  11870. if ( geometry.__webglCustomAttributesList === undefined ) {
  11871. geometry.__webglCustomAttributesList = [];
  11872. }
  11873. for ( var a in material.attributes ) {
  11874. var attribute = material.attributes[ a ];
  11875. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  11876. attribute.__webglInitialized = true;
  11877. var size = 1; // "f" and "i"
  11878. if ( attribute.type === "v2" ) size = 2;
  11879. else if ( attribute.type === "v3" ) size = 3;
  11880. else if ( attribute.type === "v4" ) size = 4;
  11881. else if ( attribute.type === "c" ) size = 3;
  11882. attribute.size = size;
  11883. attribute.array = new Float32Array( nvertices * size );
  11884. attribute.buffer = _gl.createBuffer();
  11885. attribute.buffer.belongsToAttribute = a;
  11886. attribute.needsUpdate = true;
  11887. }
  11888. geometry.__webglCustomAttributesList.push( attribute );
  11889. }
  11890. }
  11891. };
  11892. function initParticleBuffers ( geometry, object ) {
  11893. var nvertices = geometry.vertices.length;
  11894. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11895. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11896. geometry.__sortArray = [];
  11897. geometry.__webglParticleCount = nvertices;
  11898. initCustomAttributes ( geometry, object );
  11899. };
  11900. function initLineBuffers ( geometry, object ) {
  11901. var nvertices = geometry.vertices.length;
  11902. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11903. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11904. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  11905. geometry.__webglLineCount = nvertices;
  11906. initCustomAttributes ( geometry, object );
  11907. };
  11908. function initRibbonBuffers ( geometry, object ) {
  11909. var nvertices = geometry.vertices.length;
  11910. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11911. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11912. geometry.__normalArray = new Float32Array( nvertices * 3 );
  11913. geometry.__webglVertexCount = nvertices;
  11914. initCustomAttributes ( geometry, object );
  11915. };
  11916. function initMeshBuffers ( geometryGroup, object ) {
  11917. var geometry = object.geometry,
  11918. faces3 = geometryGroup.faces3,
  11919. faces4 = geometryGroup.faces4,
  11920. nvertices = faces3.length * 3 + faces4.length * 4,
  11921. ntris = faces3.length * 1 + faces4.length * 2,
  11922. nlines = faces3.length * 3 + faces4.length * 4,
  11923. material = getBufferMaterial( object, geometryGroup ),
  11924. uvType = bufferGuessUVType( material ),
  11925. normalType = bufferGuessNormalType( material ),
  11926. vertexColorType = bufferGuessVertexColorType( material );
  11927. // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  11928. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  11929. if ( normalType ) {
  11930. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  11931. }
  11932. if ( geometry.hasTangents ) {
  11933. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  11934. }
  11935. if ( vertexColorType ) {
  11936. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  11937. }
  11938. if ( uvType ) {
  11939. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  11940. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  11941. }
  11942. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  11943. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  11944. }
  11945. }
  11946. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  11947. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  11948. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  11949. }
  11950. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  11951. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  11952. var m, ml;
  11953. if ( geometryGroup.numMorphTargets ) {
  11954. geometryGroup.__morphTargetsArrays = [];
  11955. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11956. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  11957. }
  11958. }
  11959. if ( geometryGroup.numMorphNormals ) {
  11960. geometryGroup.__morphNormalsArrays = [];
  11961. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11962. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  11963. }
  11964. }
  11965. geometryGroup.__webglFaceCount = ntris * 3;
  11966. geometryGroup.__webglLineCount = nlines * 2;
  11967. // custom attributes
  11968. if ( material.attributes ) {
  11969. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  11970. geometryGroup.__webglCustomAttributesList = [];
  11971. }
  11972. for ( var a in material.attributes ) {
  11973. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  11974. // attribute buffers which are correctly indexed in the setMeshBuffers function
  11975. var originalAttribute = material.attributes[ a ];
  11976. var attribute = {};
  11977. for ( var property in originalAttribute ) {
  11978. attribute[ property ] = originalAttribute[ property ];
  11979. }
  11980. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  11981. attribute.__webglInitialized = true;
  11982. var size = 1; // "f" and "i"
  11983. if( attribute.type === "v2" ) size = 2;
  11984. else if( attribute.type === "v3" ) size = 3;
  11985. else if( attribute.type === "v4" ) size = 4;
  11986. else if( attribute.type === "c" ) size = 3;
  11987. attribute.size = size;
  11988. attribute.array = new Float32Array( nvertices * size );
  11989. attribute.buffer = _gl.createBuffer();
  11990. attribute.buffer.belongsToAttribute = a;
  11991. originalAttribute.needsUpdate = true;
  11992. attribute.__original = originalAttribute;
  11993. }
  11994. geometryGroup.__webglCustomAttributesList.push( attribute );
  11995. }
  11996. }
  11997. geometryGroup.__inittedArrays = true;
  11998. };
  11999. function getBufferMaterial( object, geometryGroup ) {
  12000. return object.material instanceof THREE.MeshFaceMaterial
  12001. ? object.material.materials[ geometryGroup.materialIndex ]
  12002. : object.material;
  12003. };
  12004. function materialNeedsSmoothNormals ( material ) {
  12005. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  12006. };
  12007. function bufferGuessNormalType ( material ) {
  12008. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  12009. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  12010. return false;
  12011. }
  12012. if ( materialNeedsSmoothNormals( material ) ) {
  12013. return THREE.SmoothShading;
  12014. } else {
  12015. return THREE.FlatShading;
  12016. }
  12017. };
  12018. function bufferGuessVertexColorType( material ) {
  12019. if ( material.vertexColors ) {
  12020. return material.vertexColors;
  12021. }
  12022. return false;
  12023. };
  12024. function bufferGuessUVType( material ) {
  12025. // material must use some texture to require uvs
  12026. if ( material.map ||
  12027. material.lightMap ||
  12028. material.bumpMap ||
  12029. material.normalMap ||
  12030. material.specularMap ||
  12031. material instanceof THREE.ShaderMaterial ) {
  12032. return true;
  12033. }
  12034. return false;
  12035. };
  12036. //
  12037. function initDirectBuffers( geometry ) {
  12038. var a, attribute, type;
  12039. for ( a in geometry.attributes ) {
  12040. if ( a === "index" ) {
  12041. type = _gl.ELEMENT_ARRAY_BUFFER;
  12042. } else {
  12043. type = _gl.ARRAY_BUFFER;
  12044. }
  12045. attribute = geometry.attributes[ a ];
  12046. if ( attribute.numItems === undefined ) {
  12047. attribute.numItems = attribute.array.length;
  12048. }
  12049. attribute.buffer = _gl.createBuffer();
  12050. _gl.bindBuffer( type, attribute.buffer );
  12051. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  12052. }
  12053. };
  12054. // Buffer setting
  12055. function setParticleBuffers ( geometry, hint, object ) {
  12056. var v, c, vertex, offset, index, color,
  12057. vertices = geometry.vertices,
  12058. vl = vertices.length,
  12059. colors = geometry.colors,
  12060. cl = colors.length,
  12061. vertexArray = geometry.__vertexArray,
  12062. colorArray = geometry.__colorArray,
  12063. sortArray = geometry.__sortArray,
  12064. dirtyVertices = geometry.verticesNeedUpdate,
  12065. dirtyElements = geometry.elementsNeedUpdate,
  12066. dirtyColors = geometry.colorsNeedUpdate,
  12067. customAttributes = geometry.__webglCustomAttributesList,
  12068. i, il,
  12069. a, ca, cal, value,
  12070. customAttribute;
  12071. if ( object.sortParticles ) {
  12072. _projScreenMatrixPS.copy( _projScreenMatrix );
  12073. _projScreenMatrixPS.multiply( object.matrixWorld );
  12074. for ( v = 0; v < vl; v ++ ) {
  12075. vertex = vertices[ v ];
  12076. _vector3.copy( vertex );
  12077. _vector3.applyProjection( _projScreenMatrixPS );
  12078. sortArray[ v ] = [ _vector3.z, v ];
  12079. }
  12080. sortArray.sort( numericalSort );
  12081. for ( v = 0; v < vl; v ++ ) {
  12082. vertex = vertices[ sortArray[v][1] ];
  12083. offset = v * 3;
  12084. vertexArray[ offset ] = vertex.x;
  12085. vertexArray[ offset + 1 ] = vertex.y;
  12086. vertexArray[ offset + 2 ] = vertex.z;
  12087. }
  12088. for ( c = 0; c < cl; c ++ ) {
  12089. offset = c * 3;
  12090. color = colors[ sortArray[c][1] ];
  12091. colorArray[ offset ] = color.r;
  12092. colorArray[ offset + 1 ] = color.g;
  12093. colorArray[ offset + 2 ] = color.b;
  12094. }
  12095. if ( customAttributes ) {
  12096. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12097. customAttribute = customAttributes[ i ];
  12098. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  12099. offset = 0;
  12100. cal = customAttribute.value.length;
  12101. if ( customAttribute.size === 1 ) {
  12102. for ( ca = 0; ca < cal; ca ++ ) {
  12103. index = sortArray[ ca ][ 1 ];
  12104. customAttribute.array[ ca ] = customAttribute.value[ index ];
  12105. }
  12106. } else if ( customAttribute.size === 2 ) {
  12107. for ( ca = 0; ca < cal; ca ++ ) {
  12108. index = sortArray[ ca ][ 1 ];
  12109. value = customAttribute.value[ index ];
  12110. customAttribute.array[ offset ] = value.x;
  12111. customAttribute.array[ offset + 1 ] = value.y;
  12112. offset += 2;
  12113. }
  12114. } else if ( customAttribute.size === 3 ) {
  12115. if ( customAttribute.type === "c" ) {
  12116. for ( ca = 0; ca < cal; ca ++ ) {
  12117. index = sortArray[ ca ][ 1 ];
  12118. value = customAttribute.value[ index ];
  12119. customAttribute.array[ offset ] = value.r;
  12120. customAttribute.array[ offset + 1 ] = value.g;
  12121. customAttribute.array[ offset + 2 ] = value.b;
  12122. offset += 3;
  12123. }
  12124. } else {
  12125. for ( ca = 0; ca < cal; ca ++ ) {
  12126. index = sortArray[ ca ][ 1 ];
  12127. value = customAttribute.value[ index ];
  12128. customAttribute.array[ offset ] = value.x;
  12129. customAttribute.array[ offset + 1 ] = value.y;
  12130. customAttribute.array[ offset + 2 ] = value.z;
  12131. offset += 3;
  12132. }
  12133. }
  12134. } else if ( customAttribute.size === 4 ) {
  12135. for ( ca = 0; ca < cal; ca ++ ) {
  12136. index = sortArray[ ca ][ 1 ];
  12137. value = customAttribute.value[ index ];
  12138. customAttribute.array[ offset ] = value.x;
  12139. customAttribute.array[ offset + 1 ] = value.y;
  12140. customAttribute.array[ offset + 2 ] = value.z;
  12141. customAttribute.array[ offset + 3 ] = value.w;
  12142. offset += 4;
  12143. }
  12144. }
  12145. }
  12146. }
  12147. } else {
  12148. if ( dirtyVertices ) {
  12149. for ( v = 0; v < vl; v ++ ) {
  12150. vertex = vertices[ v ];
  12151. offset = v * 3;
  12152. vertexArray[ offset ] = vertex.x;
  12153. vertexArray[ offset + 1 ] = vertex.y;
  12154. vertexArray[ offset + 2 ] = vertex.z;
  12155. }
  12156. }
  12157. if ( dirtyColors ) {
  12158. for ( c = 0; c < cl; c ++ ) {
  12159. color = colors[ c ];
  12160. offset = c * 3;
  12161. colorArray[ offset ] = color.r;
  12162. colorArray[ offset + 1 ] = color.g;
  12163. colorArray[ offset + 2 ] = color.b;
  12164. }
  12165. }
  12166. if ( customAttributes ) {
  12167. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12168. customAttribute = customAttributes[ i ];
  12169. if ( customAttribute.needsUpdate &&
  12170. ( customAttribute.boundTo === undefined ||
  12171. customAttribute.boundTo === "vertices") ) {
  12172. cal = customAttribute.value.length;
  12173. offset = 0;
  12174. if ( customAttribute.size === 1 ) {
  12175. for ( ca = 0; ca < cal; ca ++ ) {
  12176. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12177. }
  12178. } else if ( customAttribute.size === 2 ) {
  12179. for ( ca = 0; ca < cal; ca ++ ) {
  12180. value = customAttribute.value[ ca ];
  12181. customAttribute.array[ offset ] = value.x;
  12182. customAttribute.array[ offset + 1 ] = value.y;
  12183. offset += 2;
  12184. }
  12185. } else if ( customAttribute.size === 3 ) {
  12186. if ( customAttribute.type === "c" ) {
  12187. for ( ca = 0; ca < cal; ca ++ ) {
  12188. value = customAttribute.value[ ca ];
  12189. customAttribute.array[ offset ] = value.r;
  12190. customAttribute.array[ offset + 1 ] = value.g;
  12191. customAttribute.array[ offset + 2 ] = value.b;
  12192. offset += 3;
  12193. }
  12194. } else {
  12195. for ( ca = 0; ca < cal; ca ++ ) {
  12196. value = customAttribute.value[ ca ];
  12197. customAttribute.array[ offset ] = value.x;
  12198. customAttribute.array[ offset + 1 ] = value.y;
  12199. customAttribute.array[ offset + 2 ] = value.z;
  12200. offset += 3;
  12201. }
  12202. }
  12203. } else if ( customAttribute.size === 4 ) {
  12204. for ( ca = 0; ca < cal; ca ++ ) {
  12205. value = customAttribute.value[ ca ];
  12206. customAttribute.array[ offset ] = value.x;
  12207. customAttribute.array[ offset + 1 ] = value.y;
  12208. customAttribute.array[ offset + 2 ] = value.z;
  12209. customAttribute.array[ offset + 3 ] = value.w;
  12210. offset += 4;
  12211. }
  12212. }
  12213. }
  12214. }
  12215. }
  12216. }
  12217. if ( dirtyVertices || object.sortParticles ) {
  12218. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12219. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12220. }
  12221. if ( dirtyColors || object.sortParticles ) {
  12222. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12223. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12224. }
  12225. if ( customAttributes ) {
  12226. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12227. customAttribute = customAttributes[ i ];
  12228. if ( customAttribute.needsUpdate || object.sortParticles ) {
  12229. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12230. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12231. }
  12232. }
  12233. }
  12234. };
  12235. function setLineBuffers ( geometry, hint ) {
  12236. var v, c, d, vertex, offset, color,
  12237. vertices = geometry.vertices,
  12238. colors = geometry.colors,
  12239. lineDistances = geometry.lineDistances,
  12240. vl = vertices.length,
  12241. cl = colors.length,
  12242. dl = lineDistances.length,
  12243. vertexArray = geometry.__vertexArray,
  12244. colorArray = geometry.__colorArray,
  12245. lineDistanceArray = geometry.__lineDistanceArray,
  12246. dirtyVertices = geometry.verticesNeedUpdate,
  12247. dirtyColors = geometry.colorsNeedUpdate,
  12248. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  12249. customAttributes = geometry.__webglCustomAttributesList,
  12250. i, il,
  12251. a, ca, cal, value,
  12252. customAttribute;
  12253. if ( dirtyVertices ) {
  12254. for ( v = 0; v < vl; v ++ ) {
  12255. vertex = vertices[ v ];
  12256. offset = v * 3;
  12257. vertexArray[ offset ] = vertex.x;
  12258. vertexArray[ offset + 1 ] = vertex.y;
  12259. vertexArray[ offset + 2 ] = vertex.z;
  12260. }
  12261. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12262. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12263. }
  12264. if ( dirtyColors ) {
  12265. for ( c = 0; c < cl; c ++ ) {
  12266. color = colors[ c ];
  12267. offset = c * 3;
  12268. colorArray[ offset ] = color.r;
  12269. colorArray[ offset + 1 ] = color.g;
  12270. colorArray[ offset + 2 ] = color.b;
  12271. }
  12272. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12273. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12274. }
  12275. if ( dirtyLineDistances ) {
  12276. for ( d = 0; d < dl; d ++ ) {
  12277. lineDistanceArray[ d ] = lineDistances[ d ];
  12278. }
  12279. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  12280. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  12281. }
  12282. if ( customAttributes ) {
  12283. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12284. customAttribute = customAttributes[ i ];
  12285. if ( customAttribute.needsUpdate &&
  12286. ( customAttribute.boundTo === undefined ||
  12287. customAttribute.boundTo === "vertices" ) ) {
  12288. offset = 0;
  12289. cal = customAttribute.value.length;
  12290. if ( customAttribute.size === 1 ) {
  12291. for ( ca = 0; ca < cal; ca ++ ) {
  12292. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12293. }
  12294. } else if ( customAttribute.size === 2 ) {
  12295. for ( ca = 0; ca < cal; ca ++ ) {
  12296. value = customAttribute.value[ ca ];
  12297. customAttribute.array[ offset ] = value.x;
  12298. customAttribute.array[ offset + 1 ] = value.y;
  12299. offset += 2;
  12300. }
  12301. } else if ( customAttribute.size === 3 ) {
  12302. if ( customAttribute.type === "c" ) {
  12303. for ( ca = 0; ca < cal; ca ++ ) {
  12304. value = customAttribute.value[ ca ];
  12305. customAttribute.array[ offset ] = value.r;
  12306. customAttribute.array[ offset + 1 ] = value.g;
  12307. customAttribute.array[ offset + 2 ] = value.b;
  12308. offset += 3;
  12309. }
  12310. } else {
  12311. for ( ca = 0; ca < cal; ca ++ ) {
  12312. value = customAttribute.value[ ca ];
  12313. customAttribute.array[ offset ] = value.x;
  12314. customAttribute.array[ offset + 1 ] = value.y;
  12315. customAttribute.array[ offset + 2 ] = value.z;
  12316. offset += 3;
  12317. }
  12318. }
  12319. } else if ( customAttribute.size === 4 ) {
  12320. for ( ca = 0; ca < cal; ca ++ ) {
  12321. value = customAttribute.value[ ca ];
  12322. customAttribute.array[ offset ] = value.x;
  12323. customAttribute.array[ offset + 1 ] = value.y;
  12324. customAttribute.array[ offset + 2 ] = value.z;
  12325. customAttribute.array[ offset + 3 ] = value.w;
  12326. offset += 4;
  12327. }
  12328. }
  12329. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12330. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12331. }
  12332. }
  12333. }
  12334. };
  12335. function setRibbonBuffers ( geometry, hint ) {
  12336. var v, c, n, vertex, offset, color, normal,
  12337. i, il, ca, cal, customAttribute, value,
  12338. vertices = geometry.vertices,
  12339. colors = geometry.colors,
  12340. normals = geometry.normals,
  12341. vl = vertices.length,
  12342. cl = colors.length,
  12343. nl = normals.length,
  12344. vertexArray = geometry.__vertexArray,
  12345. colorArray = geometry.__colorArray,
  12346. normalArray = geometry.__normalArray,
  12347. dirtyVertices = geometry.verticesNeedUpdate,
  12348. dirtyColors = geometry.colorsNeedUpdate,
  12349. dirtyNormals = geometry.normalsNeedUpdate,
  12350. customAttributes = geometry.__webglCustomAttributesList;
  12351. if ( dirtyVertices ) {
  12352. for ( v = 0; v < vl; v ++ ) {
  12353. vertex = vertices[ v ];
  12354. offset = v * 3;
  12355. vertexArray[ offset ] = vertex.x;
  12356. vertexArray[ offset + 1 ] = vertex.y;
  12357. vertexArray[ offset + 2 ] = vertex.z;
  12358. }
  12359. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12360. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12361. }
  12362. if ( dirtyColors ) {
  12363. for ( c = 0; c < cl; c ++ ) {
  12364. color = colors[ c ];
  12365. offset = c * 3;
  12366. colorArray[ offset ] = color.r;
  12367. colorArray[ offset + 1 ] = color.g;
  12368. colorArray[ offset + 2 ] = color.b;
  12369. }
  12370. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12371. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12372. }
  12373. if ( dirtyNormals ) {
  12374. for ( n = 0; n < nl; n ++ ) {
  12375. normal = normals[ n ];
  12376. offset = n * 3;
  12377. normalArray[ offset ] = normal.x;
  12378. normalArray[ offset + 1 ] = normal.y;
  12379. normalArray[ offset + 2 ] = normal.z;
  12380. }
  12381. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglNormalBuffer );
  12382. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  12383. }
  12384. if ( customAttributes ) {
  12385. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12386. customAttribute = customAttributes[ i ];
  12387. if ( customAttribute.needsUpdate &&
  12388. ( customAttribute.boundTo === undefined ||
  12389. customAttribute.boundTo === "vertices" ) ) {
  12390. offset = 0;
  12391. cal = customAttribute.value.length;
  12392. if ( customAttribute.size === 1 ) {
  12393. for ( ca = 0; ca < cal; ca ++ ) {
  12394. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12395. }
  12396. } else if ( customAttribute.size === 2 ) {
  12397. for ( ca = 0; ca < cal; ca ++ ) {
  12398. value = customAttribute.value[ ca ];
  12399. customAttribute.array[ offset ] = value.x;
  12400. customAttribute.array[ offset + 1 ] = value.y;
  12401. offset += 2;
  12402. }
  12403. } else if ( customAttribute.size === 3 ) {
  12404. if ( customAttribute.type === "c" ) {
  12405. for ( ca = 0; ca < cal; ca ++ ) {
  12406. value = customAttribute.value[ ca ];
  12407. customAttribute.array[ offset ] = value.r;
  12408. customAttribute.array[ offset + 1 ] = value.g;
  12409. customAttribute.array[ offset + 2 ] = value.b;
  12410. offset += 3;
  12411. }
  12412. } else {
  12413. for ( ca = 0; ca < cal; ca ++ ) {
  12414. value = customAttribute.value[ ca ];
  12415. customAttribute.array[ offset ] = value.x;
  12416. customAttribute.array[ offset + 1 ] = value.y;
  12417. customAttribute.array[ offset + 2 ] = value.z;
  12418. offset += 3;
  12419. }
  12420. }
  12421. } else if ( customAttribute.size === 4 ) {
  12422. for ( ca = 0; ca < cal; ca ++ ) {
  12423. value = customAttribute.value[ ca ];
  12424. customAttribute.array[ offset ] = value.x;
  12425. customAttribute.array[ offset + 1 ] = value.y;
  12426. customAttribute.array[ offset + 2 ] = value.z;
  12427. customAttribute.array[ offset + 3 ] = value.w;
  12428. offset += 4;
  12429. }
  12430. }
  12431. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12432. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12433. }
  12434. }
  12435. }
  12436. };
  12437. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  12438. if ( ! geometryGroup.__inittedArrays ) {
  12439. return;
  12440. }
  12441. var normalType = bufferGuessNormalType( material ),
  12442. vertexColorType = bufferGuessVertexColorType( material ),
  12443. uvType = bufferGuessUVType( material ),
  12444. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  12445. var f, fl, fi, face,
  12446. vertexNormals, faceNormal, normal,
  12447. vertexColors, faceColor,
  12448. vertexTangents,
  12449. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  12450. c1, c2, c3, c4,
  12451. sw1, sw2, sw3, sw4,
  12452. si1, si2, si3, si4,
  12453. sa1, sa2, sa3, sa4,
  12454. sb1, sb2, sb3, sb4,
  12455. m, ml, i, il,
  12456. vn, uvi, uv2i,
  12457. vk, vkl, vka,
  12458. nka, chf, faceVertexNormals,
  12459. a,
  12460. vertexIndex = 0,
  12461. offset = 0,
  12462. offset_uv = 0,
  12463. offset_uv2 = 0,
  12464. offset_face = 0,
  12465. offset_normal = 0,
  12466. offset_tangent = 0,
  12467. offset_line = 0,
  12468. offset_color = 0,
  12469. offset_skin = 0,
  12470. offset_morphTarget = 0,
  12471. offset_custom = 0,
  12472. offset_customSrc = 0,
  12473. value,
  12474. vertexArray = geometryGroup.__vertexArray,
  12475. uvArray = geometryGroup.__uvArray,
  12476. uv2Array = geometryGroup.__uv2Array,
  12477. normalArray = geometryGroup.__normalArray,
  12478. tangentArray = geometryGroup.__tangentArray,
  12479. colorArray = geometryGroup.__colorArray,
  12480. skinIndexArray = geometryGroup.__skinIndexArray,
  12481. skinWeightArray = geometryGroup.__skinWeightArray,
  12482. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  12483. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  12484. customAttributes = geometryGroup.__webglCustomAttributesList,
  12485. customAttribute,
  12486. faceArray = geometryGroup.__faceArray,
  12487. lineArray = geometryGroup.__lineArray,
  12488. geometry = object.geometry, // this is shared for all chunks
  12489. dirtyVertices = geometry.verticesNeedUpdate,
  12490. dirtyElements = geometry.elementsNeedUpdate,
  12491. dirtyUvs = geometry.uvsNeedUpdate,
  12492. dirtyNormals = geometry.normalsNeedUpdate,
  12493. dirtyTangents = geometry.tangentsNeedUpdate,
  12494. dirtyColors = geometry.colorsNeedUpdate,
  12495. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  12496. vertices = geometry.vertices,
  12497. chunk_faces3 = geometryGroup.faces3,
  12498. chunk_faces4 = geometryGroup.faces4,
  12499. obj_faces = geometry.faces,
  12500. obj_uvs = geometry.faceVertexUvs[ 0 ],
  12501. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  12502. obj_colors = geometry.colors,
  12503. obj_skinIndices = geometry.skinIndices,
  12504. obj_skinWeights = geometry.skinWeights,
  12505. morphTargets = geometry.morphTargets,
  12506. morphNormals = geometry.morphNormals;
  12507. if ( dirtyVertices ) {
  12508. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12509. face = obj_faces[ chunk_faces3[ f ] ];
  12510. v1 = vertices[ face.a ];
  12511. v2 = vertices[ face.b ];
  12512. v3 = vertices[ face.c ];
  12513. vertexArray[ offset ] = v1.x;
  12514. vertexArray[ offset + 1 ] = v1.y;
  12515. vertexArray[ offset + 2 ] = v1.z;
  12516. vertexArray[ offset + 3 ] = v2.x;
  12517. vertexArray[ offset + 4 ] = v2.y;
  12518. vertexArray[ offset + 5 ] = v2.z;
  12519. vertexArray[ offset + 6 ] = v3.x;
  12520. vertexArray[ offset + 7 ] = v3.y;
  12521. vertexArray[ offset + 8 ] = v3.z;
  12522. offset += 9;
  12523. }
  12524. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12525. face = obj_faces[ chunk_faces4[ f ] ];
  12526. v1 = vertices[ face.a ];
  12527. v2 = vertices[ face.b ];
  12528. v3 = vertices[ face.c ];
  12529. v4 = vertices[ face.d ];
  12530. vertexArray[ offset ] = v1.x;
  12531. vertexArray[ offset + 1 ] = v1.y;
  12532. vertexArray[ offset + 2 ] = v1.z;
  12533. vertexArray[ offset + 3 ] = v2.x;
  12534. vertexArray[ offset + 4 ] = v2.y;
  12535. vertexArray[ offset + 5 ] = v2.z;
  12536. vertexArray[ offset + 6 ] = v3.x;
  12537. vertexArray[ offset + 7 ] = v3.y;
  12538. vertexArray[ offset + 8 ] = v3.z;
  12539. vertexArray[ offset + 9 ] = v4.x;
  12540. vertexArray[ offset + 10 ] = v4.y;
  12541. vertexArray[ offset + 11 ] = v4.z;
  12542. offset += 12;
  12543. }
  12544. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12545. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12546. }
  12547. if ( dirtyMorphTargets ) {
  12548. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  12549. offset_morphTarget = 0;
  12550. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12551. chf = chunk_faces3[ f ];
  12552. face = obj_faces[ chf ];
  12553. // morph positions
  12554. v1 = morphTargets[ vk ].vertices[ face.a ];
  12555. v2 = morphTargets[ vk ].vertices[ face.b ];
  12556. v3 = morphTargets[ vk ].vertices[ face.c ];
  12557. vka = morphTargetsArrays[ vk ];
  12558. vka[ offset_morphTarget ] = v1.x;
  12559. vka[ offset_morphTarget + 1 ] = v1.y;
  12560. vka[ offset_morphTarget + 2 ] = v1.z;
  12561. vka[ offset_morphTarget + 3 ] = v2.x;
  12562. vka[ offset_morphTarget + 4 ] = v2.y;
  12563. vka[ offset_morphTarget + 5 ] = v2.z;
  12564. vka[ offset_morphTarget + 6 ] = v3.x;
  12565. vka[ offset_morphTarget + 7 ] = v3.y;
  12566. vka[ offset_morphTarget + 8 ] = v3.z;
  12567. // morph normals
  12568. if ( material.morphNormals ) {
  12569. if ( needsSmoothNormals ) {
  12570. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  12571. n1 = faceVertexNormals.a;
  12572. n2 = faceVertexNormals.b;
  12573. n3 = faceVertexNormals.c;
  12574. } else {
  12575. n1 = morphNormals[ vk ].faceNormals[ chf ];
  12576. n2 = n1;
  12577. n3 = n1;
  12578. }
  12579. nka = morphNormalsArrays[ vk ];
  12580. nka[ offset_morphTarget ] = n1.x;
  12581. nka[ offset_morphTarget + 1 ] = n1.y;
  12582. nka[ offset_morphTarget + 2 ] = n1.z;
  12583. nka[ offset_morphTarget + 3 ] = n2.x;
  12584. nka[ offset_morphTarget + 4 ] = n2.y;
  12585. nka[ offset_morphTarget + 5 ] = n2.z;
  12586. nka[ offset_morphTarget + 6 ] = n3.x;
  12587. nka[ offset_morphTarget + 7 ] = n3.y;
  12588. nka[ offset_morphTarget + 8 ] = n3.z;
  12589. }
  12590. //
  12591. offset_morphTarget += 9;
  12592. }
  12593. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12594. chf = chunk_faces4[ f ];
  12595. face = obj_faces[ chf ];
  12596. // morph positions
  12597. v1 = morphTargets[ vk ].vertices[ face.a ];
  12598. v2 = morphTargets[ vk ].vertices[ face.b ];
  12599. v3 = morphTargets[ vk ].vertices[ face.c ];
  12600. v4 = morphTargets[ vk ].vertices[ face.d ];
  12601. vka = morphTargetsArrays[ vk ];
  12602. vka[ offset_morphTarget ] = v1.x;
  12603. vka[ offset_morphTarget + 1 ] = v1.y;
  12604. vka[ offset_morphTarget + 2 ] = v1.z;
  12605. vka[ offset_morphTarget + 3 ] = v2.x;
  12606. vka[ offset_morphTarget + 4 ] = v2.y;
  12607. vka[ offset_morphTarget + 5 ] = v2.z;
  12608. vka[ offset_morphTarget + 6 ] = v3.x;
  12609. vka[ offset_morphTarget + 7 ] = v3.y;
  12610. vka[ offset_morphTarget + 8 ] = v3.z;
  12611. vka[ offset_morphTarget + 9 ] = v4.x;
  12612. vka[ offset_morphTarget + 10 ] = v4.y;
  12613. vka[ offset_morphTarget + 11 ] = v4.z;
  12614. // morph normals
  12615. if ( material.morphNormals ) {
  12616. if ( needsSmoothNormals ) {
  12617. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  12618. n1 = faceVertexNormals.a;
  12619. n2 = faceVertexNormals.b;
  12620. n3 = faceVertexNormals.c;
  12621. n4 = faceVertexNormals.d;
  12622. } else {
  12623. n1 = morphNormals[ vk ].faceNormals[ chf ];
  12624. n2 = n1;
  12625. n3 = n1;
  12626. n4 = n1;
  12627. }
  12628. nka = morphNormalsArrays[ vk ];
  12629. nka[ offset_morphTarget ] = n1.x;
  12630. nka[ offset_morphTarget + 1 ] = n1.y;
  12631. nka[ offset_morphTarget + 2 ] = n1.z;
  12632. nka[ offset_morphTarget + 3 ] = n2.x;
  12633. nka[ offset_morphTarget + 4 ] = n2.y;
  12634. nka[ offset_morphTarget + 5 ] = n2.z;
  12635. nka[ offset_morphTarget + 6 ] = n3.x;
  12636. nka[ offset_morphTarget + 7 ] = n3.y;
  12637. nka[ offset_morphTarget + 8 ] = n3.z;
  12638. nka[ offset_morphTarget + 9 ] = n4.x;
  12639. nka[ offset_morphTarget + 10 ] = n4.y;
  12640. nka[ offset_morphTarget + 11 ] = n4.z;
  12641. }
  12642. //
  12643. offset_morphTarget += 12;
  12644. }
  12645. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  12646. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  12647. if ( material.morphNormals ) {
  12648. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  12649. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  12650. }
  12651. }
  12652. }
  12653. if ( obj_skinWeights.length ) {
  12654. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12655. face = obj_faces[ chunk_faces3[ f ] ];
  12656. // weights
  12657. sw1 = obj_skinWeights[ face.a ];
  12658. sw2 = obj_skinWeights[ face.b ];
  12659. sw3 = obj_skinWeights[ face.c ];
  12660. skinWeightArray[ offset_skin ] = sw1.x;
  12661. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  12662. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  12663. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  12664. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  12665. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  12666. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  12667. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  12668. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  12669. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  12670. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  12671. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  12672. // indices
  12673. si1 = obj_skinIndices[ face.a ];
  12674. si2 = obj_skinIndices[ face.b ];
  12675. si3 = obj_skinIndices[ face.c ];
  12676. skinIndexArray[ offset_skin ] = si1.x;
  12677. skinIndexArray[ offset_skin + 1 ] = si1.y;
  12678. skinIndexArray[ offset_skin + 2 ] = si1.z;
  12679. skinIndexArray[ offset_skin + 3 ] = si1.w;
  12680. skinIndexArray[ offset_skin + 4 ] = si2.x;
  12681. skinIndexArray[ offset_skin + 5 ] = si2.y;
  12682. skinIndexArray[ offset_skin + 6 ] = si2.z;
  12683. skinIndexArray[ offset_skin + 7 ] = si2.w;
  12684. skinIndexArray[ offset_skin + 8 ] = si3.x;
  12685. skinIndexArray[ offset_skin + 9 ] = si3.y;
  12686. skinIndexArray[ offset_skin + 10 ] = si3.z;
  12687. skinIndexArray[ offset_skin + 11 ] = si3.w;
  12688. offset_skin += 12;
  12689. }
  12690. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12691. face = obj_faces[ chunk_faces4[ f ] ];
  12692. // weights
  12693. sw1 = obj_skinWeights[ face.a ];
  12694. sw2 = obj_skinWeights[ face.b ];
  12695. sw3 = obj_skinWeights[ face.c ];
  12696. sw4 = obj_skinWeights[ face.d ];
  12697. skinWeightArray[ offset_skin ] = sw1.x;
  12698. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  12699. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  12700. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  12701. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  12702. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  12703. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  12704. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  12705. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  12706. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  12707. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  12708. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  12709. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  12710. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  12711. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  12712. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  12713. // indices
  12714. si1 = obj_skinIndices[ face.a ];
  12715. si2 = obj_skinIndices[ face.b ];
  12716. si3 = obj_skinIndices[ face.c ];
  12717. si4 = obj_skinIndices[ face.d ];
  12718. skinIndexArray[ offset_skin ] = si1.x;
  12719. skinIndexArray[ offset_skin + 1 ] = si1.y;
  12720. skinIndexArray[ offset_skin + 2 ] = si1.z;
  12721. skinIndexArray[ offset_skin + 3 ] = si1.w;
  12722. skinIndexArray[ offset_skin + 4 ] = si2.x;
  12723. skinIndexArray[ offset_skin + 5 ] = si2.y;
  12724. skinIndexArray[ offset_skin + 6 ] = si2.z;
  12725. skinIndexArray[ offset_skin + 7 ] = si2.w;
  12726. skinIndexArray[ offset_skin + 8 ] = si3.x;
  12727. skinIndexArray[ offset_skin + 9 ] = si3.y;
  12728. skinIndexArray[ offset_skin + 10 ] = si3.z;
  12729. skinIndexArray[ offset_skin + 11 ] = si3.w;
  12730. skinIndexArray[ offset_skin + 12 ] = si4.x;
  12731. skinIndexArray[ offset_skin + 13 ] = si4.y;
  12732. skinIndexArray[ offset_skin + 14 ] = si4.z;
  12733. skinIndexArray[ offset_skin + 15 ] = si4.w;
  12734. offset_skin += 16;
  12735. }
  12736. if ( offset_skin > 0 ) {
  12737. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  12738. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  12739. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  12740. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  12741. }
  12742. }
  12743. if ( dirtyColors && vertexColorType ) {
  12744. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12745. face = obj_faces[ chunk_faces3[ f ] ];
  12746. vertexColors = face.vertexColors;
  12747. faceColor = face.color;
  12748. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  12749. c1 = vertexColors[ 0 ];
  12750. c2 = vertexColors[ 1 ];
  12751. c3 = vertexColors[ 2 ];
  12752. } else {
  12753. c1 = faceColor;
  12754. c2 = faceColor;
  12755. c3 = faceColor;
  12756. }
  12757. colorArray[ offset_color ] = c1.r;
  12758. colorArray[ offset_color + 1 ] = c1.g;
  12759. colorArray[ offset_color + 2 ] = c1.b;
  12760. colorArray[ offset_color + 3 ] = c2.r;
  12761. colorArray[ offset_color + 4 ] = c2.g;
  12762. colorArray[ offset_color + 5 ] = c2.b;
  12763. colorArray[ offset_color + 6 ] = c3.r;
  12764. colorArray[ offset_color + 7 ] = c3.g;
  12765. colorArray[ offset_color + 8 ] = c3.b;
  12766. offset_color += 9;
  12767. }
  12768. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12769. face = obj_faces[ chunk_faces4[ f ] ];
  12770. vertexColors = face.vertexColors;
  12771. faceColor = face.color;
  12772. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  12773. c1 = vertexColors[ 0 ];
  12774. c2 = vertexColors[ 1 ];
  12775. c3 = vertexColors[ 2 ];
  12776. c4 = vertexColors[ 3 ];
  12777. } else {
  12778. c1 = faceColor;
  12779. c2 = faceColor;
  12780. c3 = faceColor;
  12781. c4 = faceColor;
  12782. }
  12783. colorArray[ offset_color ] = c1.r;
  12784. colorArray[ offset_color + 1 ] = c1.g;
  12785. colorArray[ offset_color + 2 ] = c1.b;
  12786. colorArray[ offset_color + 3 ] = c2.r;
  12787. colorArray[ offset_color + 4 ] = c2.g;
  12788. colorArray[ offset_color + 5 ] = c2.b;
  12789. colorArray[ offset_color + 6 ] = c3.r;
  12790. colorArray[ offset_color + 7 ] = c3.g;
  12791. colorArray[ offset_color + 8 ] = c3.b;
  12792. colorArray[ offset_color + 9 ] = c4.r;
  12793. colorArray[ offset_color + 10 ] = c4.g;
  12794. colorArray[ offset_color + 11 ] = c4.b;
  12795. offset_color += 12;
  12796. }
  12797. if ( offset_color > 0 ) {
  12798. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12799. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12800. }
  12801. }
  12802. if ( dirtyTangents && geometry.hasTangents ) {
  12803. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12804. face = obj_faces[ chunk_faces3[ f ] ];
  12805. vertexTangents = face.vertexTangents;
  12806. t1 = vertexTangents[ 0 ];
  12807. t2 = vertexTangents[ 1 ];
  12808. t3 = vertexTangents[ 2 ];
  12809. tangentArray[ offset_tangent ] = t1.x;
  12810. tangentArray[ offset_tangent + 1 ] = t1.y;
  12811. tangentArray[ offset_tangent + 2 ] = t1.z;
  12812. tangentArray[ offset_tangent + 3 ] = t1.w;
  12813. tangentArray[ offset_tangent + 4 ] = t2.x;
  12814. tangentArray[ offset_tangent + 5 ] = t2.y;
  12815. tangentArray[ offset_tangent + 6 ] = t2.z;
  12816. tangentArray[ offset_tangent + 7 ] = t2.w;
  12817. tangentArray[ offset_tangent + 8 ] = t3.x;
  12818. tangentArray[ offset_tangent + 9 ] = t3.y;
  12819. tangentArray[ offset_tangent + 10 ] = t3.z;
  12820. tangentArray[ offset_tangent + 11 ] = t3.w;
  12821. offset_tangent += 12;
  12822. }
  12823. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12824. face = obj_faces[ chunk_faces4[ f ] ];
  12825. vertexTangents = face.vertexTangents;
  12826. t1 = vertexTangents[ 0 ];
  12827. t2 = vertexTangents[ 1 ];
  12828. t3 = vertexTangents[ 2 ];
  12829. t4 = vertexTangents[ 3 ];
  12830. tangentArray[ offset_tangent ] = t1.x;
  12831. tangentArray[ offset_tangent + 1 ] = t1.y;
  12832. tangentArray[ offset_tangent + 2 ] = t1.z;
  12833. tangentArray[ offset_tangent + 3 ] = t1.w;
  12834. tangentArray[ offset_tangent + 4 ] = t2.x;
  12835. tangentArray[ offset_tangent + 5 ] = t2.y;
  12836. tangentArray[ offset_tangent + 6 ] = t2.z;
  12837. tangentArray[ offset_tangent + 7 ] = t2.w;
  12838. tangentArray[ offset_tangent + 8 ] = t3.x;
  12839. tangentArray[ offset_tangent + 9 ] = t3.y;
  12840. tangentArray[ offset_tangent + 10 ] = t3.z;
  12841. tangentArray[ offset_tangent + 11 ] = t3.w;
  12842. tangentArray[ offset_tangent + 12 ] = t4.x;
  12843. tangentArray[ offset_tangent + 13 ] = t4.y;
  12844. tangentArray[ offset_tangent + 14 ] = t4.z;
  12845. tangentArray[ offset_tangent + 15 ] = t4.w;
  12846. offset_tangent += 16;
  12847. }
  12848. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12849. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  12850. }
  12851. if ( dirtyNormals && normalType ) {
  12852. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12853. face = obj_faces[ chunk_faces3[ f ] ];
  12854. vertexNormals = face.vertexNormals;
  12855. faceNormal = face.normal;
  12856. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  12857. for ( i = 0; i < 3; i ++ ) {
  12858. vn = vertexNormals[ i ];
  12859. normalArray[ offset_normal ] = vn.x;
  12860. normalArray[ offset_normal + 1 ] = vn.y;
  12861. normalArray[ offset_normal + 2 ] = vn.z;
  12862. offset_normal += 3;
  12863. }
  12864. } else {
  12865. for ( i = 0; i < 3; i ++ ) {
  12866. normalArray[ offset_normal ] = faceNormal.x;
  12867. normalArray[ offset_normal + 1 ] = faceNormal.y;
  12868. normalArray[ offset_normal + 2 ] = faceNormal.z;
  12869. offset_normal += 3;
  12870. }
  12871. }
  12872. }
  12873. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12874. face = obj_faces[ chunk_faces4[ f ] ];
  12875. vertexNormals = face.vertexNormals;
  12876. faceNormal = face.normal;
  12877. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  12878. for ( i = 0; i < 4; i ++ ) {
  12879. vn = vertexNormals[ i ];
  12880. normalArray[ offset_normal ] = vn.x;
  12881. normalArray[ offset_normal + 1 ] = vn.y;
  12882. normalArray[ offset_normal + 2 ] = vn.z;
  12883. offset_normal += 3;
  12884. }
  12885. } else {
  12886. for ( i = 0; i < 4; i ++ ) {
  12887. normalArray[ offset_normal ] = faceNormal.x;
  12888. normalArray[ offset_normal + 1 ] = faceNormal.y;
  12889. normalArray[ offset_normal + 2 ] = faceNormal.z;
  12890. offset_normal += 3;
  12891. }
  12892. }
  12893. }
  12894. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12895. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  12896. }
  12897. if ( dirtyUvs && obj_uvs && uvType ) {
  12898. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12899. fi = chunk_faces3[ f ];
  12900. uv = obj_uvs[ fi ];
  12901. if ( uv === undefined ) continue;
  12902. for ( i = 0; i < 3; i ++ ) {
  12903. uvi = uv[ i ];
  12904. uvArray[ offset_uv ] = uvi.x;
  12905. uvArray[ offset_uv + 1 ] = uvi.y;
  12906. offset_uv += 2;
  12907. }
  12908. }
  12909. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12910. fi = chunk_faces4[ f ];
  12911. uv = obj_uvs[ fi ];
  12912. if ( uv === undefined ) continue;
  12913. for ( i = 0; i < 4; i ++ ) {
  12914. uvi = uv[ i ];
  12915. uvArray[ offset_uv ] = uvi.x;
  12916. uvArray[ offset_uv + 1 ] = uvi.y;
  12917. offset_uv += 2;
  12918. }
  12919. }
  12920. if ( offset_uv > 0 ) {
  12921. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12922. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  12923. }
  12924. }
  12925. if ( dirtyUvs && obj_uvs2 && uvType ) {
  12926. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12927. fi = chunk_faces3[ f ];
  12928. uv2 = obj_uvs2[ fi ];
  12929. if ( uv2 === undefined ) continue;
  12930. for ( i = 0; i < 3; i ++ ) {
  12931. uv2i = uv2[ i ];
  12932. uv2Array[ offset_uv2 ] = uv2i.x;
  12933. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  12934. offset_uv2 += 2;
  12935. }
  12936. }
  12937. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12938. fi = chunk_faces4[ f ];
  12939. uv2 = obj_uvs2[ fi ];
  12940. if ( uv2 === undefined ) continue;
  12941. for ( i = 0; i < 4; i ++ ) {
  12942. uv2i = uv2[ i ];
  12943. uv2Array[ offset_uv2 ] = uv2i.x;
  12944. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  12945. offset_uv2 += 2;
  12946. }
  12947. }
  12948. if ( offset_uv2 > 0 ) {
  12949. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12950. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  12951. }
  12952. }
  12953. if ( dirtyElements ) {
  12954. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12955. faceArray[ offset_face ] = vertexIndex;
  12956. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12957. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  12958. offset_face += 3;
  12959. lineArray[ offset_line ] = vertexIndex;
  12960. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  12961. lineArray[ offset_line + 2 ] = vertexIndex;
  12962. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  12963. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  12964. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  12965. offset_line += 6;
  12966. vertexIndex += 3;
  12967. }
  12968. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12969. faceArray[ offset_face ] = vertexIndex;
  12970. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12971. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  12972. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  12973. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  12974. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  12975. offset_face += 6;
  12976. lineArray[ offset_line ] = vertexIndex;
  12977. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  12978. lineArray[ offset_line + 2 ] = vertexIndex;
  12979. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  12980. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  12981. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  12982. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  12983. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  12984. offset_line += 8;
  12985. vertexIndex += 4;
  12986. }
  12987. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12988. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  12989. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  12990. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  12991. }
  12992. if ( customAttributes ) {
  12993. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12994. customAttribute = customAttributes[ i ];
  12995. if ( ! customAttribute.__original.needsUpdate ) continue;
  12996. offset_custom = 0;
  12997. offset_customSrc = 0;
  12998. if ( customAttribute.size === 1 ) {
  12999. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13000. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13001. face = obj_faces[ chunk_faces3[ f ] ];
  13002. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  13003. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  13004. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  13005. offset_custom += 3;
  13006. }
  13007. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13008. face = obj_faces[ chunk_faces4[ f ] ];
  13009. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  13010. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  13011. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  13012. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  13013. offset_custom += 4;
  13014. }
  13015. } else if ( customAttribute.boundTo === "faces" ) {
  13016. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13017. value = customAttribute.value[ chunk_faces3[ f ] ];
  13018. customAttribute.array[ offset_custom ] = value;
  13019. customAttribute.array[ offset_custom + 1 ] = value;
  13020. customAttribute.array[ offset_custom + 2 ] = value;
  13021. offset_custom += 3;
  13022. }
  13023. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13024. value = customAttribute.value[ chunk_faces4[ f ] ];
  13025. customAttribute.array[ offset_custom ] = value;
  13026. customAttribute.array[ offset_custom + 1 ] = value;
  13027. customAttribute.array[ offset_custom + 2 ] = value;
  13028. customAttribute.array[ offset_custom + 3 ] = value;
  13029. offset_custom += 4;
  13030. }
  13031. }
  13032. } else if ( customAttribute.size === 2 ) {
  13033. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13034. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13035. face = obj_faces[ chunk_faces3[ f ] ];
  13036. v1 = customAttribute.value[ face.a ];
  13037. v2 = customAttribute.value[ face.b ];
  13038. v3 = customAttribute.value[ face.c ];
  13039. customAttribute.array[ offset_custom ] = v1.x;
  13040. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13041. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13042. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13043. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13044. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13045. offset_custom += 6;
  13046. }
  13047. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13048. face = obj_faces[ chunk_faces4[ f ] ];
  13049. v1 = customAttribute.value[ face.a ];
  13050. v2 = customAttribute.value[ face.b ];
  13051. v3 = customAttribute.value[ face.c ];
  13052. v4 = customAttribute.value[ face.d ];
  13053. customAttribute.array[ offset_custom ] = v1.x;
  13054. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13055. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13056. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13057. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13058. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13059. customAttribute.array[ offset_custom + 6 ] = v4.x;
  13060. customAttribute.array[ offset_custom + 7 ] = v4.y;
  13061. offset_custom += 8;
  13062. }
  13063. } else if ( customAttribute.boundTo === "faces" ) {
  13064. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13065. value = customAttribute.value[ chunk_faces3[ f ] ];
  13066. v1 = value;
  13067. v2 = value;
  13068. v3 = value;
  13069. customAttribute.array[ offset_custom ] = v1.x;
  13070. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13071. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13072. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13073. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13074. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13075. offset_custom += 6;
  13076. }
  13077. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13078. value = customAttribute.value[ chunk_faces4[ f ] ];
  13079. v1 = value;
  13080. v2 = value;
  13081. v3 = value;
  13082. v4 = value;
  13083. customAttribute.array[ offset_custom ] = v1.x;
  13084. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13085. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13086. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13087. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13088. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13089. customAttribute.array[ offset_custom + 6 ] = v4.x;
  13090. customAttribute.array[ offset_custom + 7 ] = v4.y;
  13091. offset_custom += 8;
  13092. }
  13093. }
  13094. } else if ( customAttribute.size === 3 ) {
  13095. var pp;
  13096. if ( customAttribute.type === "c" ) {
  13097. pp = [ "r", "g", "b" ];
  13098. } else {
  13099. pp = [ "x", "y", "z" ];
  13100. }
  13101. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13102. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13103. face = obj_faces[ chunk_faces3[ f ] ];
  13104. v1 = customAttribute.value[ face.a ];
  13105. v2 = customAttribute.value[ face.b ];
  13106. v3 = customAttribute.value[ face.c ];
  13107. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13108. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13109. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13110. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13111. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13112. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13113. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13114. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13115. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13116. offset_custom += 9;
  13117. }
  13118. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13119. face = obj_faces[ chunk_faces4[ f ] ];
  13120. v1 = customAttribute.value[ face.a ];
  13121. v2 = customAttribute.value[ face.b ];
  13122. v3 = customAttribute.value[ face.c ];
  13123. v4 = customAttribute.value[ face.d ];
  13124. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13125. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13126. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13127. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13128. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13129. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13130. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13131. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13132. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13133. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  13134. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  13135. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  13136. offset_custom += 12;
  13137. }
  13138. } else if ( customAttribute.boundTo === "faces" ) {
  13139. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13140. value = customAttribute.value[ chunk_faces3[ f ] ];
  13141. v1 = value;
  13142. v2 = value;
  13143. v3 = value;
  13144. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13145. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13146. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13147. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13148. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13149. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13150. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13151. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13152. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13153. offset_custom += 9;
  13154. }
  13155. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13156. value = customAttribute.value[ chunk_faces4[ f ] ];
  13157. v1 = value;
  13158. v2 = value;
  13159. v3 = value;
  13160. v4 = value;
  13161. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13162. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13163. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13164. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13165. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13166. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13167. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13168. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13169. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13170. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  13171. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  13172. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  13173. offset_custom += 12;
  13174. }
  13175. } else if ( customAttribute.boundTo === "faceVertices" ) {
  13176. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13177. value = customAttribute.value[ chunk_faces3[ f ] ];
  13178. v1 = value[ 0 ];
  13179. v2 = value[ 1 ];
  13180. v3 = value[ 2 ];
  13181. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13182. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13183. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13184. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13185. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13186. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13187. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13188. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13189. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13190. offset_custom += 9;
  13191. }
  13192. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13193. value = customAttribute.value[ chunk_faces4[ f ] ];
  13194. v1 = value[ 0 ];
  13195. v2 = value[ 1 ];
  13196. v3 = value[ 2 ];
  13197. v4 = value[ 3 ];
  13198. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13199. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13200. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13201. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13202. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13203. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13204. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13205. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13206. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13207. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  13208. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  13209. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  13210. offset_custom += 12;
  13211. }
  13212. }
  13213. } else if ( customAttribute.size === 4 ) {
  13214. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13215. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13216. face = obj_faces[ chunk_faces3[ f ] ];
  13217. v1 = customAttribute.value[ face.a ];
  13218. v2 = customAttribute.value[ face.b ];
  13219. v3 = customAttribute.value[ face.c ];
  13220. customAttribute.array[ offset_custom ] = v1.x;
  13221. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13222. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13223. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13224. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13225. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13226. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13227. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13228. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13229. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13230. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13231. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13232. offset_custom += 12;
  13233. }
  13234. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13235. face = obj_faces[ chunk_faces4[ f ] ];
  13236. v1 = customAttribute.value[ face.a ];
  13237. v2 = customAttribute.value[ face.b ];
  13238. v3 = customAttribute.value[ face.c ];
  13239. v4 = customAttribute.value[ face.d ];
  13240. customAttribute.array[ offset_custom ] = v1.x;
  13241. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13242. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13243. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13244. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13245. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13246. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13247. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13248. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13249. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13250. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13251. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13252. customAttribute.array[ offset_custom + 12 ] = v4.x;
  13253. customAttribute.array[ offset_custom + 13 ] = v4.y;
  13254. customAttribute.array[ offset_custom + 14 ] = v4.z;
  13255. customAttribute.array[ offset_custom + 15 ] = v4.w;
  13256. offset_custom += 16;
  13257. }
  13258. } else if ( customAttribute.boundTo === "faces" ) {
  13259. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13260. value = customAttribute.value[ chunk_faces3[ f ] ];
  13261. v1 = value;
  13262. v2 = value;
  13263. v3 = value;
  13264. customAttribute.array[ offset_custom ] = v1.x;
  13265. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13266. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13267. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13268. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13269. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13270. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13271. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13272. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13273. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13274. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13275. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13276. offset_custom += 12;
  13277. }
  13278. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13279. value = customAttribute.value[ chunk_faces4[ f ] ];
  13280. v1 = value;
  13281. v2 = value;
  13282. v3 = value;
  13283. v4 = value;
  13284. customAttribute.array[ offset_custom ] = v1.x;
  13285. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13286. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13287. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13288. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13289. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13290. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13291. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13292. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13293. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13294. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13295. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13296. customAttribute.array[ offset_custom + 12 ] = v4.x;
  13297. customAttribute.array[ offset_custom + 13 ] = v4.y;
  13298. customAttribute.array[ offset_custom + 14 ] = v4.z;
  13299. customAttribute.array[ offset_custom + 15 ] = v4.w;
  13300. offset_custom += 16;
  13301. }
  13302. } else if ( customAttribute.boundTo === "faceVertices" ) {
  13303. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13304. value = customAttribute.value[ chunk_faces3[ f ] ];
  13305. v1 = value[ 0 ];
  13306. v2 = value[ 1 ];
  13307. v3 = value[ 2 ];
  13308. customAttribute.array[ offset_custom ] = v1.x;
  13309. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13310. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13311. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13312. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13313. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13314. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13315. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13316. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13317. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13318. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13319. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13320. offset_custom += 12;
  13321. }
  13322. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13323. value = customAttribute.value[ chunk_faces4[ f ] ];
  13324. v1 = value[ 0 ];
  13325. v2 = value[ 1 ];
  13326. v3 = value[ 2 ];
  13327. v4 = value[ 3 ];
  13328. customAttribute.array[ offset_custom ] = v1.x;
  13329. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13330. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13331. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13332. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13333. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13334. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13335. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13336. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13337. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13338. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13339. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13340. customAttribute.array[ offset_custom + 12 ] = v4.x;
  13341. customAttribute.array[ offset_custom + 13 ] = v4.y;
  13342. customAttribute.array[ offset_custom + 14 ] = v4.z;
  13343. customAttribute.array[ offset_custom + 15 ] = v4.w;
  13344. offset_custom += 16;
  13345. }
  13346. }
  13347. }
  13348. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  13349. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  13350. }
  13351. }
  13352. if ( dispose ) {
  13353. delete geometryGroup.__inittedArrays;
  13354. delete geometryGroup.__colorArray;
  13355. delete geometryGroup.__normalArray;
  13356. delete geometryGroup.__tangentArray;
  13357. delete geometryGroup.__uvArray;
  13358. delete geometryGroup.__uv2Array;
  13359. delete geometryGroup.__faceArray;
  13360. delete geometryGroup.__vertexArray;
  13361. delete geometryGroup.__lineArray;
  13362. delete geometryGroup.__skinIndexArray;
  13363. delete geometryGroup.__skinWeightArray;
  13364. }
  13365. };
  13366. function setDirectBuffers ( geometry, hint, dispose ) {
  13367. var attributes = geometry.attributes;
  13368. var attributeName, attributeItem;
  13369. for ( attributeName in attributes ) {
  13370. attributeItem = attributes[ attributeName ];
  13371. if ( attributeItem.needsUpdate ) {
  13372. if ( attributeName === 'index' ) {
  13373. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer );
  13374. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint );
  13375. } else {
  13376. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13377. _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint );
  13378. }
  13379. attributeItem.needsUpdate = false;
  13380. }
  13381. if ( dispose && ! attributeItem.dynamic ) {
  13382. attributeItem.array = null;
  13383. }
  13384. }
  13385. };
  13386. // Buffer rendering
  13387. this.renderBufferImmediate = function ( object, program, material ) {
  13388. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  13389. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  13390. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  13391. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  13392. if ( object.hasPositions ) {
  13393. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  13394. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  13395. _gl.enableVertexAttribArray( program.attributes.position );
  13396. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13397. }
  13398. if ( object.hasNormals ) {
  13399. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  13400. if ( material.shading === THREE.FlatShading ) {
  13401. var nx, ny, nz,
  13402. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  13403. normalArray,
  13404. i, il = object.count * 3;
  13405. for( i = 0; i < il; i += 9 ) {
  13406. normalArray = object.normalArray;
  13407. nax = normalArray[ i ];
  13408. nay = normalArray[ i + 1 ];
  13409. naz = normalArray[ i + 2 ];
  13410. nbx = normalArray[ i + 3 ];
  13411. nby = normalArray[ i + 4 ];
  13412. nbz = normalArray[ i + 5 ];
  13413. ncx = normalArray[ i + 6 ];
  13414. ncy = normalArray[ i + 7 ];
  13415. ncz = normalArray[ i + 8 ];
  13416. nx = ( nax + nbx + ncx ) / 3;
  13417. ny = ( nay + nby + ncy ) / 3;
  13418. nz = ( naz + nbz + ncz ) / 3;
  13419. normalArray[ i ] = nx;
  13420. normalArray[ i + 1 ] = ny;
  13421. normalArray[ i + 2 ] = nz;
  13422. normalArray[ i + 3 ] = nx;
  13423. normalArray[ i + 4 ] = ny;
  13424. normalArray[ i + 5 ] = nz;
  13425. normalArray[ i + 6 ] = nx;
  13426. normalArray[ i + 7 ] = ny;
  13427. normalArray[ i + 8 ] = nz;
  13428. }
  13429. }
  13430. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  13431. _gl.enableVertexAttribArray( program.attributes.normal );
  13432. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13433. }
  13434. if ( object.hasUvs && material.map ) {
  13435. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  13436. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  13437. _gl.enableVertexAttribArray( program.attributes.uv );
  13438. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13439. }
  13440. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  13441. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  13442. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  13443. _gl.enableVertexAttribArray( program.attributes.color );
  13444. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13445. }
  13446. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  13447. object.count = 0;
  13448. };
  13449. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  13450. if ( material.visible === false ) return;
  13451. var linewidth, a, attribute;
  13452. var attributeItem, attributeName, attributePointer, attributeSize;
  13453. var program = setProgram( camera, lights, fog, material, object );
  13454. var programAttributes = program.attributes;
  13455. var geometryAttributes = geometry.attributes;
  13456. var updateBuffers = false,
  13457. wireframeBit = material.wireframe ? 1 : 0,
  13458. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13459. if ( geometryHash !== _currentGeometryGroupHash ) {
  13460. _currentGeometryGroupHash = geometryHash;
  13461. updateBuffers = true;
  13462. }
  13463. if ( updateBuffers ) {
  13464. disableAttributes();
  13465. }
  13466. // render mesh
  13467. if ( object instanceof THREE.Mesh ) {
  13468. var index = geometryAttributes[ "index" ];
  13469. // indexed triangles
  13470. if ( index ) {
  13471. var offsets = geometry.offsets;
  13472. // if there is more than 1 chunk
  13473. // must set attribute pointers to use new offsets for each chunk
  13474. // even if geometry and materials didn't change
  13475. if ( offsets.length > 1 ) updateBuffers = true;
  13476. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13477. var startIndex = offsets[ i ].index;
  13478. if ( updateBuffers ) {
  13479. for ( attributeName in geometryAttributes ) {
  13480. if ( attributeName === 'index' ) continue;
  13481. attributePointer = programAttributes[ attributeName ];
  13482. attributeItem = geometryAttributes[ attributeName ];
  13483. attributeSize = attributeItem.itemSize;
  13484. if ( attributePointer >= 0 ) {
  13485. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13486. enableAttribute( attributePointer );
  13487. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  13488. }
  13489. }
  13490. // indices
  13491. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13492. }
  13493. // render indexed triangles
  13494. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  13495. _this.info.render.calls ++;
  13496. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13497. _this.info.render.faces += offsets[ i ].count / 3;
  13498. }
  13499. // non-indexed triangles
  13500. } else {
  13501. if ( updateBuffers ) {
  13502. for ( attributeName in geometryAttributes ) {
  13503. if ( attributeName === 'index') continue;
  13504. attributePointer = programAttributes[ attributeName ];
  13505. attributeItem = geometryAttributes[ attributeName ];
  13506. attributeSize = attributeItem.itemSize;
  13507. if ( attributePointer >= 0 ) {
  13508. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13509. enableAttribute( attributePointer );
  13510. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13511. }
  13512. }
  13513. }
  13514. var position = geometry.attributes[ "position" ];
  13515. // render non-indexed triangles
  13516. _gl.drawArrays( _gl.TRIANGLES, 0, position.numItems / 3 );
  13517. _this.info.render.calls ++;
  13518. _this.info.render.vertices += position.numItems / 3;
  13519. _this.info.render.faces += position.numItems / 3 / 3;
  13520. }
  13521. // render particles
  13522. } else if ( object instanceof THREE.ParticleSystem ) {
  13523. if ( updateBuffers ) {
  13524. for ( attributeName in geometryAttributes ) {
  13525. attributePointer = programAttributes[ attributeName ];
  13526. attributeItem = geometryAttributes[ attributeName ];
  13527. attributeSize = attributeItem.itemSize;
  13528. if ( attributePointer >= 0 ) {
  13529. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13530. enableAttribute( attributePointer );
  13531. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13532. }
  13533. }
  13534. var position = geometryAttributes[ "position" ];
  13535. // render particles
  13536. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  13537. _this.info.render.calls ++;
  13538. _this.info.render.points += position.numItems / 3;
  13539. }
  13540. } else if ( object instanceof THREE.Line ) {
  13541. if ( updateBuffers ) {
  13542. for ( attributeName in geometryAttributes ) {
  13543. attributePointer = programAttributes[ attributeName ];
  13544. attributeItem = geometryAttributes[ attributeName ];
  13545. attributeSize = attributeItem.itemSize;
  13546. if ( attributePointer >= 0 ) {
  13547. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13548. enableAttribute( attributePointer );
  13549. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13550. }
  13551. }
  13552. // render lines
  13553. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13554. setLineWidth( material.linewidth );
  13555. var position = geometryAttributes[ "position" ];
  13556. _gl.drawArrays( primitives, 0, position.numItems / 3 );
  13557. _this.info.render.calls ++;
  13558. _this.info.render.points += position.numItems;
  13559. }
  13560. }
  13561. };
  13562. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  13563. if ( material.visible === false ) return;
  13564. var linewidth, a, attribute, i, il;
  13565. var program = setProgram( camera, lights, fog, material, object );
  13566. var attributes = program.attributes;
  13567. var updateBuffers = false,
  13568. wireframeBit = material.wireframe ? 1 : 0,
  13569. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13570. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  13571. _currentGeometryGroupHash = geometryGroupHash;
  13572. updateBuffers = true;
  13573. }
  13574. if ( updateBuffers ) {
  13575. disableAttributes();
  13576. }
  13577. // vertices
  13578. if ( !material.morphTargets && attributes.position >= 0 ) {
  13579. if ( updateBuffers ) {
  13580. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13581. enableAttribute( attributes.position );
  13582. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13583. }
  13584. } else {
  13585. if ( object.morphTargetBase ) {
  13586. setupMorphTargets( material, geometryGroup, object );
  13587. }
  13588. }
  13589. if ( updateBuffers ) {
  13590. // custom attributes
  13591. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  13592. if ( geometryGroup.__webglCustomAttributesList ) {
  13593. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  13594. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  13595. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  13596. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  13597. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  13598. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  13599. }
  13600. }
  13601. }
  13602. // colors
  13603. if ( attributes.color >= 0 ) {
  13604. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13605. enableAttribute( attributes.color );
  13606. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13607. }
  13608. // normals
  13609. if ( attributes.normal >= 0 ) {
  13610. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13611. enableAttribute( attributes.normal );
  13612. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13613. }
  13614. // tangents
  13615. if ( attributes.tangent >= 0 ) {
  13616. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13617. enableAttribute( attributes.tangent );
  13618. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  13619. }
  13620. // uvs
  13621. if ( attributes.uv >= 0 ) {
  13622. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13623. enableAttribute( attributes.uv );
  13624. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13625. }
  13626. if ( attributes.uv2 >= 0 ) {
  13627. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13628. enableAttribute( attributes.uv2 );
  13629. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  13630. }
  13631. if ( material.skinning &&
  13632. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  13633. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13634. enableAttribute( attributes.skinIndex );
  13635. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  13636. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13637. enableAttribute( attributes.skinWeight );
  13638. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  13639. }
  13640. // line distances
  13641. if ( attributes.lineDistance >= 0 ) {
  13642. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  13643. enableAttribute( attributes.lineDistance );
  13644. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  13645. }
  13646. }
  13647. // render mesh
  13648. if ( object instanceof THREE.Mesh ) {
  13649. // wireframe
  13650. if ( material.wireframe ) {
  13651. setLineWidth( material.wireframeLinewidth );
  13652. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13653. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  13654. // triangles
  13655. } else {
  13656. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13657. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  13658. }
  13659. _this.info.render.calls ++;
  13660. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  13661. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  13662. // render lines
  13663. } else if ( object instanceof THREE.Line ) {
  13664. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13665. setLineWidth( material.linewidth );
  13666. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  13667. _this.info.render.calls ++;
  13668. // render particles
  13669. } else if ( object instanceof THREE.ParticleSystem ) {
  13670. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  13671. _this.info.render.calls ++;
  13672. _this.info.render.points += geometryGroup.__webglParticleCount;
  13673. // render ribbon
  13674. } else if ( object instanceof THREE.Ribbon ) {
  13675. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  13676. _this.info.render.calls ++;
  13677. }
  13678. };
  13679. function enableAttribute( attribute ) {
  13680. if ( ! _enabledAttributes[ attribute ] ) {
  13681. _gl.enableVertexAttribArray( attribute );
  13682. _enabledAttributes[ attribute ] = true;
  13683. }
  13684. };
  13685. function disableAttributes() {
  13686. for ( var attribute in _enabledAttributes ) {
  13687. if ( _enabledAttributes[ attribute ] ) {
  13688. _gl.disableVertexAttribArray( attribute );
  13689. _enabledAttributes[ attribute ] = false;
  13690. }
  13691. }
  13692. };
  13693. function setupMorphTargets ( material, geometryGroup, object ) {
  13694. // set base
  13695. var attributes = material.program.attributes;
  13696. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  13697. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  13698. enableAttribute( attributes.position );
  13699. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13700. } else if ( attributes.position >= 0 ) {
  13701. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13702. enableAttribute( attributes.position );
  13703. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13704. }
  13705. if ( object.morphTargetForcedOrder.length ) {
  13706. // set forced order
  13707. var m = 0;
  13708. var order = object.morphTargetForcedOrder;
  13709. var influences = object.morphTargetInfluences;
  13710. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  13711. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13712. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  13713. enableAttribute( attributes[ "morphTarget" + m ] );
  13714. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13715. }
  13716. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13717. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  13718. enableAttribute( attributes[ "morphNormal" + m ] );
  13719. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13720. }
  13721. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  13722. m ++;
  13723. }
  13724. } else {
  13725. // find the most influencing
  13726. var influence, activeInfluenceIndices = [];
  13727. var influences = object.morphTargetInfluences;
  13728. var i, il = influences.length;
  13729. for ( i = 0; i < il; i ++ ) {
  13730. influence = influences[ i ];
  13731. if ( influence > 0 ) {
  13732. activeInfluenceIndices.push( [ influence, i ] );
  13733. }
  13734. }
  13735. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  13736. activeInfluenceIndices.sort( numericalSort );
  13737. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  13738. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  13739. activeInfluenceIndices.sort( numericalSort );
  13740. } else if ( activeInfluenceIndices.length === 0 ) {
  13741. activeInfluenceIndices.push( [ 0, 0 ] );
  13742. };
  13743. var influenceIndex, m = 0;
  13744. while ( m < material.numSupportedMorphTargets ) {
  13745. if ( activeInfluenceIndices[ m ] ) {
  13746. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  13747. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13748. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  13749. enableAttribute( attributes[ "morphTarget" + m ] );
  13750. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13751. }
  13752. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13753. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  13754. enableAttribute( attributes[ "morphNormal" + m ] );
  13755. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13756. }
  13757. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  13758. } else {
  13759. /*
  13760. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13761. if ( material.morphNormals ) {
  13762. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13763. }
  13764. */
  13765. object.__webglMorphTargetInfluences[ m ] = 0;
  13766. }
  13767. m ++;
  13768. }
  13769. }
  13770. // load updated influences uniform
  13771. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  13772. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  13773. }
  13774. };
  13775. // Sorting
  13776. function painterSortStable ( a, b ) {
  13777. if ( a.z !== b.z ) {
  13778. return b.z - a.z;
  13779. } else {
  13780. return a.id - b.id;
  13781. }
  13782. };
  13783. function numericalSort ( a, b ) {
  13784. return b[ 0 ] - a[ 0 ];
  13785. };
  13786. // Rendering
  13787. this.render = function ( scene, camera, renderTarget, forceClear ) {
  13788. if ( camera instanceof THREE.Camera === false ) {
  13789. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  13790. return;
  13791. }
  13792. var i, il,
  13793. webglObject, object,
  13794. renderList,
  13795. lights = scene.__lights,
  13796. fog = scene.fog;
  13797. // reset caching for this frame
  13798. _currentMaterialId = -1;
  13799. _lightsNeedUpdate = true;
  13800. // update scene graph
  13801. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  13802. // update camera matrices and frustum
  13803. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  13804. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  13805. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  13806. _frustum.setFromMatrix( _projScreenMatrix );
  13807. // update WebGL objects
  13808. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  13809. // custom render plugins (pre pass)
  13810. renderPlugins( this.renderPluginsPre, scene, camera );
  13811. //
  13812. _this.info.render.calls = 0;
  13813. _this.info.render.vertices = 0;
  13814. _this.info.render.faces = 0;
  13815. _this.info.render.points = 0;
  13816. this.setRenderTarget( renderTarget );
  13817. if ( this.autoClear || forceClear ) {
  13818. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  13819. }
  13820. // set matrices for regular objects (frustum culled)
  13821. renderList = scene.__webglObjects;
  13822. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13823. webglObject = renderList[ i ];
  13824. object = webglObject.object;
  13825. webglObject.id = i;
  13826. webglObject.render = false;
  13827. if ( object.visible ) {
  13828. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  13829. setupMatrices( object, camera );
  13830. unrollBufferMaterial( webglObject );
  13831. webglObject.render = true;
  13832. if ( this.sortObjects === true ) {
  13833. if ( object.renderDepth !== null ) {
  13834. webglObject.z = object.renderDepth;
  13835. } else {
  13836. _vector3.getPositionFromMatrix( object.matrixWorld );
  13837. _vector3.applyProjection( _projScreenMatrix );
  13838. webglObject.z = _vector3.z;
  13839. }
  13840. }
  13841. }
  13842. }
  13843. }
  13844. if ( this.sortObjects ) {
  13845. renderList.sort( painterSortStable );
  13846. }
  13847. // set matrices for immediate objects
  13848. renderList = scene.__webglObjectsImmediate;
  13849. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13850. webglObject = renderList[ i ];
  13851. object = webglObject.object;
  13852. if ( object.visible ) {
  13853. setupMatrices( object, camera );
  13854. unrollImmediateBufferMaterial( webglObject );
  13855. }
  13856. }
  13857. if ( scene.overrideMaterial ) {
  13858. var material = scene.overrideMaterial;
  13859. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13860. this.setDepthTest( material.depthTest );
  13861. this.setDepthWrite( material.depthWrite );
  13862. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13863. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  13864. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  13865. } else {
  13866. var material = null;
  13867. // opaque pass (front-to-back order)
  13868. this.setBlending( THREE.NoBlending );
  13869. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  13870. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  13871. // transparent pass (back-to-front order)
  13872. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  13873. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  13874. }
  13875. // custom render plugins (post pass)
  13876. renderPlugins( this.renderPluginsPost, scene, camera );
  13877. // Generate mipmap if we're using any kind of mipmap filtering
  13878. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  13879. updateRenderTargetMipmap( renderTarget );
  13880. }
  13881. // Ensure depth buffer writing is enabled so it can be cleared on next render
  13882. this.setDepthTest( true );
  13883. this.setDepthWrite( true );
  13884. // _gl.finish();
  13885. };
  13886. function renderPlugins( plugins, scene, camera ) {
  13887. if ( ! plugins.length ) return;
  13888. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  13889. // reset state for plugin (to start from clean slate)
  13890. _currentProgram = null;
  13891. _currentCamera = null;
  13892. _oldBlending = -1;
  13893. _oldDepthTest = -1;
  13894. _oldDepthWrite = -1;
  13895. _oldDoubleSided = -1;
  13896. _oldFlipSided = -1;
  13897. _currentGeometryGroupHash = -1;
  13898. _currentMaterialId = -1;
  13899. _lightsNeedUpdate = true;
  13900. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  13901. // reset state after plugin (anything could have changed)
  13902. _currentProgram = null;
  13903. _currentCamera = null;
  13904. _oldBlending = -1;
  13905. _oldDepthTest = -1;
  13906. _oldDepthWrite = -1;
  13907. _oldDoubleSided = -1;
  13908. _oldFlipSided = -1;
  13909. _currentGeometryGroupHash = -1;
  13910. _currentMaterialId = -1;
  13911. _lightsNeedUpdate = true;
  13912. }
  13913. };
  13914. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13915. var webglObject, object, buffer, material, start, end, delta;
  13916. if ( reverse ) {
  13917. start = renderList.length - 1;
  13918. end = -1;
  13919. delta = -1;
  13920. } else {
  13921. start = 0;
  13922. end = renderList.length;
  13923. delta = 1;
  13924. }
  13925. for ( var i = start; i !== end; i += delta ) {
  13926. webglObject = renderList[ i ];
  13927. if ( webglObject.render ) {
  13928. object = webglObject.object;
  13929. buffer = webglObject.buffer;
  13930. if ( overrideMaterial ) {
  13931. material = overrideMaterial;
  13932. } else {
  13933. material = webglObject[ materialType ];
  13934. if ( ! material ) continue;
  13935. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13936. _this.setDepthTest( material.depthTest );
  13937. _this.setDepthWrite( material.depthWrite );
  13938. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13939. }
  13940. _this.setMaterialFaces( material );
  13941. if ( buffer instanceof THREE.BufferGeometry ) {
  13942. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  13943. } else {
  13944. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  13945. }
  13946. }
  13947. }
  13948. };
  13949. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13950. var webglObject, object, material, program;
  13951. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  13952. webglObject = renderList[ i ];
  13953. object = webglObject.object;
  13954. if ( object.visible ) {
  13955. if ( overrideMaterial ) {
  13956. material = overrideMaterial;
  13957. } else {
  13958. material = webglObject[ materialType ];
  13959. if ( ! material ) continue;
  13960. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13961. _this.setDepthTest( material.depthTest );
  13962. _this.setDepthWrite( material.depthWrite );
  13963. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13964. }
  13965. _this.renderImmediateObject( camera, lights, fog, material, object );
  13966. }
  13967. }
  13968. };
  13969. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  13970. var program = setProgram( camera, lights, fog, material, object );
  13971. _currentGeometryGroupHash = -1;
  13972. _this.setMaterialFaces( material );
  13973. if ( object.immediateRenderCallback ) {
  13974. object.immediateRenderCallback( program, _gl, _frustum );
  13975. } else {
  13976. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  13977. }
  13978. };
  13979. function unrollImmediateBufferMaterial ( globject ) {
  13980. var object = globject.object,
  13981. material = object.material;
  13982. if ( material.transparent ) {
  13983. globject.transparent = material;
  13984. globject.opaque = null;
  13985. } else {
  13986. globject.opaque = material;
  13987. globject.transparent = null;
  13988. }
  13989. };
  13990. function unrollBufferMaterial ( globject ) {
  13991. var object = globject.object,
  13992. buffer = globject.buffer,
  13993. material, materialIndex, meshMaterial;
  13994. meshMaterial = object.material;
  13995. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  13996. materialIndex = buffer.materialIndex;
  13997. material = meshMaterial.materials[ materialIndex ];
  13998. if ( material.transparent ) {
  13999. globject.transparent = material;
  14000. globject.opaque = null;
  14001. } else {
  14002. globject.opaque = material;
  14003. globject.transparent = null;
  14004. }
  14005. } else {
  14006. material = meshMaterial;
  14007. if ( material ) {
  14008. if ( material.transparent ) {
  14009. globject.transparent = material;
  14010. globject.opaque = null;
  14011. } else {
  14012. globject.opaque = material;
  14013. globject.transparent = null;
  14014. }
  14015. }
  14016. }
  14017. };
  14018. // Geometry splitting
  14019. function sortFacesByMaterial ( geometry, material ) {
  14020. var f, fl, face, materialIndex, vertices,
  14021. groupHash, hash_map = {};
  14022. var numMorphTargets = geometry.morphTargets.length;
  14023. var numMorphNormals = geometry.morphNormals.length;
  14024. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  14025. geometry.geometryGroups = {};
  14026. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  14027. face = geometry.faces[ f ];
  14028. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  14029. if ( hash_map[ materialIndex ] === undefined ) {
  14030. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  14031. }
  14032. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  14033. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  14034. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  14035. }
  14036. vertices = face instanceof THREE.Face3 ? 3 : 4;
  14037. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  14038. hash_map[ materialIndex ].counter += 1;
  14039. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  14040. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  14041. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  14042. }
  14043. }
  14044. if ( face instanceof THREE.Face3 ) {
  14045. geometry.geometryGroups[ groupHash ].faces3.push( f );
  14046. } else {
  14047. geometry.geometryGroups[ groupHash ].faces4.push( f );
  14048. }
  14049. geometry.geometryGroups[ groupHash ].vertices += vertices;
  14050. }
  14051. geometry.geometryGroupsList = [];
  14052. for ( var g in geometry.geometryGroups ) {
  14053. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  14054. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  14055. }
  14056. };
  14057. // Objects refresh
  14058. this.initWebGLObjects = function ( scene ) {
  14059. if ( !scene.__webglObjects ) {
  14060. scene.__webglObjects = [];
  14061. scene.__webglObjectsImmediate = [];
  14062. scene.__webglSprites = [];
  14063. scene.__webglFlares = [];
  14064. }
  14065. while ( scene.__objectsAdded.length ) {
  14066. addObject( scene.__objectsAdded[ 0 ], scene );
  14067. scene.__objectsAdded.splice( 0, 1 );
  14068. }
  14069. while ( scene.__objectsRemoved.length ) {
  14070. removeObject( scene.__objectsRemoved[ 0 ], scene );
  14071. scene.__objectsRemoved.splice( 0, 1 );
  14072. }
  14073. // update must be called after objects adding / removal
  14074. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  14075. var object = scene.__webglObjects[ o ].object;
  14076. // TODO: Remove this hack (WebGLRenderer refactoring)
  14077. if ( object.__webglInit === undefined ) {
  14078. if ( object.__webglActive !== undefined ) {
  14079. removeObject( object, scene );
  14080. }
  14081. addObject( object, scene );
  14082. }
  14083. updateObject( object );
  14084. }
  14085. };
  14086. // Objects adding
  14087. function addObject( object, scene ) {
  14088. var g, geometry, material, geometryGroup;
  14089. if ( object.__webglInit === undefined ) {
  14090. object.__webglInit = true;
  14091. object._modelViewMatrix = new THREE.Matrix4();
  14092. object._normalMatrix = new THREE.Matrix3();
  14093. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  14094. object.geometry.__webglInit = true;
  14095. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  14096. }
  14097. geometry = object.geometry;
  14098. if ( geometry === undefined ) {
  14099. // fail silently for now
  14100. } else if ( geometry instanceof THREE.BufferGeometry ) {
  14101. initDirectBuffers( geometry );
  14102. } else if ( object instanceof THREE.Mesh ) {
  14103. material = object.material;
  14104. if ( geometry.geometryGroups === undefined ) {
  14105. sortFacesByMaterial( geometry, material );
  14106. }
  14107. // create separate VBOs per geometry chunk
  14108. for ( g in geometry.geometryGroups ) {
  14109. geometryGroup = geometry.geometryGroups[ g ];
  14110. // initialise VBO on the first access
  14111. if ( ! geometryGroup.__webglVertexBuffer ) {
  14112. createMeshBuffers( geometryGroup );
  14113. initMeshBuffers( geometryGroup, object );
  14114. geometry.verticesNeedUpdate = true;
  14115. geometry.morphTargetsNeedUpdate = true;
  14116. geometry.elementsNeedUpdate = true;
  14117. geometry.uvsNeedUpdate = true;
  14118. geometry.normalsNeedUpdate = true;
  14119. geometry.tangentsNeedUpdate = true;
  14120. geometry.colorsNeedUpdate = true;
  14121. }
  14122. }
  14123. } else if ( object instanceof THREE.Ribbon ) {
  14124. if ( ! geometry.__webglVertexBuffer ) {
  14125. createRibbonBuffers( geometry );
  14126. initRibbonBuffers( geometry, object );
  14127. geometry.verticesNeedUpdate = true;
  14128. geometry.colorsNeedUpdate = true;
  14129. geometry.normalsNeedUpdate = true;
  14130. }
  14131. } else if ( object instanceof THREE.Line ) {
  14132. if ( ! geometry.__webglVertexBuffer ) {
  14133. createLineBuffers( geometry );
  14134. initLineBuffers( geometry, object );
  14135. geometry.verticesNeedUpdate = true;
  14136. geometry.colorsNeedUpdate = true;
  14137. geometry.lineDistancesNeedUpdate = true;
  14138. }
  14139. } else if ( object instanceof THREE.ParticleSystem ) {
  14140. if ( ! geometry.__webglVertexBuffer ) {
  14141. createParticleBuffers( geometry );
  14142. initParticleBuffers( geometry, object );
  14143. geometry.verticesNeedUpdate = true;
  14144. geometry.colorsNeedUpdate = true;
  14145. }
  14146. }
  14147. }
  14148. if ( object.__webglActive === undefined ) {
  14149. if ( object instanceof THREE.Mesh ) {
  14150. geometry = object.geometry;
  14151. if ( geometry instanceof THREE.BufferGeometry ) {
  14152. addBuffer( scene.__webglObjects, geometry, object );
  14153. } else if ( geometry instanceof THREE.Geometry ) {
  14154. for ( g in geometry.geometryGroups ) {
  14155. geometryGroup = geometry.geometryGroups[ g ];
  14156. addBuffer( scene.__webglObjects, geometryGroup, object );
  14157. }
  14158. }
  14159. } else if ( object instanceof THREE.Ribbon ||
  14160. object instanceof THREE.Line ||
  14161. object instanceof THREE.ParticleSystem ) {
  14162. geometry = object.geometry;
  14163. addBuffer( scene.__webglObjects, geometry, object );
  14164. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14165. addBufferImmediate( scene.__webglObjectsImmediate, object );
  14166. } else if ( object instanceof THREE.Sprite ) {
  14167. scene.__webglSprites.push( object );
  14168. } else if ( object instanceof THREE.LensFlare ) {
  14169. scene.__webglFlares.push( object );
  14170. }
  14171. object.__webglActive = true;
  14172. }
  14173. };
  14174. function addBuffer( objlist, buffer, object ) {
  14175. objlist.push(
  14176. {
  14177. id: null,
  14178. buffer: buffer,
  14179. object: object,
  14180. opaque: null,
  14181. transparent: null,
  14182. z: 0
  14183. }
  14184. );
  14185. };
  14186. function addBufferImmediate( objlist, object ) {
  14187. objlist.push(
  14188. {
  14189. id: null,
  14190. object: object,
  14191. opaque: null,
  14192. transparent: null,
  14193. z: 0
  14194. }
  14195. );
  14196. };
  14197. // Objects updates
  14198. function updateObject( object ) {
  14199. var geometry = object.geometry,
  14200. geometryGroup, customAttributesDirty, material;
  14201. if ( geometry instanceof THREE.BufferGeometry ) {
  14202. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  14203. } else if ( object instanceof THREE.Mesh ) {
  14204. // check all geometry groups
  14205. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  14206. geometryGroup = geometry.geometryGroupsList[ i ];
  14207. material = getBufferMaterial( object, geometryGroup );
  14208. if ( geometry.buffersNeedUpdate ) {
  14209. initMeshBuffers( geometryGroup, object );
  14210. }
  14211. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14212. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  14213. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  14214. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  14215. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  14216. }
  14217. }
  14218. geometry.verticesNeedUpdate = false;
  14219. geometry.morphTargetsNeedUpdate = false;
  14220. geometry.elementsNeedUpdate = false;
  14221. geometry.uvsNeedUpdate = false;
  14222. geometry.normalsNeedUpdate = false;
  14223. geometry.colorsNeedUpdate = false;
  14224. geometry.tangentsNeedUpdate = false;
  14225. geometry.buffersNeedUpdate = false;
  14226. material.attributes && clearCustomAttributes( material );
  14227. } else if ( object instanceof THREE.Ribbon ) {
  14228. material = getBufferMaterial( object, geometry );
  14229. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14230. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.normalsNeedUpdate || customAttributesDirty ) {
  14231. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  14232. }
  14233. geometry.verticesNeedUpdate = false;
  14234. geometry.colorsNeedUpdate = false;
  14235. geometry.normalsNeedUpdate = false;
  14236. material.attributes && clearCustomAttributes( material );
  14237. } else if ( object instanceof THREE.Line ) {
  14238. material = getBufferMaterial( object, geometry );
  14239. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14240. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  14241. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  14242. }
  14243. geometry.verticesNeedUpdate = false;
  14244. geometry.colorsNeedUpdate = false;
  14245. geometry.lineDistancesNeedUpdate = false;
  14246. material.attributes && clearCustomAttributes( material );
  14247. } else if ( object instanceof THREE.ParticleSystem ) {
  14248. material = getBufferMaterial( object, geometry );
  14249. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14250. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  14251. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  14252. }
  14253. geometry.verticesNeedUpdate = false;
  14254. geometry.colorsNeedUpdate = false;
  14255. material.attributes && clearCustomAttributes( material );
  14256. }
  14257. };
  14258. // Objects updates - custom attributes check
  14259. function areCustomAttributesDirty( material ) {
  14260. for ( var a in material.attributes ) {
  14261. if ( material.attributes[ a ].needsUpdate ) return true;
  14262. }
  14263. return false;
  14264. };
  14265. function clearCustomAttributes( material ) {
  14266. for ( var a in material.attributes ) {
  14267. material.attributes[ a ].needsUpdate = false;
  14268. }
  14269. };
  14270. // Objects removal
  14271. function removeObject( object, scene ) {
  14272. if ( object instanceof THREE.Mesh ||
  14273. object instanceof THREE.ParticleSystem ||
  14274. object instanceof THREE.Ribbon ||
  14275. object instanceof THREE.Line ) {
  14276. removeInstances( scene.__webglObjects, object );
  14277. } else if ( object instanceof THREE.Sprite ) {
  14278. removeInstancesDirect( scene.__webglSprites, object );
  14279. } else if ( object instanceof THREE.LensFlare ) {
  14280. removeInstancesDirect( scene.__webglFlares, object );
  14281. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14282. removeInstances( scene.__webglObjectsImmediate, object );
  14283. }
  14284. delete object.__webglActive;
  14285. };
  14286. function removeInstances( objlist, object ) {
  14287. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  14288. if ( objlist[ o ].object === object ) {
  14289. objlist.splice( o, 1 );
  14290. }
  14291. }
  14292. };
  14293. function removeInstancesDirect( objlist, object ) {
  14294. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  14295. if ( objlist[ o ] === object ) {
  14296. objlist.splice( o, 1 );
  14297. }
  14298. }
  14299. };
  14300. // Materials
  14301. this.initMaterial = function ( material, lights, fog, object ) {
  14302. material.addEventListener( 'dispose', onMaterialDispose );
  14303. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  14304. if ( material instanceof THREE.MeshDepthMaterial ) {
  14305. shaderID = 'depth';
  14306. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14307. shaderID = 'normal';
  14308. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  14309. shaderID = 'basic';
  14310. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14311. shaderID = 'lambert';
  14312. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14313. shaderID = 'phong';
  14314. } else if ( material instanceof THREE.LineBasicMaterial ) {
  14315. shaderID = 'basic';
  14316. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14317. shaderID = 'dashed';
  14318. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  14319. shaderID = 'particle_basic';
  14320. }
  14321. if ( shaderID ) {
  14322. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  14323. }
  14324. // heuristics to create shader parameters according to lights in the scene
  14325. // (not to blow over maxLights budget)
  14326. maxLightCount = allocateLights( lights );
  14327. maxShadows = allocateShadows( lights );
  14328. maxBones = allocateBones( object );
  14329. parameters = {
  14330. map: !!material.map,
  14331. envMap: !!material.envMap,
  14332. lightMap: !!material.lightMap,
  14333. bumpMap: !!material.bumpMap,
  14334. normalMap: !!material.normalMap,
  14335. specularMap: !!material.specularMap,
  14336. vertexColors: material.vertexColors,
  14337. fog: fog,
  14338. useFog: material.fog,
  14339. fogExp: fog instanceof THREE.FogExp2,
  14340. sizeAttenuation: material.sizeAttenuation,
  14341. skinning: material.skinning,
  14342. maxBones: maxBones,
  14343. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  14344. boneTextureWidth: object && object.boneTextureWidth,
  14345. boneTextureHeight: object && object.boneTextureHeight,
  14346. morphTargets: material.morphTargets,
  14347. morphNormals: material.morphNormals,
  14348. maxMorphTargets: this.maxMorphTargets,
  14349. maxMorphNormals: this.maxMorphNormals,
  14350. maxDirLights: maxLightCount.directional,
  14351. maxPointLights: maxLightCount.point,
  14352. maxSpotLights: maxLightCount.spot,
  14353. maxHemiLights: maxLightCount.hemi,
  14354. maxShadows: maxShadows,
  14355. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  14356. shadowMapType: this.shadowMapType,
  14357. shadowMapDebug: this.shadowMapDebug,
  14358. shadowMapCascade: this.shadowMapCascade,
  14359. alphaTest: material.alphaTest,
  14360. metal: material.metal,
  14361. perPixel: material.perPixel,
  14362. wrapAround: material.wrapAround,
  14363. doubleSided: material.side === THREE.DoubleSide,
  14364. flipSided: material.side === THREE.BackSide
  14365. };
  14366. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters );
  14367. var attributes = material.program.attributes;
  14368. if ( material.morphTargets ) {
  14369. material.numSupportedMorphTargets = 0;
  14370. var id, base = "morphTarget";
  14371. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  14372. id = base + i;
  14373. if ( attributes[ id ] >= 0 ) {
  14374. material.numSupportedMorphTargets ++;
  14375. }
  14376. }
  14377. }
  14378. if ( material.morphNormals ) {
  14379. material.numSupportedMorphNormals = 0;
  14380. var id, base = "morphNormal";
  14381. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  14382. id = base + i;
  14383. if ( attributes[ id ] >= 0 ) {
  14384. material.numSupportedMorphNormals ++;
  14385. }
  14386. }
  14387. }
  14388. material.uniformsList = [];
  14389. for ( u in material.uniforms ) {
  14390. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  14391. }
  14392. };
  14393. function setMaterialShaders( material, shaders ) {
  14394. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  14395. material.vertexShader = shaders.vertexShader;
  14396. material.fragmentShader = shaders.fragmentShader;
  14397. };
  14398. function setProgram( camera, lights, fog, material, object ) {
  14399. _usedTextureUnits = 0;
  14400. if ( material.needsUpdate ) {
  14401. if ( material.program ) deallocateMaterial( material );
  14402. _this.initMaterial( material, lights, fog, object );
  14403. material.needsUpdate = false;
  14404. }
  14405. if ( material.morphTargets ) {
  14406. if ( ! object.__webglMorphTargetInfluences ) {
  14407. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  14408. }
  14409. }
  14410. var refreshMaterial = false;
  14411. var program = material.program,
  14412. p_uniforms = program.uniforms,
  14413. m_uniforms = material.uniforms;
  14414. if ( program !== _currentProgram ) {
  14415. _gl.useProgram( program );
  14416. _currentProgram = program;
  14417. refreshMaterial = true;
  14418. }
  14419. if ( material.id !== _currentMaterialId ) {
  14420. _currentMaterialId = material.id;
  14421. refreshMaterial = true;
  14422. }
  14423. if ( refreshMaterial || camera !== _currentCamera ) {
  14424. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  14425. if ( camera !== _currentCamera ) _currentCamera = camera;
  14426. }
  14427. // skinning uniforms must be set even if material didn't change
  14428. // auto-setting of texture unit for bone texture must go before other textures
  14429. // not sure why, but otherwise weird things happen
  14430. if ( material.skinning ) {
  14431. if ( _supportsBoneTextures && object.useVertexTexture ) {
  14432. if ( p_uniforms.boneTexture !== null ) {
  14433. var textureUnit = getTextureUnit();
  14434. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  14435. _this.setTexture( object.boneTexture, textureUnit );
  14436. }
  14437. } else {
  14438. if ( p_uniforms.boneGlobalMatrices !== null ) {
  14439. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  14440. }
  14441. }
  14442. }
  14443. if ( refreshMaterial ) {
  14444. // refresh uniforms common to several materials
  14445. if ( fog && material.fog ) {
  14446. refreshUniformsFog( m_uniforms, fog );
  14447. }
  14448. if ( material instanceof THREE.MeshPhongMaterial ||
  14449. material instanceof THREE.MeshLambertMaterial ||
  14450. material.lights ) {
  14451. if ( _lightsNeedUpdate ) {
  14452. setupLights( program, lights );
  14453. _lightsNeedUpdate = false;
  14454. }
  14455. refreshUniformsLights( m_uniforms, _lights );
  14456. }
  14457. if ( material instanceof THREE.MeshBasicMaterial ||
  14458. material instanceof THREE.MeshLambertMaterial ||
  14459. material instanceof THREE.MeshPhongMaterial ) {
  14460. refreshUniformsCommon( m_uniforms, material );
  14461. }
  14462. // refresh single material specific uniforms
  14463. if ( material instanceof THREE.LineBasicMaterial ) {
  14464. refreshUniformsLine( m_uniforms, material );
  14465. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14466. refreshUniformsLine( m_uniforms, material );
  14467. refreshUniformsDash( m_uniforms, material );
  14468. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  14469. refreshUniformsParticle( m_uniforms, material );
  14470. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14471. refreshUniformsPhong( m_uniforms, material );
  14472. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14473. refreshUniformsLambert( m_uniforms, material );
  14474. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  14475. m_uniforms.mNear.value = camera.near;
  14476. m_uniforms.mFar.value = camera.far;
  14477. m_uniforms.opacity.value = material.opacity;
  14478. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14479. m_uniforms.opacity.value = material.opacity;
  14480. }
  14481. if ( object.receiveShadow && ! material._shadowPass ) {
  14482. refreshUniformsShadow( m_uniforms, lights );
  14483. }
  14484. // load common uniforms
  14485. loadUniformsGeneric( program, material.uniformsList );
  14486. // load material specific uniforms
  14487. // (shader material also gets them for the sake of genericity)
  14488. if ( material instanceof THREE.ShaderMaterial ||
  14489. material instanceof THREE.MeshPhongMaterial ||
  14490. material.envMap ) {
  14491. if ( p_uniforms.cameraPosition !== null ) {
  14492. _vector3.getPositionFromMatrix( camera.matrixWorld );
  14493. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  14494. }
  14495. }
  14496. if ( material instanceof THREE.MeshPhongMaterial ||
  14497. material instanceof THREE.MeshLambertMaterial ||
  14498. material instanceof THREE.ShaderMaterial ||
  14499. material.skinning ) {
  14500. if ( p_uniforms.viewMatrix !== null ) {
  14501. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  14502. }
  14503. }
  14504. }
  14505. loadUniformsMatrices( p_uniforms, object );
  14506. if ( p_uniforms.modelMatrix !== null ) {
  14507. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  14508. }
  14509. return program;
  14510. };
  14511. // Uniforms (refresh uniforms objects)
  14512. function refreshUniformsCommon ( uniforms, material ) {
  14513. uniforms.opacity.value = material.opacity;
  14514. if ( _this.gammaInput ) {
  14515. uniforms.diffuse.value.copyGammaToLinear( material.color );
  14516. } else {
  14517. uniforms.diffuse.value = material.color;
  14518. }
  14519. uniforms.map.value = material.map;
  14520. uniforms.lightMap.value = material.lightMap;
  14521. uniforms.specularMap.value = material.specularMap;
  14522. if ( material.bumpMap ) {
  14523. uniforms.bumpMap.value = material.bumpMap;
  14524. uniforms.bumpScale.value = material.bumpScale;
  14525. }
  14526. if ( material.normalMap ) {
  14527. uniforms.normalMap.value = material.normalMap;
  14528. uniforms.normalScale.value.copy( material.normalScale );
  14529. }
  14530. // uv repeat and offset setting priorities
  14531. // 1. color map
  14532. // 2. specular map
  14533. // 3. normal map
  14534. // 4. bump map
  14535. var uvScaleMap;
  14536. if ( material.map ) {
  14537. uvScaleMap = material.map;
  14538. } else if ( material.specularMap ) {
  14539. uvScaleMap = material.specularMap;
  14540. } else if ( material.normalMap ) {
  14541. uvScaleMap = material.normalMap;
  14542. } else if ( material.bumpMap ) {
  14543. uvScaleMap = material.bumpMap;
  14544. }
  14545. if ( uvScaleMap !== undefined ) {
  14546. var offset = uvScaleMap.offset;
  14547. var repeat = uvScaleMap.repeat;
  14548. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  14549. }
  14550. uniforms.envMap.value = material.envMap;
  14551. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  14552. if ( _this.gammaInput ) {
  14553. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  14554. uniforms.reflectivity.value = material.reflectivity;
  14555. } else {
  14556. uniforms.reflectivity.value = material.reflectivity;
  14557. }
  14558. uniforms.refractionRatio.value = material.refractionRatio;
  14559. uniforms.combine.value = material.combine;
  14560. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  14561. };
  14562. function refreshUniformsLine ( uniforms, material ) {
  14563. uniforms.diffuse.value = material.color;
  14564. uniforms.opacity.value = material.opacity;
  14565. };
  14566. function refreshUniformsDash ( uniforms, material ) {
  14567. uniforms.dashSize.value = material.dashSize;
  14568. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14569. uniforms.scale.value = material.scale;
  14570. };
  14571. function refreshUniformsParticle ( uniforms, material ) {
  14572. uniforms.psColor.value = material.color;
  14573. uniforms.opacity.value = material.opacity;
  14574. uniforms.size.value = material.size;
  14575. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  14576. uniforms.map.value = material.map;
  14577. };
  14578. function refreshUniformsFog ( uniforms, fog ) {
  14579. uniforms.fogColor.value = fog.color;
  14580. if ( fog instanceof THREE.Fog ) {
  14581. uniforms.fogNear.value = fog.near;
  14582. uniforms.fogFar.value = fog.far;
  14583. } else if ( fog instanceof THREE.FogExp2 ) {
  14584. uniforms.fogDensity.value = fog.density;
  14585. }
  14586. };
  14587. function refreshUniformsPhong ( uniforms, material ) {
  14588. uniforms.shininess.value = material.shininess;
  14589. if ( _this.gammaInput ) {
  14590. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14591. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14592. uniforms.specular.value.copyGammaToLinear( material.specular );
  14593. } else {
  14594. uniforms.ambient.value = material.ambient;
  14595. uniforms.emissive.value = material.emissive;
  14596. uniforms.specular.value = material.specular;
  14597. }
  14598. if ( material.wrapAround ) {
  14599. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14600. }
  14601. };
  14602. function refreshUniformsLambert ( uniforms, material ) {
  14603. if ( _this.gammaInput ) {
  14604. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14605. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14606. } else {
  14607. uniforms.ambient.value = material.ambient;
  14608. uniforms.emissive.value = material.emissive;
  14609. }
  14610. if ( material.wrapAround ) {
  14611. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14612. }
  14613. };
  14614. function refreshUniformsLights ( uniforms, lights ) {
  14615. uniforms.ambientLightColor.value = lights.ambient;
  14616. uniforms.directionalLightColor.value = lights.directional.colors;
  14617. uniforms.directionalLightDirection.value = lights.directional.positions;
  14618. uniforms.pointLightColor.value = lights.point.colors;
  14619. uniforms.pointLightPosition.value = lights.point.positions;
  14620. uniforms.pointLightDistance.value = lights.point.distances;
  14621. uniforms.spotLightColor.value = lights.spot.colors;
  14622. uniforms.spotLightPosition.value = lights.spot.positions;
  14623. uniforms.spotLightDistance.value = lights.spot.distances;
  14624. uniforms.spotLightDirection.value = lights.spot.directions;
  14625. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  14626. uniforms.spotLightExponent.value = lights.spot.exponents;
  14627. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  14628. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  14629. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  14630. };
  14631. function refreshUniformsShadow ( uniforms, lights ) {
  14632. if ( uniforms.shadowMatrix ) {
  14633. var j = 0;
  14634. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  14635. var light = lights[ i ];
  14636. if ( ! light.castShadow ) continue;
  14637. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  14638. uniforms.shadowMap.value[ j ] = light.shadowMap;
  14639. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  14640. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  14641. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  14642. uniforms.shadowBias.value[ j ] = light.shadowBias;
  14643. j ++;
  14644. }
  14645. }
  14646. }
  14647. };
  14648. // Uniforms (load to GPU)
  14649. function loadUniformsMatrices ( uniforms, object ) {
  14650. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  14651. if ( uniforms.normalMatrix ) {
  14652. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  14653. }
  14654. };
  14655. function getTextureUnit() {
  14656. var textureUnit = _usedTextureUnits;
  14657. if ( textureUnit >= _maxTextures ) {
  14658. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  14659. }
  14660. _usedTextureUnits += 1;
  14661. return textureUnit;
  14662. };
  14663. function loadUniformsGeneric ( program, uniforms ) {
  14664. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  14665. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  14666. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  14667. if ( !location ) continue;
  14668. uniform = uniforms[ j ][ 0 ];
  14669. type = uniform.type;
  14670. value = uniform.value;
  14671. if ( type === "i" ) { // single integer
  14672. _gl.uniform1i( location, value );
  14673. } else if ( type === "f" ) { // single float
  14674. _gl.uniform1f( location, value );
  14675. } else if ( type === "v2" ) { // single THREE.Vector2
  14676. _gl.uniform2f( location, value.x, value.y );
  14677. } else if ( type === "v3" ) { // single THREE.Vector3
  14678. _gl.uniform3f( location, value.x, value.y, value.z );
  14679. } else if ( type === "v4" ) { // single THREE.Vector4
  14680. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  14681. } else if ( type === "c" ) { // single THREE.Color
  14682. _gl.uniform3f( location, value.r, value.g, value.b );
  14683. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  14684. _gl.uniform1iv( location, value );
  14685. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  14686. _gl.uniform3iv( location, value );
  14687. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  14688. _gl.uniform1fv( location, value );
  14689. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  14690. _gl.uniform3fv( location, value );
  14691. } else if ( type === "v2v" ) { // array of THREE.Vector2
  14692. if ( uniform._array === undefined ) {
  14693. uniform._array = new Float32Array( 2 * value.length );
  14694. }
  14695. for ( i = 0, il = value.length; i < il; i ++ ) {
  14696. offset = i * 2;
  14697. uniform._array[ offset ] = value[ i ].x;
  14698. uniform._array[ offset + 1 ] = value[ i ].y;
  14699. }
  14700. _gl.uniform2fv( location, uniform._array );
  14701. } else if ( type === "v3v" ) { // array of THREE.Vector3
  14702. if ( uniform._array === undefined ) {
  14703. uniform._array = new Float32Array( 3 * value.length );
  14704. }
  14705. for ( i = 0, il = value.length; i < il; i ++ ) {
  14706. offset = i * 3;
  14707. uniform._array[ offset ] = value[ i ].x;
  14708. uniform._array[ offset + 1 ] = value[ i ].y;
  14709. uniform._array[ offset + 2 ] = value[ i ].z;
  14710. }
  14711. _gl.uniform3fv( location, uniform._array );
  14712. } else if ( type === "v4v" ) { // array of THREE.Vector4
  14713. if ( uniform._array === undefined ) {
  14714. uniform._array = new Float32Array( 4 * value.length );
  14715. }
  14716. for ( i = 0, il = value.length; i < il; i ++ ) {
  14717. offset = i * 4;
  14718. uniform._array[ offset ] = value[ i ].x;
  14719. uniform._array[ offset + 1 ] = value[ i ].y;
  14720. uniform._array[ offset + 2 ] = value[ i ].z;
  14721. uniform._array[ offset + 3 ] = value[ i ].w;
  14722. }
  14723. _gl.uniform4fv( location, uniform._array );
  14724. } else if ( type === "m4") { // single THREE.Matrix4
  14725. if ( uniform._array === undefined ) {
  14726. uniform._array = new Float32Array( 16 );
  14727. }
  14728. value.flattenToArray( uniform._array );
  14729. _gl.uniformMatrix4fv( location, false, uniform._array );
  14730. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  14731. if ( uniform._array === undefined ) {
  14732. uniform._array = new Float32Array( 16 * value.length );
  14733. }
  14734. for ( i = 0, il = value.length; i < il; i ++ ) {
  14735. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  14736. }
  14737. _gl.uniformMatrix4fv( location, false, uniform._array );
  14738. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  14739. texture = value;
  14740. textureUnit = getTextureUnit();
  14741. _gl.uniform1i( location, textureUnit );
  14742. if ( !texture ) continue;
  14743. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  14744. setCubeTexture( texture, textureUnit );
  14745. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  14746. setCubeTextureDynamic( texture, textureUnit );
  14747. } else {
  14748. _this.setTexture( texture, textureUnit );
  14749. }
  14750. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  14751. if ( uniform._array === undefined ) {
  14752. uniform._array = [];
  14753. }
  14754. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14755. uniform._array[ i ] = getTextureUnit();
  14756. }
  14757. _gl.uniform1iv( location, uniform._array );
  14758. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14759. texture = uniform.value[ i ];
  14760. textureUnit = uniform._array[ i ];
  14761. if ( !texture ) continue;
  14762. _this.setTexture( texture, textureUnit );
  14763. }
  14764. }
  14765. }
  14766. };
  14767. function setupMatrices ( object, camera ) {
  14768. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  14769. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  14770. };
  14771. //
  14772. function setColorGamma( array, offset, color, intensitySq ) {
  14773. array[ offset ] = color.r * color.r * intensitySq;
  14774. array[ offset + 1 ] = color.g * color.g * intensitySq;
  14775. array[ offset + 2 ] = color.b * color.b * intensitySq;
  14776. };
  14777. function setColorLinear( array, offset, color, intensity ) {
  14778. array[ offset ] = color.r * intensity;
  14779. array[ offset + 1 ] = color.g * intensity;
  14780. array[ offset + 2 ] = color.b * intensity;
  14781. };
  14782. function setupLights ( program, lights ) {
  14783. var l, ll, light, n,
  14784. r = 0, g = 0, b = 0,
  14785. color, skyColor, groundColor,
  14786. intensity, intensitySq,
  14787. position,
  14788. distance,
  14789. zlights = _lights,
  14790. dirColors = zlights.directional.colors,
  14791. dirPositions = zlights.directional.positions,
  14792. pointColors = zlights.point.colors,
  14793. pointPositions = zlights.point.positions,
  14794. pointDistances = zlights.point.distances,
  14795. spotColors = zlights.spot.colors,
  14796. spotPositions = zlights.spot.positions,
  14797. spotDistances = zlights.spot.distances,
  14798. spotDirections = zlights.spot.directions,
  14799. spotAnglesCos = zlights.spot.anglesCos,
  14800. spotExponents = zlights.spot.exponents,
  14801. hemiSkyColors = zlights.hemi.skyColors,
  14802. hemiGroundColors = zlights.hemi.groundColors,
  14803. hemiPositions = zlights.hemi.positions,
  14804. dirLength = 0,
  14805. pointLength = 0,
  14806. spotLength = 0,
  14807. hemiLength = 0,
  14808. dirCount = 0,
  14809. pointCount = 0,
  14810. spotCount = 0,
  14811. hemiCount = 0,
  14812. dirOffset = 0,
  14813. pointOffset = 0,
  14814. spotOffset = 0,
  14815. hemiOffset = 0;
  14816. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14817. light = lights[ l ];
  14818. if ( light.onlyShadow ) continue;
  14819. color = light.color;
  14820. intensity = light.intensity;
  14821. distance = light.distance;
  14822. if ( light instanceof THREE.AmbientLight ) {
  14823. if ( ! light.visible ) continue;
  14824. if ( _this.gammaInput ) {
  14825. r += color.r * color.r;
  14826. g += color.g * color.g;
  14827. b += color.b * color.b;
  14828. } else {
  14829. r += color.r;
  14830. g += color.g;
  14831. b += color.b;
  14832. }
  14833. } else if ( light instanceof THREE.DirectionalLight ) {
  14834. dirCount += 1;
  14835. if ( ! light.visible ) continue;
  14836. _direction.getPositionFromMatrix( light.matrixWorld );
  14837. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  14838. _direction.sub( _vector3 );
  14839. _direction.normalize();
  14840. // skip lights with undefined direction
  14841. // these create troubles in OpenGL (making pixel black)
  14842. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14843. dirOffset = dirLength * 3;
  14844. dirPositions[ dirOffset ] = _direction.x;
  14845. dirPositions[ dirOffset + 1 ] = _direction.y;
  14846. dirPositions[ dirOffset + 2 ] = _direction.z;
  14847. if ( _this.gammaInput ) {
  14848. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  14849. } else {
  14850. setColorLinear( dirColors, dirOffset, color, intensity );
  14851. }
  14852. dirLength += 1;
  14853. } else if ( light instanceof THREE.PointLight ) {
  14854. pointCount += 1;
  14855. if ( ! light.visible ) continue;
  14856. pointOffset = pointLength * 3;
  14857. if ( _this.gammaInput ) {
  14858. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  14859. } else {
  14860. setColorLinear( pointColors, pointOffset, color, intensity );
  14861. }
  14862. _vector3.getPositionFromMatrix( light.matrixWorld );
  14863. pointPositions[ pointOffset ] = _vector3.x;
  14864. pointPositions[ pointOffset + 1 ] = _vector3.y;
  14865. pointPositions[ pointOffset + 2 ] = _vector3.z;
  14866. pointDistances[ pointLength ] = distance;
  14867. pointLength += 1;
  14868. } else if ( light instanceof THREE.SpotLight ) {
  14869. spotCount += 1;
  14870. if ( ! light.visible ) continue;
  14871. spotOffset = spotLength * 3;
  14872. if ( _this.gammaInput ) {
  14873. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  14874. } else {
  14875. setColorLinear( spotColors, spotOffset, color, intensity );
  14876. }
  14877. _vector3.getPositionFromMatrix( light.matrixWorld );
  14878. spotPositions[ spotOffset ] = _vector3.x;
  14879. spotPositions[ spotOffset + 1 ] = _vector3.y;
  14880. spotPositions[ spotOffset + 2 ] = _vector3.z;
  14881. spotDistances[ spotLength ] = distance;
  14882. _direction.copy( _vector3 );
  14883. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  14884. _direction.sub( _vector3 );
  14885. _direction.normalize();
  14886. spotDirections[ spotOffset ] = _direction.x;
  14887. spotDirections[ spotOffset + 1 ] = _direction.y;
  14888. spotDirections[ spotOffset + 2 ] = _direction.z;
  14889. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  14890. spotExponents[ spotLength ] = light.exponent;
  14891. spotLength += 1;
  14892. } else if ( light instanceof THREE.HemisphereLight ) {
  14893. hemiCount += 1;
  14894. if ( ! light.visible ) continue;
  14895. _direction.getPositionFromMatrix( light.matrixWorld );
  14896. _direction.normalize();
  14897. // skip lights with undefined direction
  14898. // these create troubles in OpenGL (making pixel black)
  14899. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14900. hemiOffset = hemiLength * 3;
  14901. hemiPositions[ hemiOffset ] = _direction.x;
  14902. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  14903. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  14904. skyColor = light.color;
  14905. groundColor = light.groundColor;
  14906. if ( _this.gammaInput ) {
  14907. intensitySq = intensity * intensity;
  14908. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  14909. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  14910. } else {
  14911. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  14912. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  14913. }
  14914. hemiLength += 1;
  14915. }
  14916. }
  14917. // null eventual remains from removed lights
  14918. // (this is to avoid if in shader)
  14919. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  14920. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  14921. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  14922. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  14923. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  14924. zlights.directional.length = dirLength;
  14925. zlights.point.length = pointLength;
  14926. zlights.spot.length = spotLength;
  14927. zlights.hemi.length = hemiLength;
  14928. zlights.ambient[ 0 ] = r;
  14929. zlights.ambient[ 1 ] = g;
  14930. zlights.ambient[ 2 ] = b;
  14931. };
  14932. // GL state setting
  14933. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  14934. if ( cullFace === THREE.CullFaceNone ) {
  14935. _gl.disable( _gl.CULL_FACE );
  14936. } else {
  14937. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  14938. _gl.frontFace( _gl.CW );
  14939. } else {
  14940. _gl.frontFace( _gl.CCW );
  14941. }
  14942. if ( cullFace === THREE.CullFaceBack ) {
  14943. _gl.cullFace( _gl.BACK );
  14944. } else if ( cullFace === THREE.CullFaceFront ) {
  14945. _gl.cullFace( _gl.FRONT );
  14946. } else {
  14947. _gl.cullFace( _gl.FRONT_AND_BACK );
  14948. }
  14949. _gl.enable( _gl.CULL_FACE );
  14950. }
  14951. };
  14952. this.setMaterialFaces = function ( material ) {
  14953. var doubleSided = material.side === THREE.DoubleSide;
  14954. var flipSided = material.side === THREE.BackSide;
  14955. if ( _oldDoubleSided !== doubleSided ) {
  14956. if ( doubleSided ) {
  14957. _gl.disable( _gl.CULL_FACE );
  14958. } else {
  14959. _gl.enable( _gl.CULL_FACE );
  14960. }
  14961. _oldDoubleSided = doubleSided;
  14962. }
  14963. if ( _oldFlipSided !== flipSided ) {
  14964. if ( flipSided ) {
  14965. _gl.frontFace( _gl.CW );
  14966. } else {
  14967. _gl.frontFace( _gl.CCW );
  14968. }
  14969. _oldFlipSided = flipSided;
  14970. }
  14971. };
  14972. this.setDepthTest = function ( depthTest ) {
  14973. if ( _oldDepthTest !== depthTest ) {
  14974. if ( depthTest ) {
  14975. _gl.enable( _gl.DEPTH_TEST );
  14976. } else {
  14977. _gl.disable( _gl.DEPTH_TEST );
  14978. }
  14979. _oldDepthTest = depthTest;
  14980. }
  14981. };
  14982. this.setDepthWrite = function ( depthWrite ) {
  14983. if ( _oldDepthWrite !== depthWrite ) {
  14984. _gl.depthMask( depthWrite );
  14985. _oldDepthWrite = depthWrite;
  14986. }
  14987. };
  14988. function setLineWidth ( width ) {
  14989. if ( width !== _oldLineWidth ) {
  14990. _gl.lineWidth( width );
  14991. _oldLineWidth = width;
  14992. }
  14993. };
  14994. function setPolygonOffset ( polygonoffset, factor, units ) {
  14995. if ( _oldPolygonOffset !== polygonoffset ) {
  14996. if ( polygonoffset ) {
  14997. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  14998. } else {
  14999. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  15000. }
  15001. _oldPolygonOffset = polygonoffset;
  15002. }
  15003. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  15004. _gl.polygonOffset( factor, units );
  15005. _oldPolygonOffsetFactor = factor;
  15006. _oldPolygonOffsetUnits = units;
  15007. }
  15008. };
  15009. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  15010. if ( blending !== _oldBlending ) {
  15011. if ( blending === THREE.NoBlending ) {
  15012. _gl.disable( _gl.BLEND );
  15013. } else if ( blending === THREE.AdditiveBlending ) {
  15014. _gl.enable( _gl.BLEND );
  15015. _gl.blendEquation( _gl.FUNC_ADD );
  15016. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  15017. } else if ( blending === THREE.SubtractiveBlending ) {
  15018. // TODO: Find blendFuncSeparate() combination
  15019. _gl.enable( _gl.BLEND );
  15020. _gl.blendEquation( _gl.FUNC_ADD );
  15021. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  15022. } else if ( blending === THREE.MultiplyBlending ) {
  15023. // TODO: Find blendFuncSeparate() combination
  15024. _gl.enable( _gl.BLEND );
  15025. _gl.blendEquation( _gl.FUNC_ADD );
  15026. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  15027. } else if ( blending === THREE.CustomBlending ) {
  15028. _gl.enable( _gl.BLEND );
  15029. } else {
  15030. _gl.enable( _gl.BLEND );
  15031. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  15032. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  15033. }
  15034. _oldBlending = blending;
  15035. }
  15036. if ( blending === THREE.CustomBlending ) {
  15037. if ( blendEquation !== _oldBlendEquation ) {
  15038. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  15039. _oldBlendEquation = blendEquation;
  15040. }
  15041. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  15042. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  15043. _oldBlendSrc = blendSrc;
  15044. _oldBlendDst = blendDst;
  15045. }
  15046. } else {
  15047. _oldBlendEquation = null;
  15048. _oldBlendSrc = null;
  15049. _oldBlendDst = null;
  15050. }
  15051. };
  15052. // Defines
  15053. function generateDefines ( defines ) {
  15054. var value, chunk, chunks = [];
  15055. for ( var d in defines ) {
  15056. value = defines[ d ];
  15057. if ( value === false ) continue;
  15058. chunk = "#define " + d + " " + value;
  15059. chunks.push( chunk );
  15060. }
  15061. return chunks.join( "\n" );
  15062. };
  15063. // Shaders
  15064. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters ) {
  15065. var p, pl, d, program, code;
  15066. var chunks = [];
  15067. // Generate code
  15068. if ( shaderID ) {
  15069. chunks.push( shaderID );
  15070. } else {
  15071. chunks.push( fragmentShader );
  15072. chunks.push( vertexShader );
  15073. }
  15074. for ( d in defines ) {
  15075. chunks.push( d );
  15076. chunks.push( defines[ d ] );
  15077. }
  15078. for ( p in parameters ) {
  15079. chunks.push( p );
  15080. chunks.push( parameters[ p ] );
  15081. }
  15082. code = chunks.join();
  15083. // Check if code has been already compiled
  15084. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  15085. var programInfo = _programs[ p ];
  15086. if ( programInfo.code === code ) {
  15087. // console.log( "Code already compiled." /*: \n\n" + code*/ );
  15088. programInfo.usedTimes ++;
  15089. return programInfo.program;
  15090. }
  15091. }
  15092. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  15093. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  15094. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  15095. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  15096. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  15097. }
  15098. // console.log( "building new program " );
  15099. //
  15100. var customDefines = generateDefines( defines );
  15101. //
  15102. program = _gl.createProgram();
  15103. var prefix_vertex = [
  15104. "precision " + _precision + " float;",
  15105. customDefines,
  15106. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  15107. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  15108. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  15109. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  15110. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  15111. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  15112. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  15113. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  15114. "#define MAX_SHADOWS " + parameters.maxShadows,
  15115. "#define MAX_BONES " + parameters.maxBones,
  15116. parameters.map ? "#define USE_MAP" : "",
  15117. parameters.envMap ? "#define USE_ENVMAP" : "",
  15118. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  15119. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  15120. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  15121. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  15122. parameters.vertexColors ? "#define USE_COLOR" : "",
  15123. parameters.skinning ? "#define USE_SKINNING" : "",
  15124. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  15125. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  15126. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  15127. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  15128. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  15129. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  15130. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  15131. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  15132. parameters.flipSided ? "#define FLIP_SIDED" : "",
  15133. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  15134. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  15135. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  15136. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  15137. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  15138. "uniform mat4 modelMatrix;",
  15139. "uniform mat4 modelViewMatrix;",
  15140. "uniform mat4 projectionMatrix;",
  15141. "uniform mat4 viewMatrix;",
  15142. "uniform mat3 normalMatrix;",
  15143. "uniform vec3 cameraPosition;",
  15144. "attribute vec3 position;",
  15145. "attribute vec3 normal;",
  15146. "attribute vec2 uv;",
  15147. "attribute vec2 uv2;",
  15148. "#ifdef USE_COLOR",
  15149. "attribute vec3 color;",
  15150. "#endif",
  15151. "#ifdef USE_MORPHTARGETS",
  15152. "attribute vec3 morphTarget0;",
  15153. "attribute vec3 morphTarget1;",
  15154. "attribute vec3 morphTarget2;",
  15155. "attribute vec3 morphTarget3;",
  15156. "#ifdef USE_MORPHNORMALS",
  15157. "attribute vec3 morphNormal0;",
  15158. "attribute vec3 morphNormal1;",
  15159. "attribute vec3 morphNormal2;",
  15160. "attribute vec3 morphNormal3;",
  15161. "#else",
  15162. "attribute vec3 morphTarget4;",
  15163. "attribute vec3 morphTarget5;",
  15164. "attribute vec3 morphTarget6;",
  15165. "attribute vec3 morphTarget7;",
  15166. "#endif",
  15167. "#endif",
  15168. "#ifdef USE_SKINNING",
  15169. "attribute vec4 skinIndex;",
  15170. "attribute vec4 skinWeight;",
  15171. "#endif",
  15172. ""
  15173. ].join("\n");
  15174. var prefix_fragment = [
  15175. "precision " + _precision + " float;",
  15176. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  15177. customDefines,
  15178. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  15179. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  15180. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  15181. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  15182. "#define MAX_SHADOWS " + parameters.maxShadows,
  15183. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  15184. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  15185. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  15186. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  15187. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  15188. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  15189. parameters.map ? "#define USE_MAP" : "",
  15190. parameters.envMap ? "#define USE_ENVMAP" : "",
  15191. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  15192. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  15193. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  15194. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  15195. parameters.vertexColors ? "#define USE_COLOR" : "",
  15196. parameters.metal ? "#define METAL" : "",
  15197. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  15198. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  15199. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  15200. parameters.flipSided ? "#define FLIP_SIDED" : "",
  15201. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  15202. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  15203. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  15204. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  15205. "uniform mat4 viewMatrix;",
  15206. "uniform vec3 cameraPosition;",
  15207. ""
  15208. ].join("\n");
  15209. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  15210. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  15211. _gl.attachShader( program, glVertexShader );
  15212. _gl.attachShader( program, glFragmentShader );
  15213. _gl.linkProgram( program );
  15214. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  15215. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  15216. }
  15217. // clean up
  15218. _gl.deleteShader( glFragmentShader );
  15219. _gl.deleteShader( glVertexShader );
  15220. // console.log( prefix_fragment + fragmentShader );
  15221. // console.log( prefix_vertex + vertexShader );
  15222. program.uniforms = {};
  15223. program.attributes = {};
  15224. var identifiers, u, a, i;
  15225. // cache uniform locations
  15226. identifiers = [
  15227. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  15228. 'morphTargetInfluences'
  15229. ];
  15230. if ( parameters.useVertexTexture ) {
  15231. identifiers.push( 'boneTexture' );
  15232. } else {
  15233. identifiers.push( 'boneGlobalMatrices' );
  15234. }
  15235. for ( u in uniforms ) {
  15236. identifiers.push( u );
  15237. }
  15238. cacheUniformLocations( program, identifiers );
  15239. // cache attributes locations
  15240. identifiers = [
  15241. "position", "normal", "uv", "uv2", "tangent", "color",
  15242. "skinIndex", "skinWeight", "lineDistance"
  15243. ];
  15244. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  15245. identifiers.push( "morphTarget" + i );
  15246. }
  15247. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  15248. identifiers.push( "morphNormal" + i );
  15249. }
  15250. for ( a in attributes ) {
  15251. identifiers.push( a );
  15252. }
  15253. cacheAttributeLocations( program, identifiers );
  15254. program.id = _programs_counter ++;
  15255. _programs.push( { program: program, code: code, usedTimes: 1 } );
  15256. _this.info.memory.programs = _programs.length;
  15257. return program;
  15258. };
  15259. // Shader parameters cache
  15260. function cacheUniformLocations ( program, identifiers ) {
  15261. var i, l, id;
  15262. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  15263. id = identifiers[ i ];
  15264. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  15265. }
  15266. };
  15267. function cacheAttributeLocations ( program, identifiers ) {
  15268. var i, l, id;
  15269. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  15270. id = identifiers[ i ];
  15271. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  15272. }
  15273. };
  15274. function addLineNumbers ( string ) {
  15275. var chunks = string.split( "\n" );
  15276. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  15277. // Chrome reports shader errors on lines
  15278. // starting counting from 1
  15279. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  15280. }
  15281. return chunks.join( "\n" );
  15282. };
  15283. function getShader ( type, string ) {
  15284. var shader;
  15285. if ( type === "fragment" ) {
  15286. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  15287. } else if ( type === "vertex" ) {
  15288. shader = _gl.createShader( _gl.VERTEX_SHADER );
  15289. }
  15290. _gl.shaderSource( shader, string );
  15291. _gl.compileShader( shader );
  15292. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  15293. console.error( _gl.getShaderInfoLog( shader ) );
  15294. console.error( addLineNumbers( string ) );
  15295. return null;
  15296. }
  15297. return shader;
  15298. };
  15299. // Textures
  15300. function isPowerOfTwo ( value ) {
  15301. return ( value & ( value - 1 ) ) === 0;
  15302. };
  15303. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  15304. if ( isImagePowerOfTwo ) {
  15305. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  15306. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  15307. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  15308. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  15309. } else {
  15310. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  15311. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  15312. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  15313. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  15314. }
  15315. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  15316. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  15317. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  15318. texture.__oldAnisotropy = texture.anisotropy;
  15319. }
  15320. }
  15321. };
  15322. this.setTexture = function ( texture, slot ) {
  15323. if ( texture.needsUpdate ) {
  15324. if ( ! texture.__webglInit ) {
  15325. texture.__webglInit = true;
  15326. texture.addEventListener( 'dispose', onTextureDispose );
  15327. texture.__webglTexture = _gl.createTexture();
  15328. _this.info.memory.textures ++;
  15329. }
  15330. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15331. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15332. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15333. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  15334. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  15335. var image = texture.image,
  15336. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  15337. glFormat = paramThreeToGL( texture.format ),
  15338. glType = paramThreeToGL( texture.type );
  15339. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  15340. var mipmap, mipmaps = texture.mipmaps;
  15341. if ( texture instanceof THREE.DataTexture ) {
  15342. // use manually created mipmaps if available
  15343. // if there are no manual mipmaps
  15344. // set 0 level mipmap and then use GL to generate other mipmap levels
  15345. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15346. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15347. mipmap = mipmaps[ i ];
  15348. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15349. }
  15350. texture.generateMipmaps = false;
  15351. } else {
  15352. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  15353. }
  15354. } else if ( texture instanceof THREE.CompressedTexture ) {
  15355. // compressed textures can only use manually created mipmaps
  15356. // WebGL can't generate mipmaps for DDS textures
  15357. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15358. mipmap = mipmaps[ i ];
  15359. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15360. }
  15361. } else { // regular Texture (image, video, canvas)
  15362. // use manually created mipmaps if available
  15363. // if there are no manual mipmaps
  15364. // set 0 level mipmap and then use GL to generate other mipmap levels
  15365. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15366. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15367. mipmap = mipmaps[ i ];
  15368. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  15369. }
  15370. texture.generateMipmaps = false;
  15371. } else {
  15372. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  15373. }
  15374. }
  15375. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15376. texture.needsUpdate = false;
  15377. if ( texture.onUpdate ) texture.onUpdate();
  15378. } else {
  15379. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15380. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15381. }
  15382. };
  15383. function clampToMaxSize ( image, maxSize ) {
  15384. if ( image.width <= maxSize && image.height <= maxSize ) {
  15385. return image;
  15386. }
  15387. // Warning: Scaling through the canvas will only work with images that use
  15388. // premultiplied alpha.
  15389. var maxDimension = Math.max( image.width, image.height );
  15390. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  15391. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  15392. var canvas = document.createElement( 'canvas' );
  15393. canvas.width = newWidth;
  15394. canvas.height = newHeight;
  15395. var ctx = canvas.getContext( "2d" );
  15396. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  15397. return canvas;
  15398. }
  15399. function setCubeTexture ( texture, slot ) {
  15400. if ( texture.image.length === 6 ) {
  15401. if ( texture.needsUpdate ) {
  15402. if ( ! texture.image.__webglTextureCube ) {
  15403. texture.addEventListener( 'dispose', onTextureDispose );
  15404. texture.image.__webglTextureCube = _gl.createTexture();
  15405. _this.info.memory.textures ++;
  15406. }
  15407. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15408. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15409. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15410. var isCompressed = texture instanceof THREE.CompressedTexture;
  15411. var cubeImage = [];
  15412. for ( var i = 0; i < 6; i ++ ) {
  15413. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  15414. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  15415. } else {
  15416. cubeImage[ i ] = texture.image[ i ];
  15417. }
  15418. }
  15419. var image = cubeImage[ 0 ],
  15420. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  15421. glFormat = paramThreeToGL( texture.format ),
  15422. glType = paramThreeToGL( texture.type );
  15423. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  15424. for ( var i = 0; i < 6; i ++ ) {
  15425. if ( isCompressed ) {
  15426. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  15427. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  15428. mipmap = mipmaps[ j ];
  15429. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15430. }
  15431. } else {
  15432. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  15433. }
  15434. }
  15435. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  15436. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15437. }
  15438. texture.needsUpdate = false;
  15439. if ( texture.onUpdate ) texture.onUpdate();
  15440. } else {
  15441. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15442. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15443. }
  15444. }
  15445. };
  15446. function setCubeTextureDynamic ( texture, slot ) {
  15447. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15448. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  15449. };
  15450. // Render targets
  15451. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  15452. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15453. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  15454. };
  15455. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  15456. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15457. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15458. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  15459. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15460. /* For some reason this is not working. Defaulting to RGBA4.
  15461. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15462. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  15463. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15464. */
  15465. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15466. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15467. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15468. } else {
  15469. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  15470. }
  15471. };
  15472. this.setRenderTarget = function ( renderTarget ) {
  15473. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  15474. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  15475. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  15476. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  15477. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15478. renderTarget.__webglTexture = _gl.createTexture();
  15479. _this.info.memory.textures ++;
  15480. // Setup texture, create render and frame buffers
  15481. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  15482. glFormat = paramThreeToGL( renderTarget.format ),
  15483. glType = paramThreeToGL( renderTarget.type );
  15484. if ( isCube ) {
  15485. renderTarget.__webglFramebuffer = [];
  15486. renderTarget.__webglRenderbuffer = [];
  15487. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15488. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  15489. for ( var i = 0; i < 6; i ++ ) {
  15490. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15491. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  15492. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15493. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  15494. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  15495. }
  15496. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15497. } else {
  15498. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  15499. if ( renderTarget.shareDepthFrom ) {
  15500. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  15501. } else {
  15502. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  15503. }
  15504. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15505. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  15506. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15507. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  15508. if ( renderTarget.shareDepthFrom ) {
  15509. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15510. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15511. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15512. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15513. }
  15514. } else {
  15515. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  15516. }
  15517. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15518. }
  15519. // Release everything
  15520. if ( isCube ) {
  15521. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15522. } else {
  15523. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15524. }
  15525. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15526. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15527. }
  15528. var framebuffer, width, height, vx, vy;
  15529. if ( renderTarget ) {
  15530. if ( isCube ) {
  15531. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  15532. } else {
  15533. framebuffer = renderTarget.__webglFramebuffer;
  15534. }
  15535. width = renderTarget.width;
  15536. height = renderTarget.height;
  15537. vx = 0;
  15538. vy = 0;
  15539. } else {
  15540. framebuffer = null;
  15541. width = _viewportWidth;
  15542. height = _viewportHeight;
  15543. vx = _viewportX;
  15544. vy = _viewportY;
  15545. }
  15546. if ( framebuffer !== _currentFramebuffer ) {
  15547. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15548. _gl.viewport( vx, vy, width, height );
  15549. _currentFramebuffer = framebuffer;
  15550. }
  15551. _currentWidth = width;
  15552. _currentHeight = height;
  15553. };
  15554. function updateRenderTargetMipmap ( renderTarget ) {
  15555. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  15556. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15557. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15558. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15559. } else {
  15560. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15561. _gl.generateMipmap( _gl.TEXTURE_2D );
  15562. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15563. }
  15564. };
  15565. // Fallback filters for non-power-of-2 textures
  15566. function filterFallback ( f ) {
  15567. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  15568. return _gl.NEAREST;
  15569. }
  15570. return _gl.LINEAR;
  15571. };
  15572. // Map three.js constants to WebGL constants
  15573. function paramThreeToGL ( p ) {
  15574. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  15575. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  15576. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  15577. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  15578. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  15579. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  15580. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  15581. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  15582. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  15583. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  15584. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  15585. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  15586. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  15587. if ( p === THREE.ByteType ) return _gl.BYTE;
  15588. if ( p === THREE.ShortType ) return _gl.SHORT;
  15589. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  15590. if ( p === THREE.IntType ) return _gl.INT;
  15591. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  15592. if ( p === THREE.FloatType ) return _gl.FLOAT;
  15593. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  15594. if ( p === THREE.RGBFormat ) return _gl.RGB;
  15595. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  15596. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  15597. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  15598. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  15599. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  15600. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  15601. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  15602. if ( p === THREE.OneFactor ) return _gl.ONE;
  15603. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  15604. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  15605. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  15606. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  15607. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  15608. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  15609. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  15610. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  15611. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  15612. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  15613. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15614. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15615. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15616. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15617. }
  15618. return 0;
  15619. };
  15620. // Allocations
  15621. function allocateBones ( object ) {
  15622. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  15623. return 1024;
  15624. } else {
  15625. // default for when object is not specified
  15626. // ( for example when prebuilding shader
  15627. // to be used with multiple objects )
  15628. //
  15629. // - leave some extra space for other uniforms
  15630. // - limit here is ANGLE's 254 max uniform vectors
  15631. // (up to 54 should be safe)
  15632. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  15633. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  15634. var maxBones = nVertexMatrices;
  15635. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  15636. maxBones = Math.min( object.bones.length, maxBones );
  15637. if ( maxBones < object.bones.length ) {
  15638. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  15639. }
  15640. }
  15641. return maxBones;
  15642. }
  15643. };
  15644. function allocateLights( lights ) {
  15645. var dirLights = 0;
  15646. var pointLights = 0;
  15647. var spotLights = 0;
  15648. var hemiLights = 0;
  15649. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  15650. var light = lights[ l ];
  15651. if ( light.onlyShadow ) continue;
  15652. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  15653. if ( light instanceof THREE.PointLight ) pointLights ++;
  15654. if ( light instanceof THREE.SpotLight ) spotLights ++;
  15655. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  15656. }
  15657. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  15658. };
  15659. function allocateShadows( lights ) {
  15660. var maxShadows = 0;
  15661. for ( var l = 0, ll = lights.length; l < ll; l++ ) {
  15662. var light = lights[ l ];
  15663. if ( ! light.castShadow ) continue;
  15664. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  15665. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  15666. }
  15667. return maxShadows;
  15668. };
  15669. // Initialization
  15670. function initGL() {
  15671. try {
  15672. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  15673. throw 'Error creating WebGL context.';
  15674. }
  15675. } catch ( error ) {
  15676. console.error( error );
  15677. }
  15678. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  15679. _glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' );
  15680. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  15681. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15682. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15683. if ( ! _glExtensionTextureFloat ) {
  15684. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  15685. }
  15686. if ( ! _glExtensionStandardDerivatives ) {
  15687. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  15688. }
  15689. if ( ! _glExtensionTextureFilterAnisotropic ) {
  15690. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  15691. }
  15692. if ( ! _glExtensionCompressedTextureS3TC ) {
  15693. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  15694. }
  15695. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15696. _gl.getShaderPrecisionFormat = function() {
  15697. return {
  15698. "rangeMin" : 1,
  15699. "rangeMax" : 1,
  15700. "precision" : 1
  15701. };
  15702. }
  15703. }
  15704. };
  15705. function setDefaultGLState () {
  15706. _gl.clearColor( 0, 0, 0, 1 );
  15707. _gl.clearDepth( 1 );
  15708. _gl.clearStencil( 0 );
  15709. _gl.enable( _gl.DEPTH_TEST );
  15710. _gl.depthFunc( _gl.LEQUAL );
  15711. _gl.frontFace( _gl.CCW );
  15712. _gl.cullFace( _gl.BACK );
  15713. _gl.enable( _gl.CULL_FACE );
  15714. _gl.enable( _gl.BLEND );
  15715. _gl.blendEquation( _gl.FUNC_ADD );
  15716. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  15717. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  15718. };
  15719. // default plugins (order is important)
  15720. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  15721. this.addPrePlugin( this.shadowMapPlugin );
  15722. this.addPostPlugin( new THREE.SpritePlugin() );
  15723. this.addPostPlugin( new THREE.LensFlarePlugin() );
  15724. };
  15725. /**
  15726. * @author szimek / https://github.com/szimek/
  15727. * @author alteredq / http://alteredqualia.com/
  15728. */
  15729. THREE.WebGLRenderTarget = function ( width, height, options ) {
  15730. this.width = width;
  15731. this.height = height;
  15732. options = options || {};
  15733. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  15734. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  15735. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  15736. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  15737. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  15738. this.offset = new THREE.Vector2( 0, 0 );
  15739. this.repeat = new THREE.Vector2( 1, 1 );
  15740. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  15741. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  15742. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  15743. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  15744. this.generateMipmaps = true;
  15745. this.shareDepthFrom = null;
  15746. };
  15747. THREE.WebGLRenderTarget.prototype = {
  15748. constructor: THREE.WebGLRenderTarget,
  15749. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  15750. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  15751. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  15752. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  15753. clone: function () {
  15754. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  15755. tmp.wrapS = this.wrapS;
  15756. tmp.wrapT = this.wrapT;
  15757. tmp.magFilter = this.magFilter;
  15758. tmp.minFilter = this.minFilter;
  15759. tmp.anisotropy = this.anisotropy;
  15760. tmp.offset.copy( this.offset );
  15761. tmp.repeat.copy( this.repeat );
  15762. tmp.format = this.format;
  15763. tmp.type = this.type;
  15764. tmp.depthBuffer = this.depthBuffer;
  15765. tmp.stencilBuffer = this.stencilBuffer;
  15766. tmp.generateMipmaps = this.generateMipmaps;
  15767. tmp.shareDepthFrom = this.shareDepthFrom;
  15768. return tmp;
  15769. },
  15770. dispose: function () {
  15771. this.dispatchEvent( { type: 'dispose' } );
  15772. }
  15773. };
  15774. /**
  15775. * @author alteredq / http://alteredqualia.com
  15776. */
  15777. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  15778. THREE.WebGLRenderTarget.call( this, width, height, options );
  15779. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  15780. };
  15781. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  15782. /**
  15783. * @author mrdoob / http://mrdoob.com/
  15784. */
  15785. THREE.RenderableVertex = function () {
  15786. this.positionWorld = new THREE.Vector3();
  15787. this.positionScreen = new THREE.Vector4();
  15788. this.visible = true;
  15789. };
  15790. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  15791. this.positionWorld.copy( vertex.positionWorld );
  15792. this.positionScreen.copy( vertex.positionScreen );
  15793. };
  15794. /**
  15795. * @author mrdoob / http://mrdoob.com/
  15796. */
  15797. THREE.RenderableFace3 = function () {
  15798. this.v1 = new THREE.RenderableVertex();
  15799. this.v2 = new THREE.RenderableVertex();
  15800. this.v3 = new THREE.RenderableVertex();
  15801. this.centroidModel = new THREE.Vector3();
  15802. this.normalModel = new THREE.Vector3();
  15803. this.normalModelView = new THREE.Vector3();
  15804. this.vertexNormalsLength = 0;
  15805. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15806. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15807. this.color = null;
  15808. this.material = null;
  15809. this.uvs = [[]];
  15810. this.z = null;
  15811. };
  15812. /**
  15813. * @author mrdoob / http://mrdoob.com/
  15814. */
  15815. THREE.RenderableFace4 = function () {
  15816. this.v1 = new THREE.RenderableVertex();
  15817. this.v2 = new THREE.RenderableVertex();
  15818. this.v3 = new THREE.RenderableVertex();
  15819. this.v4 = new THREE.RenderableVertex();
  15820. this.centroidModel = new THREE.Vector3();
  15821. this.normalModel = new THREE.Vector3();
  15822. this.normalModelView = new THREE.Vector3();
  15823. this.vertexNormalsLength = 0;
  15824. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15825. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15826. this.color = null;
  15827. this.material = null;
  15828. this.uvs = [[]];
  15829. this.z = null;
  15830. };
  15831. /**
  15832. * @author mrdoob / http://mrdoob.com/
  15833. */
  15834. THREE.RenderableObject = function () {
  15835. this.object = null;
  15836. this.z = null;
  15837. };
  15838. /**
  15839. * @author mrdoob / http://mrdoob.com/
  15840. */
  15841. THREE.RenderableParticle = function () {
  15842. this.object = null;
  15843. this.x = null;
  15844. this.y = null;
  15845. this.z = null;
  15846. this.rotation = null;
  15847. this.scale = new THREE.Vector2();
  15848. this.material = null;
  15849. };
  15850. /**
  15851. * @author mrdoob / http://mrdoob.com/
  15852. */
  15853. THREE.RenderableLine = function () {
  15854. this.z = null;
  15855. this.v1 = new THREE.RenderableVertex();
  15856. this.v2 = new THREE.RenderableVertex();
  15857. this.vertexColors = [ new THREE.Color(), new THREE.Color() ];
  15858. this.material = null;
  15859. };
  15860. /**
  15861. * @author mrdoob / http://mrdoob.com/
  15862. * @author alteredq / http://alteredqualia.com/
  15863. */
  15864. THREE.GeometryUtils = {
  15865. // Merge two geometries or geometry and geometry from object (using object's transform)
  15866. merge: function ( geometry1, object2 /* mesh | geometry */, materialIndexOffset ) {
  15867. var matrix, normalMatrix,
  15868. vertexOffset = geometry1.vertices.length,
  15869. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  15870. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  15871. vertices1 = geometry1.vertices,
  15872. vertices2 = geometry2.vertices,
  15873. faces1 = geometry1.faces,
  15874. faces2 = geometry2.faces,
  15875. uvs1 = geometry1.faceVertexUvs[ 0 ],
  15876. uvs2 = geometry2.faceVertexUvs[ 0 ];
  15877. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  15878. if ( object2 instanceof THREE.Mesh ) {
  15879. object2.matrixAutoUpdate && object2.updateMatrix();
  15880. matrix = object2.matrix;
  15881. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  15882. }
  15883. // vertices
  15884. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  15885. var vertex = vertices2[ i ];
  15886. var vertexCopy = vertex.clone();
  15887. if ( matrix ) vertexCopy.applyMatrix4( matrix );
  15888. vertices1.push( vertexCopy );
  15889. }
  15890. // faces
  15891. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  15892. var face = faces2[ i ], faceCopy, normal, color,
  15893. faceVertexNormals = face.vertexNormals,
  15894. faceVertexColors = face.vertexColors;
  15895. if ( face instanceof THREE.Face3 ) {
  15896. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  15897. } else if ( face instanceof THREE.Face4 ) {
  15898. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  15899. }
  15900. faceCopy.normal.copy( face.normal );
  15901. if ( normalMatrix ) {
  15902. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  15903. }
  15904. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  15905. normal = faceVertexNormals[ j ].clone();
  15906. if ( normalMatrix ) {
  15907. normal.applyMatrix3( normalMatrix ).normalize();
  15908. }
  15909. faceCopy.vertexNormals.push( normal );
  15910. }
  15911. faceCopy.color.copy( face.color );
  15912. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  15913. color = faceVertexColors[ j ];
  15914. faceCopy.vertexColors.push( color.clone() );
  15915. }
  15916. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  15917. faceCopy.centroid.copy( face.centroid );
  15918. if ( matrix ) {
  15919. faceCopy.centroid.applyMatrix4( matrix );
  15920. }
  15921. faces1.push( faceCopy );
  15922. }
  15923. // uvs
  15924. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  15925. var uv = uvs2[ i ], uvCopy = [];
  15926. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  15927. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  15928. }
  15929. uvs1.push( uvCopy );
  15930. }
  15931. },
  15932. removeMaterials: function ( geometry, materialIndexArray ) {
  15933. var materialIndexMap = {};
  15934. for ( var i = 0, il = materialIndexArray.length; i < il; i ++ ) {
  15935. materialIndexMap[ materialIndexArray[i] ] = true;
  15936. }
  15937. var face, newFaces = [];
  15938. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15939. face = geometry.faces[ i ];
  15940. if ( ! ( face.materialIndex in materialIndexMap ) ) newFaces.push( face );
  15941. }
  15942. geometry.faces = newFaces;
  15943. },
  15944. // Get random point in triangle (via barycentric coordinates)
  15945. // (uniform distribution)
  15946. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  15947. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  15948. var a, b, c,
  15949. point = new THREE.Vector3(),
  15950. tmp = THREE.GeometryUtils.__v1;
  15951. a = THREE.GeometryUtils.random();
  15952. b = THREE.GeometryUtils.random();
  15953. if ( ( a + b ) > 1 ) {
  15954. a = 1 - a;
  15955. b = 1 - b;
  15956. }
  15957. c = 1 - a - b;
  15958. point.copy( vectorA );
  15959. point.multiplyScalar( a );
  15960. tmp.copy( vectorB );
  15961. tmp.multiplyScalar( b );
  15962. point.add( tmp );
  15963. tmp.copy( vectorC );
  15964. tmp.multiplyScalar( c );
  15965. point.add( tmp );
  15966. return point;
  15967. },
  15968. // Get random point in face (triangle / quad)
  15969. // (uniform distribution)
  15970. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  15971. var vA, vB, vC, vD;
  15972. if ( face instanceof THREE.Face3 ) {
  15973. vA = geometry.vertices[ face.a ];
  15974. vB = geometry.vertices[ face.b ];
  15975. vC = geometry.vertices[ face.c ];
  15976. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  15977. } else if ( face instanceof THREE.Face4 ) {
  15978. vA = geometry.vertices[ face.a ];
  15979. vB = geometry.vertices[ face.b ];
  15980. vC = geometry.vertices[ face.c ];
  15981. vD = geometry.vertices[ face.d ];
  15982. var area1, area2;
  15983. if ( useCachedAreas ) {
  15984. if ( face._area1 && face._area2 ) {
  15985. area1 = face._area1;
  15986. area2 = face._area2;
  15987. } else {
  15988. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  15989. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15990. face._area1 = area1;
  15991. face._area2 = area2;
  15992. }
  15993. } else {
  15994. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  15995. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15996. }
  15997. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  15998. if ( r < area1 ) {
  15999. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  16000. } else {
  16001. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  16002. }
  16003. }
  16004. },
  16005. // Get uniformly distributed random points in mesh
  16006. // - create array with cumulative sums of face areas
  16007. // - pick random number from 0 to total area
  16008. // - find corresponding place in area array by binary search
  16009. // - get random point in face
  16010. randomPointsInGeometry: function ( geometry, n ) {
  16011. var face, i,
  16012. faces = geometry.faces,
  16013. vertices = geometry.vertices,
  16014. il = faces.length,
  16015. totalArea = 0,
  16016. cumulativeAreas = [],
  16017. vA, vB, vC, vD;
  16018. // precompute face areas
  16019. for ( i = 0; i < il; i ++ ) {
  16020. face = faces[ i ];
  16021. if ( face instanceof THREE.Face3 ) {
  16022. vA = vertices[ face.a ];
  16023. vB = vertices[ face.b ];
  16024. vC = vertices[ face.c ];
  16025. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  16026. } else if ( face instanceof THREE.Face4 ) {
  16027. vA = vertices[ face.a ];
  16028. vB = vertices[ face.b ];
  16029. vC = vertices[ face.c ];
  16030. vD = vertices[ face.d ];
  16031. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  16032. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  16033. face._area = face._area1 + face._area2;
  16034. }
  16035. totalArea += face._area;
  16036. cumulativeAreas[ i ] = totalArea;
  16037. }
  16038. // binary search cumulative areas array
  16039. function binarySearchIndices( value ) {
  16040. function binarySearch( start, end ) {
  16041. // return closest larger index
  16042. // if exact number is not found
  16043. if ( end < start )
  16044. return start;
  16045. var mid = start + Math.floor( ( end - start ) / 2 );
  16046. if ( cumulativeAreas[ mid ] > value ) {
  16047. return binarySearch( start, mid - 1 );
  16048. } else if ( cumulativeAreas[ mid ] < value ) {
  16049. return binarySearch( mid + 1, end );
  16050. } else {
  16051. return mid;
  16052. }
  16053. }
  16054. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  16055. return result;
  16056. }
  16057. // pick random face weighted by face area
  16058. var r, index,
  16059. result = [];
  16060. var stats = {};
  16061. for ( i = 0; i < n; i ++ ) {
  16062. r = THREE.GeometryUtils.random() * totalArea;
  16063. index = binarySearchIndices( r );
  16064. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  16065. if ( ! stats[ index ] ) {
  16066. stats[ index ] = 1;
  16067. } else {
  16068. stats[ index ] += 1;
  16069. }
  16070. }
  16071. return result;
  16072. },
  16073. // Get triangle area (half of parallelogram)
  16074. // http://mathworld.wolfram.com/TriangleArea.html
  16075. triangleArea: function ( vectorA, vectorB, vectorC ) {
  16076. var tmp1 = THREE.GeometryUtils.__v1,
  16077. tmp2 = THREE.GeometryUtils.__v2;
  16078. tmp1.subVectors( vectorB, vectorA );
  16079. tmp2.subVectors( vectorC, vectorA );
  16080. tmp1.cross( tmp2 );
  16081. return 0.5 * tmp1.length();
  16082. },
  16083. // Center geometry so that 0,0,0 is in center of bounding box
  16084. center: function ( geometry ) {
  16085. geometry.computeBoundingBox();
  16086. var bb = geometry.boundingBox;
  16087. var offset = new THREE.Vector3();
  16088. offset.addVectors( bb.min, bb.max );
  16089. offset.multiplyScalar( -0.5 );
  16090. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  16091. geometry.computeBoundingBox();
  16092. return offset;
  16093. },
  16094. // Normalize UVs to be from <0,1>
  16095. // (for now just the first set of UVs)
  16096. normalizeUVs: function ( geometry ) {
  16097. var uvSet = geometry.faceVertexUvs[ 0 ];
  16098. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  16099. var uvs = uvSet[ i ];
  16100. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  16101. // texture repeat
  16102. if( uvs[ j ].x !== 1.0 ) uvs[ j ].x = uvs[ j ].x - Math.floor( uvs[ j ].x );
  16103. if( uvs[ j ].y !== 1.0 ) uvs[ j ].y = uvs[ j ].y - Math.floor( uvs[ j ].y );
  16104. }
  16105. }
  16106. },
  16107. triangulateQuads: function ( geometry ) {
  16108. var i, il, j, jl;
  16109. var faces = [];
  16110. var faceUvs = [];
  16111. var faceVertexUvs = [];
  16112. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  16113. faceUvs[ i ] = [];
  16114. }
  16115. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  16116. faceVertexUvs[ i ] = [];
  16117. }
  16118. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  16119. var face = geometry.faces[ i ];
  16120. if ( face instanceof THREE.Face4 ) {
  16121. var a = face.a;
  16122. var b = face.b;
  16123. var c = face.c;
  16124. var d = face.d;
  16125. var triA = new THREE.Face3();
  16126. var triB = new THREE.Face3();
  16127. triA.color.copy( face.color );
  16128. triB.color.copy( face.color );
  16129. triA.materialIndex = face.materialIndex;
  16130. triB.materialIndex = face.materialIndex;
  16131. triA.a = a;
  16132. triA.b = b;
  16133. triA.c = d;
  16134. triB.a = b;
  16135. triB.b = c;
  16136. triB.c = d;
  16137. if ( face.vertexColors.length === 4 ) {
  16138. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  16139. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  16140. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  16141. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  16142. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  16143. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  16144. }
  16145. faces.push( triA, triB );
  16146. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  16147. if ( geometry.faceVertexUvs[ j ].length ) {
  16148. var uvs = geometry.faceVertexUvs[ j ][ i ];
  16149. var uvA = uvs[ 0 ];
  16150. var uvB = uvs[ 1 ];
  16151. var uvC = uvs[ 2 ];
  16152. var uvD = uvs[ 3 ];
  16153. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  16154. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  16155. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  16156. }
  16157. }
  16158. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  16159. if ( geometry.faceUvs[ j ].length ) {
  16160. var faceUv = geometry.faceUvs[ j ][ i ];
  16161. faceUvs[ j ].push( faceUv, faceUv );
  16162. }
  16163. }
  16164. } else {
  16165. faces.push( face );
  16166. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  16167. faceUvs[ j ].push( geometry.faceUvs[ j ][ i ] );
  16168. }
  16169. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  16170. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  16171. }
  16172. }
  16173. }
  16174. geometry.faces = faces;
  16175. geometry.faceUvs = faceUvs;
  16176. geometry.faceVertexUvs = faceVertexUvs;
  16177. geometry.computeCentroids();
  16178. geometry.computeFaceNormals();
  16179. geometry.computeVertexNormals();
  16180. if ( geometry.hasTangents ) geometry.computeTangents();
  16181. },
  16182. setMaterialIndex: function ( geometry, index, startFace, endFace ){
  16183. var faces = geometry.faces;
  16184. var start = startFace || 0;
  16185. var end = endFace || faces.length - 1;
  16186. for ( var i = start; i <= end; i ++ ) {
  16187. faces[i].materialIndex = index;
  16188. }
  16189. }
  16190. };
  16191. THREE.GeometryUtils.random = THREE.Math.random16;
  16192. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  16193. THREE.GeometryUtils.__v2 = new THREE.Vector3();
  16194. /**
  16195. * @author alteredq / http://alteredqualia.com/
  16196. * @author mrdoob / http://mrdoob.com/
  16197. */
  16198. THREE.ImageUtils = {
  16199. crossOrigin: 'anonymous',
  16200. loadTexture: function ( url, mapping, onLoad, onError ) {
  16201. var image = new Image();
  16202. var texture = new THREE.Texture( image, mapping );
  16203. var loader = new THREE.ImageLoader();
  16204. loader.crossOrigin = this.crossOrigin;
  16205. loader.load( url, function ( image ) {
  16206. texture.image = image;
  16207. texture.needsUpdate = true;
  16208. if ( onLoad ) onLoad( texture );
  16209. } );
  16210. texture.sourceFile = url;
  16211. return texture;
  16212. },
  16213. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  16214. var texture = new THREE.CompressedTexture();
  16215. texture.mapping = mapping;
  16216. var request = new XMLHttpRequest();
  16217. request.onload = function () {
  16218. var buffer = request.response;
  16219. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16220. texture.format = dds.format;
  16221. texture.mipmaps = dds.mipmaps;
  16222. texture.image.width = dds.width;
  16223. texture.image.height = dds.height;
  16224. // gl.generateMipmap fails for compressed textures
  16225. // mipmaps must be embedded in the DDS file
  16226. // or texture filters must not use mipmapping
  16227. texture.generateMipmaps = false;
  16228. texture.needsUpdate = true;
  16229. if ( onLoad ) onLoad( texture );
  16230. }
  16231. request.onerror = onError;
  16232. request.open( 'GET', url, true );
  16233. request.responseType = "arraybuffer";
  16234. request.send( null );
  16235. return texture;
  16236. },
  16237. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  16238. var images = [];
  16239. images.loadCount = 0;
  16240. var texture = new THREE.Texture();
  16241. texture.image = images;
  16242. if ( mapping !== undefined ) texture.mapping = mapping;
  16243. // no flipping needed for cube textures
  16244. texture.flipY = false;
  16245. for ( var i = 0, il = array.length; i < il; ++ i ) {
  16246. var cubeImage = new Image();
  16247. images[ i ] = cubeImage;
  16248. cubeImage.onload = function () {
  16249. images.loadCount += 1;
  16250. if ( images.loadCount === 6 ) {
  16251. texture.needsUpdate = true;
  16252. if ( onLoad ) onLoad( texture );
  16253. }
  16254. };
  16255. cubeImage.onerror = onError;
  16256. cubeImage.crossOrigin = this.crossOrigin;
  16257. cubeImage.src = array[ i ];
  16258. }
  16259. return texture;
  16260. },
  16261. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  16262. var images = [];
  16263. images.loadCount = 0;
  16264. var texture = new THREE.CompressedTexture();
  16265. texture.image = images;
  16266. if ( mapping !== undefined ) texture.mapping = mapping;
  16267. // no flipping for cube textures
  16268. // (also flipping doesn't work for compressed textures )
  16269. texture.flipY = false;
  16270. // can't generate mipmaps for compressed textures
  16271. // mips must be embedded in DDS files
  16272. texture.generateMipmaps = false;
  16273. var generateCubeFaceCallback = function ( rq, img ) {
  16274. return function () {
  16275. var buffer = rq.response;
  16276. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16277. img.format = dds.format;
  16278. img.mipmaps = dds.mipmaps;
  16279. img.width = dds.width;
  16280. img.height = dds.height;
  16281. images.loadCount += 1;
  16282. if ( images.loadCount === 6 ) {
  16283. texture.format = dds.format;
  16284. texture.needsUpdate = true;
  16285. if ( onLoad ) onLoad( texture );
  16286. }
  16287. }
  16288. }
  16289. // compressed cubemap textures as 6 separate DDS files
  16290. if ( array instanceof Array ) {
  16291. for ( var i = 0, il = array.length; i < il; ++ i ) {
  16292. var cubeImage = {};
  16293. images[ i ] = cubeImage;
  16294. var request = new XMLHttpRequest();
  16295. request.onload = generateCubeFaceCallback( request, cubeImage );
  16296. request.onerror = onError;
  16297. var url = array[ i ];
  16298. request.open( 'GET', url, true );
  16299. request.responseType = "arraybuffer";
  16300. request.send( null );
  16301. }
  16302. // compressed cubemap texture stored in a single DDS file
  16303. } else {
  16304. var url = array;
  16305. var request = new XMLHttpRequest();
  16306. request.onload = function( ) {
  16307. var buffer = request.response;
  16308. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16309. if ( dds.isCubemap ) {
  16310. var faces = dds.mipmaps.length / dds.mipmapCount;
  16311. for ( var f = 0; f < faces; f ++ ) {
  16312. images[ f ] = { mipmaps : [] };
  16313. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16314. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  16315. images[ f ].format = dds.format;
  16316. images[ f ].width = dds.width;
  16317. images[ f ].height = dds.height;
  16318. }
  16319. }
  16320. texture.format = dds.format;
  16321. texture.needsUpdate = true;
  16322. if ( onLoad ) onLoad( texture );
  16323. }
  16324. }
  16325. request.onerror = onError;
  16326. request.open( 'GET', url, true );
  16327. request.responseType = "arraybuffer";
  16328. request.send( null );
  16329. }
  16330. return texture;
  16331. },
  16332. parseDDS: function ( buffer, loadMipmaps ) {
  16333. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  16334. // Adapted from @toji's DDS utils
  16335. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  16336. // All values and structures referenced from:
  16337. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  16338. var DDS_MAGIC = 0x20534444;
  16339. var DDSD_CAPS = 0x1,
  16340. DDSD_HEIGHT = 0x2,
  16341. DDSD_WIDTH = 0x4,
  16342. DDSD_PITCH = 0x8,
  16343. DDSD_PIXELFORMAT = 0x1000,
  16344. DDSD_MIPMAPCOUNT = 0x20000,
  16345. DDSD_LINEARSIZE = 0x80000,
  16346. DDSD_DEPTH = 0x800000;
  16347. var DDSCAPS_COMPLEX = 0x8,
  16348. DDSCAPS_MIPMAP = 0x400000,
  16349. DDSCAPS_TEXTURE = 0x1000;
  16350. var DDSCAPS2_CUBEMAP = 0x200,
  16351. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  16352. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  16353. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  16354. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  16355. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  16356. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  16357. DDSCAPS2_VOLUME = 0x200000;
  16358. var DDPF_ALPHAPIXELS = 0x1,
  16359. DDPF_ALPHA = 0x2,
  16360. DDPF_FOURCC = 0x4,
  16361. DDPF_RGB = 0x40,
  16362. DDPF_YUV = 0x200,
  16363. DDPF_LUMINANCE = 0x20000;
  16364. function fourCCToInt32( value ) {
  16365. return value.charCodeAt(0) +
  16366. (value.charCodeAt(1) << 8) +
  16367. (value.charCodeAt(2) << 16) +
  16368. (value.charCodeAt(3) << 24);
  16369. }
  16370. function int32ToFourCC( value ) {
  16371. return String.fromCharCode(
  16372. value & 0xff,
  16373. (value >> 8) & 0xff,
  16374. (value >> 16) & 0xff,
  16375. (value >> 24) & 0xff
  16376. );
  16377. }
  16378. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  16379. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  16380. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  16381. var headerLengthInt = 31; // The header length in 32 bit ints
  16382. // Offsets into the header array
  16383. var off_magic = 0;
  16384. var off_size = 1;
  16385. var off_flags = 2;
  16386. var off_height = 3;
  16387. var off_width = 4;
  16388. var off_mipmapCount = 7;
  16389. var off_pfFlags = 20;
  16390. var off_pfFourCC = 21;
  16391. var off_caps = 27;
  16392. var off_caps2 = 28;
  16393. var off_caps3 = 29;
  16394. var off_caps4 = 30;
  16395. // Parse header
  16396. var header = new Int32Array( buffer, 0, headerLengthInt );
  16397. if ( header[ off_magic ] !== DDS_MAGIC ) {
  16398. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  16399. return dds;
  16400. }
  16401. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  16402. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  16403. return dds;
  16404. }
  16405. var blockBytes;
  16406. var fourCC = header[ off_pfFourCC ];
  16407. switch ( fourCC ) {
  16408. case FOURCC_DXT1:
  16409. blockBytes = 8;
  16410. dds.format = THREE.RGB_S3TC_DXT1_Format;
  16411. break;
  16412. case FOURCC_DXT3:
  16413. blockBytes = 16;
  16414. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  16415. break;
  16416. case FOURCC_DXT5:
  16417. blockBytes = 16;
  16418. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  16419. break;
  16420. default:
  16421. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  16422. return dds;
  16423. }
  16424. dds.mipmapCount = 1;
  16425. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  16426. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  16427. }
  16428. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  16429. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  16430. dds.width = header[ off_width ];
  16431. dds.height = header[ off_height ];
  16432. var dataOffset = header[ off_size ] + 4;
  16433. // Extract mipmaps buffers
  16434. var width = dds.width;
  16435. var height = dds.height;
  16436. var faces = dds.isCubemap ? 6 : 1;
  16437. for ( var face = 0; face < faces; face ++ ) {
  16438. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16439. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  16440. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  16441. var mipmap = { "data": byteArray, "width": width, "height": height };
  16442. dds.mipmaps.push( mipmap );
  16443. dataOffset += dataLength;
  16444. width = Math.max( width * 0.5, 1 );
  16445. height = Math.max( height * 0.5, 1 );
  16446. }
  16447. width = dds.width;
  16448. height = dds.height;
  16449. }
  16450. return dds;
  16451. },
  16452. getNormalMap: function ( image, depth ) {
  16453. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  16454. var cross = function ( a, b ) {
  16455. 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 ] ];
  16456. }
  16457. var subtract = function ( a, b ) {
  16458. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  16459. }
  16460. var normalize = function ( a ) {
  16461. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  16462. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  16463. }
  16464. depth = depth | 1;
  16465. var width = image.width;
  16466. var height = image.height;
  16467. var canvas = document.createElement( 'canvas' );
  16468. canvas.width = width;
  16469. canvas.height = height;
  16470. var context = canvas.getContext( '2d' );
  16471. context.drawImage( image, 0, 0 );
  16472. var data = context.getImageData( 0, 0, width, height ).data;
  16473. var imageData = context.createImageData( width, height );
  16474. var output = imageData.data;
  16475. for ( var x = 0; x < width; x ++ ) {
  16476. for ( var y = 0; y < height; y ++ ) {
  16477. var ly = y - 1 < 0 ? 0 : y - 1;
  16478. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  16479. var lx = x - 1 < 0 ? 0 : x - 1;
  16480. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  16481. var points = [];
  16482. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  16483. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  16484. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  16485. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  16486. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  16487. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  16488. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  16489. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  16490. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  16491. var normals = [];
  16492. var num_points = points.length;
  16493. for ( var i = 0; i < num_points; i ++ ) {
  16494. var v1 = points[ i ];
  16495. var v2 = points[ ( i + 1 ) % num_points ];
  16496. v1 = subtract( v1, origin );
  16497. v2 = subtract( v2, origin );
  16498. normals.push( normalize( cross( v1, v2 ) ) );
  16499. }
  16500. var normal = [ 0, 0, 0 ];
  16501. for ( var i = 0; i < normals.length; i ++ ) {
  16502. normal[ 0 ] += normals[ i ][ 0 ];
  16503. normal[ 1 ] += normals[ i ][ 1 ];
  16504. normal[ 2 ] += normals[ i ][ 2 ];
  16505. }
  16506. normal[ 0 ] /= normals.length;
  16507. normal[ 1 ] /= normals.length;
  16508. normal[ 2 ] /= normals.length;
  16509. var idx = ( y * width + x ) * 4;
  16510. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16511. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16512. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  16513. output[ idx + 3 ] = 255;
  16514. }
  16515. }
  16516. context.putImageData( imageData, 0, 0 );
  16517. return canvas;
  16518. },
  16519. generateDataTexture: function ( width, height, color ) {
  16520. var size = width * height;
  16521. var data = new Uint8Array( 3 * size );
  16522. var r = Math.floor( color.r * 255 );
  16523. var g = Math.floor( color.g * 255 );
  16524. var b = Math.floor( color.b * 255 );
  16525. for ( var i = 0; i < size; i ++ ) {
  16526. data[ i * 3 ] = r;
  16527. data[ i * 3 + 1 ] = g;
  16528. data[ i * 3 + 2 ] = b;
  16529. }
  16530. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  16531. texture.needsUpdate = true;
  16532. return texture;
  16533. }
  16534. };
  16535. /**
  16536. * @author alteredq / http://alteredqualia.com/
  16537. */
  16538. THREE.SceneUtils = {
  16539. createMultiMaterialObject: function ( geometry, materials ) {
  16540. var group = new THREE.Object3D();
  16541. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  16542. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  16543. }
  16544. return group;
  16545. },
  16546. detach : function ( child, parent, scene ) {
  16547. child.applyMatrix( parent.matrixWorld );
  16548. parent.remove( child );
  16549. scene.add( child );
  16550. },
  16551. attach: function ( child, scene, parent ) {
  16552. var matrixWorldInverse = new THREE.Matrix4();
  16553. matrixWorldInverse.getInverse( parent.matrixWorld );
  16554. child.applyMatrix( matrixWorldInverse );
  16555. scene.remove( child );
  16556. parent.add( child );
  16557. }
  16558. };
  16559. /**
  16560. * @author zz85 / http://www.lab4games.net/zz85/blog
  16561. * @author alteredq / http://alteredqualia.com/
  16562. *
  16563. * For Text operations in three.js (See TextGeometry)
  16564. *
  16565. * It uses techniques used in:
  16566. *
  16567. * typeface.js and canvastext
  16568. * For converting fonts and rendering with javascript
  16569. * http://typeface.neocracy.org
  16570. *
  16571. * Triangulation ported from AS3
  16572. * Simple Polygon Triangulation
  16573. * http://actionsnippet.com/?p=1462
  16574. *
  16575. * A Method to triangulate shapes with holes
  16576. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  16577. *
  16578. */
  16579. THREE.FontUtils = {
  16580. faces : {},
  16581. // Just for now. face[weight][style]
  16582. face : "helvetiker",
  16583. weight: "normal",
  16584. style : "normal",
  16585. size : 150,
  16586. divisions : 10,
  16587. getFace : function() {
  16588. return this.faces[ this.face ][ this.weight ][ this.style ];
  16589. },
  16590. loadFace : function( data ) {
  16591. var family = data.familyName.toLowerCase();
  16592. var ThreeFont = this;
  16593. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  16594. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  16595. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16596. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16597. return data;
  16598. },
  16599. drawText : function( text ) {
  16600. var characterPts = [], allPts = [];
  16601. // RenderText
  16602. var i, p,
  16603. face = this.getFace(),
  16604. scale = this.size / face.resolution,
  16605. offset = 0,
  16606. chars = String( text ).split( '' ),
  16607. length = chars.length;
  16608. var fontPaths = [];
  16609. for ( i = 0; i < length; i ++ ) {
  16610. var path = new THREE.Path();
  16611. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  16612. offset += ret.offset;
  16613. fontPaths.push( ret.path );
  16614. }
  16615. // get the width
  16616. var width = offset / 2;
  16617. //
  16618. // for ( p = 0; p < allPts.length; p++ ) {
  16619. //
  16620. // allPts[ p ].x -= width;
  16621. //
  16622. // }
  16623. //var extract = this.extractPoints( allPts, characterPts );
  16624. //extract.contour = allPts;
  16625. //extract.paths = fontPaths;
  16626. //extract.offset = width;
  16627. return { paths : fontPaths, offset : width };
  16628. },
  16629. extractGlyphPoints : function( c, face, scale, offset, path ) {
  16630. var pts = [];
  16631. var i, i2, divisions,
  16632. outline, action, length,
  16633. scaleX, scaleY,
  16634. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16635. laste,
  16636. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16637. if ( !glyph ) return;
  16638. if ( glyph.o ) {
  16639. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16640. length = outline.length;
  16641. scaleX = scale;
  16642. scaleY = scale;
  16643. for ( i = 0; i < length; ) {
  16644. action = outline[ i ++ ];
  16645. //console.log( action );
  16646. switch( action ) {
  16647. case 'm':
  16648. // Move To
  16649. x = outline[ i++ ] * scaleX + offset;
  16650. y = outline[ i++ ] * scaleY;
  16651. path.moveTo( x, y );
  16652. break;
  16653. case 'l':
  16654. // Line To
  16655. x = outline[ i++ ] * scaleX + offset;
  16656. y = outline[ i++ ] * scaleY;
  16657. path.lineTo(x,y);
  16658. break;
  16659. case 'q':
  16660. // QuadraticCurveTo
  16661. cpx = outline[ i++ ] * scaleX + offset;
  16662. cpy = outline[ i++ ] * scaleY;
  16663. cpx1 = outline[ i++ ] * scaleX + offset;
  16664. cpy1 = outline[ i++ ] * scaleY;
  16665. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  16666. laste = pts[ pts.length - 1 ];
  16667. if ( laste ) {
  16668. cpx0 = laste.x;
  16669. cpy0 = laste.y;
  16670. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16671. var t = i2 / divisions;
  16672. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16673. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16674. }
  16675. }
  16676. break;
  16677. case 'b':
  16678. // Cubic Bezier Curve
  16679. cpx = outline[ i++ ] * scaleX + offset;
  16680. cpy = outline[ i++ ] * scaleY;
  16681. cpx1 = outline[ i++ ] * scaleX + offset;
  16682. cpy1 = outline[ i++ ] * -scaleY;
  16683. cpx2 = outline[ i++ ] * scaleX + offset;
  16684. cpy2 = outline[ i++ ] * -scaleY;
  16685. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  16686. laste = pts[ pts.length - 1 ];
  16687. if ( laste ) {
  16688. cpx0 = laste.x;
  16689. cpy0 = laste.y;
  16690. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16691. var t = i2 / divisions;
  16692. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16693. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16694. }
  16695. }
  16696. break;
  16697. }
  16698. }
  16699. }
  16700. return { offset: glyph.ha*scale, path:path};
  16701. }
  16702. };
  16703. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16704. // Parameters
  16705. parameters = parameters || {};
  16706. var size = parameters.size !== undefined ? parameters.size : 100;
  16707. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16708. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16709. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16710. var style = parameters.style !== undefined ? parameters.style : "normal";
  16711. THREE.FontUtils.size = size;
  16712. THREE.FontUtils.divisions = curveSegments;
  16713. THREE.FontUtils.face = font;
  16714. THREE.FontUtils.weight = weight;
  16715. THREE.FontUtils.style = style;
  16716. // Get a Font data json object
  16717. var data = THREE.FontUtils.drawText( text );
  16718. var paths = data.paths;
  16719. var shapes = [];
  16720. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16721. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16722. }
  16723. return shapes;
  16724. };
  16725. /**
  16726. * This code is a quick port of code written in C++ which was submitted to
  16727. * flipcode.com by John W. Ratcliff // July 22, 2000
  16728. * See original code and more information here:
  16729. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16730. *
  16731. * ported to actionscript by Zevan Rosser
  16732. * www.actionsnippet.com
  16733. *
  16734. * ported to javascript by Joshua Koo
  16735. * http://www.lab4games.net/zz85/blog
  16736. *
  16737. */
  16738. ( function( namespace ) {
  16739. var EPSILON = 0.0000000001;
  16740. // takes in an contour array and returns
  16741. var process = function( contour, indices ) {
  16742. var n = contour.length;
  16743. if ( n < 3 ) return null;
  16744. var result = [],
  16745. verts = [],
  16746. vertIndices = [];
  16747. /* we want a counter-clockwise polygon in verts */
  16748. var u, v, w;
  16749. if ( area( contour ) > 0.0 ) {
  16750. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16751. } else {
  16752. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16753. }
  16754. var nv = n;
  16755. /* remove nv - 2 vertices, creating 1 triangle every time */
  16756. var count = 2 * nv; /* error detection */
  16757. for( v = nv - 1; nv > 2; ) {
  16758. /* if we loop, it is probably a non-simple polygon */
  16759. if ( ( count-- ) <= 0 ) {
  16760. //** Triangulate: ERROR - probable bad polygon!
  16761. //throw ( "Warning, unable to triangulate polygon!" );
  16762. //return null;
  16763. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16764. console.log( "Warning, unable to triangulate polygon!" );
  16765. if ( indices ) return vertIndices;
  16766. return result;
  16767. }
  16768. /* three consecutive vertices in current polygon, <u,v,w> */
  16769. u = v; if ( nv <= u ) u = 0; /* previous */
  16770. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16771. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16772. if ( snip( contour, u, v, w, nv, verts ) ) {
  16773. var a, b, c, s, t;
  16774. /* true names of the vertices */
  16775. a = verts[ u ];
  16776. b = verts[ v ];
  16777. c = verts[ w ];
  16778. /* output Triangle */
  16779. result.push( [ contour[ a ],
  16780. contour[ b ],
  16781. contour[ c ] ] );
  16782. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16783. /* remove v from the remaining polygon */
  16784. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  16785. verts[ s ] = verts[ t ];
  16786. }
  16787. nv--;
  16788. /* reset error detection counter */
  16789. count = 2 * nv;
  16790. }
  16791. }
  16792. if ( indices ) return vertIndices;
  16793. return result;
  16794. };
  16795. // calculate area of the contour polygon
  16796. var area = function ( contour ) {
  16797. var n = contour.length;
  16798. var a = 0.0;
  16799. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16800. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16801. }
  16802. return a * 0.5;
  16803. };
  16804. var snip = function ( contour, u, v, w, n, verts ) {
  16805. var p;
  16806. var ax, ay, bx, by;
  16807. var cx, cy, px, py;
  16808. ax = contour[ verts[ u ] ].x;
  16809. ay = contour[ verts[ u ] ].y;
  16810. bx = contour[ verts[ v ] ].x;
  16811. by = contour[ verts[ v ] ].y;
  16812. cx = contour[ verts[ w ] ].x;
  16813. cy = contour[ verts[ w ] ].y;
  16814. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16815. var aX, aY, bX, bY, cX, cY;
  16816. var apx, apy, bpx, bpy, cpx, cpy;
  16817. var cCROSSap, bCROSScp, aCROSSbp;
  16818. aX = cx - bx; aY = cy - by;
  16819. bX = ax - cx; bY = ay - cy;
  16820. cX = bx - ax; cY = by - ay;
  16821. for ( p = 0; p < n; p++ ) {
  16822. if( (p === u) || (p === v) || (p === w) ) continue;
  16823. px = contour[ verts[ p ] ].x
  16824. py = contour[ verts[ p ] ].y
  16825. apx = px - ax; apy = py - ay;
  16826. bpx = px - bx; bpy = py - by;
  16827. cpx = px - cx; cpy = py - cy;
  16828. // see if p is inside triangle abc
  16829. aCROSSbp = aX*bpy - aY*bpx;
  16830. cCROSSap = cX*apy - cY*apx;
  16831. bCROSScp = bX*cpy - bY*cpx;
  16832. if ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) ) return false;
  16833. }
  16834. return true;
  16835. };
  16836. namespace.Triangulate = process;
  16837. namespace.Triangulate.area = area;
  16838. return namespace;
  16839. })(THREE.FontUtils);
  16840. // To use the typeface.js face files, hook up the API
  16841. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  16842. THREE.typeface_js = self._typeface_js;
  16843. /**
  16844. * @author zz85 / http://www.lab4games.net/zz85/blog
  16845. * Extensible curve object
  16846. *
  16847. * Some common of Curve methods
  16848. * .getPoint(t), getTangent(t)
  16849. * .getPointAt(u), getTagentAt(u)
  16850. * .getPoints(), .getSpacedPoints()
  16851. * .getLength()
  16852. * .updateArcLengths()
  16853. *
  16854. * This following classes subclasses THREE.Curve:
  16855. *
  16856. * -- 2d classes --
  16857. * THREE.LineCurve
  16858. * THREE.QuadraticBezierCurve
  16859. * THREE.CubicBezierCurve
  16860. * THREE.SplineCurve
  16861. * THREE.ArcCurve
  16862. * THREE.EllipseCurve
  16863. *
  16864. * -- 3d classes --
  16865. * THREE.LineCurve3
  16866. * THREE.QuadraticBezierCurve3
  16867. * THREE.CubicBezierCurve3
  16868. * THREE.SplineCurve3
  16869. * THREE.ClosedSplineCurve3
  16870. *
  16871. * A series of curves can be represented as a THREE.CurvePath
  16872. *
  16873. **/
  16874. /**************************************************************
  16875. * Abstract Curve base class
  16876. **************************************************************/
  16877. THREE.Curve = function () {
  16878. };
  16879. // Virtual base class method to overwrite and implement in subclasses
  16880. // - t [0 .. 1]
  16881. THREE.Curve.prototype.getPoint = function ( t ) {
  16882. console.log( "Warning, getPoint() not implemented!" );
  16883. return null;
  16884. };
  16885. // Get point at relative position in curve according to arc length
  16886. // - u [0 .. 1]
  16887. THREE.Curve.prototype.getPointAt = function ( u ) {
  16888. var t = this.getUtoTmapping( u );
  16889. return this.getPoint( t );
  16890. };
  16891. // Get sequence of points using getPoint( t )
  16892. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16893. if ( !divisions ) divisions = 5;
  16894. var d, pts = [];
  16895. for ( d = 0; d <= divisions; d ++ ) {
  16896. pts.push( this.getPoint( d / divisions ) );
  16897. }
  16898. return pts;
  16899. };
  16900. // Get sequence of points using getPointAt( u )
  16901. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16902. if ( !divisions ) divisions = 5;
  16903. var d, pts = [];
  16904. for ( d = 0; d <= divisions; d ++ ) {
  16905. pts.push( this.getPointAt( d / divisions ) );
  16906. }
  16907. return pts;
  16908. };
  16909. // Get total curve arc length
  16910. THREE.Curve.prototype.getLength = function () {
  16911. var lengths = this.getLengths();
  16912. return lengths[ lengths.length - 1 ];
  16913. };
  16914. // Get list of cumulative segment lengths
  16915. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16916. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16917. if ( this.cacheArcLengths
  16918. && ( this.cacheArcLengths.length == divisions + 1 )
  16919. && !this.needsUpdate) {
  16920. //console.log( "cached", this.cacheArcLengths );
  16921. return this.cacheArcLengths;
  16922. }
  16923. this.needsUpdate = false;
  16924. var cache = [];
  16925. var current, last = this.getPoint( 0 );
  16926. var p, sum = 0;
  16927. cache.push( 0 );
  16928. for ( p = 1; p <= divisions; p ++ ) {
  16929. current = this.getPoint ( p / divisions );
  16930. sum += current.distanceTo( last );
  16931. cache.push( sum );
  16932. last = current;
  16933. }
  16934. this.cacheArcLengths = cache;
  16935. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16936. };
  16937. THREE.Curve.prototype.updateArcLengths = function() {
  16938. this.needsUpdate = true;
  16939. this.getLengths();
  16940. };
  16941. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16942. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16943. var arcLengths = this.getLengths();
  16944. var i = 0, il = arcLengths.length;
  16945. var targetArcLength; // The targeted u distance value to get
  16946. if ( distance ) {
  16947. targetArcLength = distance;
  16948. } else {
  16949. targetArcLength = u * arcLengths[ il - 1 ];
  16950. }
  16951. //var time = Date.now();
  16952. // binary search for the index with largest value smaller than target u distance
  16953. var low = 0, high = il - 1, comparison;
  16954. while ( low <= high ) {
  16955. 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
  16956. comparison = arcLengths[ i ] - targetArcLength;
  16957. if ( comparison < 0 ) {
  16958. low = i + 1;
  16959. continue;
  16960. } else if ( comparison > 0 ) {
  16961. high = i - 1;
  16962. continue;
  16963. } else {
  16964. high = i;
  16965. break;
  16966. // DONE
  16967. }
  16968. }
  16969. i = high;
  16970. //console.log('b' , i, low, high, Date.now()- time);
  16971. if ( arcLengths[ i ] == targetArcLength ) {
  16972. var t = i / ( il - 1 );
  16973. return t;
  16974. }
  16975. // we could get finer grain at lengths, or use simple interpolatation between two points
  16976. var lengthBefore = arcLengths[ i ];
  16977. var lengthAfter = arcLengths[ i + 1 ];
  16978. var segmentLength = lengthAfter - lengthBefore;
  16979. // determine where we are between the 'before' and 'after' points
  16980. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16981. // add that fractional amount to t
  16982. var t = ( i + segmentFraction ) / ( il -1 );
  16983. return t;
  16984. };
  16985. // Returns a unit vector tangent at t
  16986. // In case any sub curve does not implement its tangent derivation,
  16987. // 2 points a small delta apart will be used to find its gradient
  16988. // which seems to give a reasonable approximation
  16989. THREE.Curve.prototype.getTangent = function( t ) {
  16990. var delta = 0.0001;
  16991. var t1 = t - delta;
  16992. var t2 = t + delta;
  16993. // Capping in case of danger
  16994. if ( t1 < 0 ) t1 = 0;
  16995. if ( t2 > 1 ) t2 = 1;
  16996. var pt1 = this.getPoint( t1 );
  16997. var pt2 = this.getPoint( t2 );
  16998. var vec = pt2.clone().sub(pt1);
  16999. return vec.normalize();
  17000. };
  17001. THREE.Curve.prototype.getTangentAt = function ( u ) {
  17002. var t = this.getUtoTmapping( u );
  17003. return this.getTangent( t );
  17004. };
  17005. /**************************************************************
  17006. * Utils
  17007. **************************************************************/
  17008. THREE.Curve.Utils = {
  17009. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  17010. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  17011. },
  17012. // Puay Bing, thanks for helping with this derivative!
  17013. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  17014. return -3 * p0 * (1 - t) * (1 - t) +
  17015. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  17016. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  17017. 3 * t * t * p3;
  17018. },
  17019. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  17020. // To check if my formulas are correct
  17021. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  17022. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  17023. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  17024. var h11 = 3 * t * t - 2 * t; // t3 − t2
  17025. return h00 + h10 + h01 + h11;
  17026. },
  17027. // Catmull-Rom
  17028. interpolate: function( p0, p1, p2, p3, t ) {
  17029. var v0 = ( p2 - p0 ) * 0.5;
  17030. var v1 = ( p3 - p1 ) * 0.5;
  17031. var t2 = t * t;
  17032. var t3 = t * t2;
  17033. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17034. }
  17035. };
  17036. // TODO: Transformation for Curves?
  17037. /**************************************************************
  17038. * 3D Curves
  17039. **************************************************************/
  17040. // A Factory method for creating new curve subclasses
  17041. THREE.Curve.create = function ( constructor, getPointFunc ) {
  17042. constructor.prototype = Object.create( THREE.Curve.prototype );
  17043. constructor.prototype.getPoint = getPointFunc;
  17044. return constructor;
  17045. };
  17046. /**
  17047. * @author zz85 / http://www.lab4games.net/zz85/blog
  17048. *
  17049. **/
  17050. /**************************************************************
  17051. * Curved Path - a curve path is simply a array of connected
  17052. * curves, but retains the api of a curve
  17053. **************************************************************/
  17054. THREE.CurvePath = function () {
  17055. this.curves = [];
  17056. this.bends = [];
  17057. this.autoClose = false; // Automatically closes the path
  17058. };
  17059. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  17060. THREE.CurvePath.prototype.add = function ( curve ) {
  17061. this.curves.push( curve );
  17062. };
  17063. THREE.CurvePath.prototype.checkConnection = function() {
  17064. // TODO
  17065. // If the ending of curve is not connected to the starting
  17066. // or the next curve, then, this is not a real path
  17067. };
  17068. THREE.CurvePath.prototype.closePath = function() {
  17069. // TODO Test
  17070. // and verify for vector3 (needs to implement equals)
  17071. // Add a line curve if start and end of lines are not connected
  17072. var startPoint = this.curves[0].getPoint(0);
  17073. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  17074. if (!startPoint.equals(endPoint)) {
  17075. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  17076. }
  17077. };
  17078. // To get accurate point with reference to
  17079. // entire path distance at time t,
  17080. // following has to be done:
  17081. // 1. Length of each sub path have to be known
  17082. // 2. Locate and identify type of curve
  17083. // 3. Get t for the curve
  17084. // 4. Return curve.getPointAt(t')
  17085. THREE.CurvePath.prototype.getPoint = function( t ) {
  17086. var d = t * this.getLength();
  17087. var curveLengths = this.getCurveLengths();
  17088. var i = 0, diff, curve;
  17089. // To think about boundaries points.
  17090. while ( i < curveLengths.length ) {
  17091. if ( curveLengths[ i ] >= d ) {
  17092. diff = curveLengths[ i ] - d;
  17093. curve = this.curves[ i ];
  17094. var u = 1 - diff / curve.getLength();
  17095. return curve.getPointAt( u );
  17096. break;
  17097. }
  17098. i ++;
  17099. }
  17100. return null;
  17101. // loop where sum != 0, sum > d , sum+1 <d
  17102. };
  17103. /*
  17104. THREE.CurvePath.prototype.getTangent = function( t ) {
  17105. };*/
  17106. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  17107. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  17108. // getPoint() depends on getLength
  17109. THREE.CurvePath.prototype.getLength = function() {
  17110. var lens = this.getCurveLengths();
  17111. return lens[ lens.length - 1 ];
  17112. };
  17113. // Compute lengths and cache them
  17114. // We cannot overwrite getLengths() because UtoT mapping uses it.
  17115. THREE.CurvePath.prototype.getCurveLengths = function() {
  17116. // We use cache values if curves and cache array are same length
  17117. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  17118. return this.cacheLengths;
  17119. };
  17120. // Get length of subsurve
  17121. // Push sums into cached array
  17122. var lengths = [], sums = 0;
  17123. var i, il = this.curves.length;
  17124. for ( i = 0; i < il; i ++ ) {
  17125. sums += this.curves[ i ].getLength();
  17126. lengths.push( sums );
  17127. }
  17128. this.cacheLengths = lengths;
  17129. return lengths;
  17130. };
  17131. // Returns min and max coordinates, as well as centroid
  17132. THREE.CurvePath.prototype.getBoundingBox = function () {
  17133. var points = this.getPoints();
  17134. var maxX, maxY, maxZ;
  17135. var minX, minY, minZ;
  17136. maxX = maxY = Number.NEGATIVE_INFINITY;
  17137. minX = minY = Number.POSITIVE_INFINITY;
  17138. var p, i, il, sum;
  17139. var v3 = points[0] instanceof THREE.Vector3;
  17140. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  17141. for ( i = 0, il = points.length; i < il; i ++ ) {
  17142. p = points[ i ];
  17143. if ( p.x > maxX ) maxX = p.x;
  17144. else if ( p.x < minX ) minX = p.x;
  17145. if ( p.y > maxY ) maxY = p.y;
  17146. else if ( p.y < minY ) minY = p.y;
  17147. if ( v3 ) {
  17148. if ( p.z > maxZ ) maxZ = p.z;
  17149. else if ( p.z < minZ ) minZ = p.z;
  17150. }
  17151. sum.add( p );
  17152. }
  17153. var ret = {
  17154. minX: minX,
  17155. minY: minY,
  17156. maxX: maxX,
  17157. maxY: maxY,
  17158. centroid: sum.divideScalar( il )
  17159. };
  17160. if ( v3 ) {
  17161. ret.maxZ = maxZ;
  17162. ret.minZ = minZ;
  17163. }
  17164. return ret;
  17165. };
  17166. /**************************************************************
  17167. * Create Geometries Helpers
  17168. **************************************************************/
  17169. /// Generate geometry from path points (for Line or ParticleSystem objects)
  17170. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  17171. var pts = this.getPoints( divisions, true );
  17172. return this.createGeometry( pts );
  17173. };
  17174. // Generate geometry from equidistance sampling along the path
  17175. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  17176. var pts = this.getSpacedPoints( divisions, true );
  17177. return this.createGeometry( pts );
  17178. };
  17179. THREE.CurvePath.prototype.createGeometry = function( points ) {
  17180. var geometry = new THREE.Geometry();
  17181. for ( var i = 0; i < points.length; i ++ ) {
  17182. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  17183. }
  17184. return geometry;
  17185. };
  17186. /**************************************************************
  17187. * Bend / Wrap Helper Methods
  17188. **************************************************************/
  17189. // Wrap path / Bend modifiers?
  17190. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  17191. this.bends.push( bendpath );
  17192. };
  17193. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  17194. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  17195. var i, il;
  17196. if ( !bends ) {
  17197. bends = this.bends;
  17198. }
  17199. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17200. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17201. }
  17202. return oldPts;
  17203. };
  17204. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  17205. var oldPts = this.getSpacedPoints( segments );
  17206. var i, il;
  17207. if ( !bends ) {
  17208. bends = this.bends;
  17209. }
  17210. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17211. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17212. }
  17213. return oldPts;
  17214. };
  17215. // This returns getPoints() bend/wrapped around the contour of a path.
  17216. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  17217. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  17218. var bounds = this.getBoundingBox();
  17219. var i, il, p, oldX, oldY, xNorm;
  17220. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  17221. p = oldPts[ i ];
  17222. oldX = p.x;
  17223. oldY = p.y;
  17224. xNorm = oldX / bounds.maxX;
  17225. // If using actual distance, for length > path, requires line extrusions
  17226. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  17227. xNorm = path.getUtoTmapping( xNorm, oldX );
  17228. // check for out of bounds?
  17229. var pathPt = path.getPoint( xNorm );
  17230. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  17231. p.x = pathPt.x + normal.x;
  17232. p.y = pathPt.y + normal.y;
  17233. }
  17234. return oldPts;
  17235. };
  17236. /**
  17237. * @author alteredq / http://alteredqualia.com/
  17238. */
  17239. THREE.Gyroscope = function () {
  17240. THREE.Object3D.call( this );
  17241. };
  17242. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  17243. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  17244. this.matrixAutoUpdate && this.updateMatrix();
  17245. // update matrixWorld
  17246. if ( this.matrixWorldNeedsUpdate || force ) {
  17247. if ( this.parent ) {
  17248. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  17249. this.matrixWorld.decompose( this.translationWorld, this.quaternionWorld, this.scaleWorld );
  17250. this.matrix.decompose( this.translationObject, this.quaternionObject, this.scaleObject );
  17251. this.matrixWorld.compose( this.translationWorld, this.quaternionObject, this.scaleWorld );
  17252. } else {
  17253. this.matrixWorld.copy( this.matrix );
  17254. }
  17255. this.matrixWorldNeedsUpdate = false;
  17256. force = true;
  17257. }
  17258. // update children
  17259. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  17260. this.children[ i ].updateMatrixWorld( force );
  17261. }
  17262. };
  17263. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  17264. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  17265. THREE.Gyroscope.prototype.quaternionWorld = new THREE.Quaternion();
  17266. THREE.Gyroscope.prototype.quaternionObject = new THREE.Quaternion();
  17267. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  17268. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  17269. /**
  17270. * @author zz85 / http://www.lab4games.net/zz85/blog
  17271. * Creates free form 2d path using series of points, lines or curves.
  17272. *
  17273. **/
  17274. THREE.Path = function ( points ) {
  17275. THREE.CurvePath.call(this);
  17276. this.actions = [];
  17277. if ( points ) {
  17278. this.fromPoints( points );
  17279. }
  17280. };
  17281. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  17282. THREE.PathActions = {
  17283. MOVE_TO: 'moveTo',
  17284. LINE_TO: 'lineTo',
  17285. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  17286. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  17287. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  17288. ARC: 'arc', // Circle
  17289. ELLIPSE: 'ellipse'
  17290. };
  17291. // TODO Clean up PATH API
  17292. // Create path using straight lines to connect all points
  17293. // - vectors: array of Vector2
  17294. THREE.Path.prototype.fromPoints = function ( vectors ) {
  17295. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  17296. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  17297. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  17298. };
  17299. };
  17300. // startPath() endPath()?
  17301. THREE.Path.prototype.moveTo = function ( x, y ) {
  17302. var args = Array.prototype.slice.call( arguments );
  17303. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  17304. };
  17305. THREE.Path.prototype.lineTo = function ( x, y ) {
  17306. var args = Array.prototype.slice.call( arguments );
  17307. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17308. var x0 = lastargs[ lastargs.length - 2 ];
  17309. var y0 = lastargs[ lastargs.length - 1 ];
  17310. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  17311. this.curves.push( curve );
  17312. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  17313. };
  17314. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  17315. var args = Array.prototype.slice.call( arguments );
  17316. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17317. var x0 = lastargs[ lastargs.length - 2 ];
  17318. var y0 = lastargs[ lastargs.length - 1 ];
  17319. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  17320. new THREE.Vector2( aCPx, aCPy ),
  17321. new THREE.Vector2( aX, aY ) );
  17322. this.curves.push( curve );
  17323. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  17324. };
  17325. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  17326. aCP2x, aCP2y,
  17327. aX, aY ) {
  17328. var args = Array.prototype.slice.call( arguments );
  17329. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17330. var x0 = lastargs[ lastargs.length - 2 ];
  17331. var y0 = lastargs[ lastargs.length - 1 ];
  17332. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  17333. new THREE.Vector2( aCP1x, aCP1y ),
  17334. new THREE.Vector2( aCP2x, aCP2y ),
  17335. new THREE.Vector2( aX, aY ) );
  17336. this.curves.push( curve );
  17337. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  17338. };
  17339. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  17340. var args = Array.prototype.slice.call( arguments );
  17341. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17342. var x0 = lastargs[ lastargs.length - 2 ];
  17343. var y0 = lastargs[ lastargs.length - 1 ];
  17344. //---
  17345. var npts = [ new THREE.Vector2( x0, y0 ) ];
  17346. Array.prototype.push.apply( npts, pts );
  17347. var curve = new THREE.SplineCurve( npts );
  17348. this.curves.push( curve );
  17349. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  17350. };
  17351. // FUTURE: Change the API or follow canvas API?
  17352. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  17353. aStartAngle, aEndAngle, aClockwise ) {
  17354. var lastargs = this.actions[ this.actions.length - 1].args;
  17355. var x0 = lastargs[ lastargs.length - 2 ];
  17356. var y0 = lastargs[ lastargs.length - 1 ];
  17357. this.absarc(aX + x0, aY + y0, aRadius,
  17358. aStartAngle, aEndAngle, aClockwise );
  17359. };
  17360. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  17361. aStartAngle, aEndAngle, aClockwise ) {
  17362. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  17363. };
  17364. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  17365. aStartAngle, aEndAngle, aClockwise ) {
  17366. var lastargs = this.actions[ this.actions.length - 1].args;
  17367. var x0 = lastargs[ lastargs.length - 2 ];
  17368. var y0 = lastargs[ lastargs.length - 1 ];
  17369. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  17370. aStartAngle, aEndAngle, aClockwise );
  17371. };
  17372. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  17373. aStartAngle, aEndAngle, aClockwise ) {
  17374. var args = Array.prototype.slice.call( arguments );
  17375. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  17376. aStartAngle, aEndAngle, aClockwise );
  17377. this.curves.push( curve );
  17378. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  17379. args.push(lastPoint.x);
  17380. args.push(lastPoint.y);
  17381. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  17382. };
  17383. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  17384. if ( ! divisions ) divisions = 40;
  17385. var points = [];
  17386. for ( var i = 0; i < divisions; i ++ ) {
  17387. points.push( this.getPoint( i / divisions ) );
  17388. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  17389. }
  17390. // if ( closedPath ) {
  17391. //
  17392. // points.push( points[ 0 ] );
  17393. //
  17394. // }
  17395. return points;
  17396. };
  17397. /* Return an array of vectors based on contour of the path */
  17398. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  17399. if (this.useSpacedPoints) {
  17400. console.log('tata');
  17401. return this.getSpacedPoints( divisions, closedPath );
  17402. }
  17403. divisions = divisions || 12;
  17404. var points = [];
  17405. var i, il, item, action, args;
  17406. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  17407. laste, j,
  17408. t, tx, ty;
  17409. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17410. item = this.actions[ i ];
  17411. action = item.action;
  17412. args = item.args;
  17413. switch( action ) {
  17414. case THREE.PathActions.MOVE_TO:
  17415. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17416. break;
  17417. case THREE.PathActions.LINE_TO:
  17418. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17419. break;
  17420. case THREE.PathActions.QUADRATIC_CURVE_TO:
  17421. cpx = args[ 2 ];
  17422. cpy = args[ 3 ];
  17423. cpx1 = args[ 0 ];
  17424. cpy1 = args[ 1 ];
  17425. if ( points.length > 0 ) {
  17426. laste = points[ points.length - 1 ];
  17427. cpx0 = laste.x;
  17428. cpy0 = laste.y;
  17429. } else {
  17430. laste = this.actions[ i - 1 ].args;
  17431. cpx0 = laste[ laste.length - 2 ];
  17432. cpy0 = laste[ laste.length - 1 ];
  17433. }
  17434. for ( j = 1; j <= divisions; j ++ ) {
  17435. t = j / divisions;
  17436. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17437. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17438. points.push( new THREE.Vector2( tx, ty ) );
  17439. }
  17440. break;
  17441. case THREE.PathActions.BEZIER_CURVE_TO:
  17442. cpx = args[ 4 ];
  17443. cpy = args[ 5 ];
  17444. cpx1 = args[ 0 ];
  17445. cpy1 = args[ 1 ];
  17446. cpx2 = args[ 2 ];
  17447. cpy2 = args[ 3 ];
  17448. if ( points.length > 0 ) {
  17449. laste = points[ points.length - 1 ];
  17450. cpx0 = laste.x;
  17451. cpy0 = laste.y;
  17452. } else {
  17453. laste = this.actions[ i - 1 ].args;
  17454. cpx0 = laste[ laste.length - 2 ];
  17455. cpy0 = laste[ laste.length - 1 ];
  17456. }
  17457. for ( j = 1; j <= divisions; j ++ ) {
  17458. t = j / divisions;
  17459. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17460. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17461. points.push( new THREE.Vector2( tx, ty ) );
  17462. }
  17463. break;
  17464. case THREE.PathActions.CSPLINE_THRU:
  17465. laste = this.actions[ i - 1 ].args;
  17466. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17467. var spts = [ last ];
  17468. var n = divisions * args[ 0 ].length;
  17469. spts = spts.concat( args[ 0 ] );
  17470. var spline = new THREE.SplineCurve( spts );
  17471. for ( j = 1; j <= n; j ++ ) {
  17472. points.push( spline.getPointAt( j / n ) ) ;
  17473. }
  17474. break;
  17475. case THREE.PathActions.ARC:
  17476. var aX = args[ 0 ], aY = args[ 1 ],
  17477. aRadius = args[ 2 ],
  17478. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17479. aClockwise = !!args[ 5 ];
  17480. var deltaAngle = aEndAngle - aStartAngle;
  17481. var angle;
  17482. var tdivisions = divisions * 2;
  17483. for ( j = 1; j <= tdivisions; j ++ ) {
  17484. t = j / tdivisions;
  17485. if ( ! aClockwise ) {
  17486. t = 1 - t;
  17487. }
  17488. angle = aStartAngle + t * deltaAngle;
  17489. tx = aX + aRadius * Math.cos( angle );
  17490. ty = aY + aRadius * Math.sin( angle );
  17491. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17492. points.push( new THREE.Vector2( tx, ty ) );
  17493. }
  17494. //console.log(points);
  17495. break;
  17496. case THREE.PathActions.ELLIPSE:
  17497. var aX = args[ 0 ], aY = args[ 1 ],
  17498. xRadius = args[ 2 ],
  17499. yRadius = args[ 3 ],
  17500. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17501. aClockwise = !!args[ 6 ];
  17502. var deltaAngle = aEndAngle - aStartAngle;
  17503. var angle;
  17504. var tdivisions = divisions * 2;
  17505. for ( j = 1; j <= tdivisions; j ++ ) {
  17506. t = j / tdivisions;
  17507. if ( ! aClockwise ) {
  17508. t = 1 - t;
  17509. }
  17510. angle = aStartAngle + t * deltaAngle;
  17511. tx = aX + xRadius * Math.cos( angle );
  17512. ty = aY + yRadius * Math.sin( angle );
  17513. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17514. points.push( new THREE.Vector2( tx, ty ) );
  17515. }
  17516. //console.log(points);
  17517. break;
  17518. } // end switch
  17519. }
  17520. // Normalize to remove the closing point by default.
  17521. var lastPoint = points[ points.length - 1];
  17522. var EPSILON = 0.0000000001;
  17523. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17524. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17525. points.splice( points.length - 1, 1);
  17526. if ( closedPath ) {
  17527. points.push( points[ 0 ] );
  17528. }
  17529. return points;
  17530. };
  17531. // Breaks path into shapes
  17532. THREE.Path.prototype.toShapes = function( isCCW ) {
  17533. var i, il, item, action, args;
  17534. var subPaths = [], lastPath = new THREE.Path();
  17535. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17536. item = this.actions[ i ];
  17537. args = item.args;
  17538. action = item.action;
  17539. if ( action == THREE.PathActions.MOVE_TO ) {
  17540. if ( lastPath.actions.length != 0 ) {
  17541. subPaths.push( lastPath );
  17542. lastPath = new THREE.Path();
  17543. }
  17544. }
  17545. lastPath[ action ].apply( lastPath, args );
  17546. }
  17547. if ( lastPath.actions.length != 0 ) {
  17548. subPaths.push( lastPath );
  17549. }
  17550. // console.log(subPaths);
  17551. if ( subPaths.length == 0 ) return [];
  17552. var solid, tmpPath, tmpShape, shapes = [];
  17553. if ( subPaths.length == 1) {
  17554. tmpPath = subPaths[0];
  17555. tmpShape = new THREE.Shape();
  17556. tmpShape.actions = tmpPath.actions;
  17557. tmpShape.curves = tmpPath.curves;
  17558. shapes.push( tmpShape );
  17559. return shapes;
  17560. }
  17561. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17562. holesFirst = isCCW ? !holesFirst : holesFirst;
  17563. // console.log("Holes first", holesFirst);
  17564. if ( holesFirst ) {
  17565. tmpShape = new THREE.Shape();
  17566. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17567. tmpPath = subPaths[ i ];
  17568. solid = THREE.Shape.Utils.isClockWise( tmpPath.getPoints() );
  17569. solid = isCCW ? !solid : solid;
  17570. if ( solid ) {
  17571. tmpShape.actions = tmpPath.actions;
  17572. tmpShape.curves = tmpPath.curves;
  17573. shapes.push( tmpShape );
  17574. tmpShape = new THREE.Shape();
  17575. //console.log('cw', i);
  17576. } else {
  17577. tmpShape.holes.push( tmpPath );
  17578. //console.log('ccw', i);
  17579. }
  17580. }
  17581. } else {
  17582. // Shapes first
  17583. tmpShape = undefined;
  17584. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17585. tmpPath = subPaths[ i ];
  17586. solid = THREE.Shape.Utils.isClockWise( tmpPath.getPoints() );
  17587. solid = isCCW ? !solid : solid;
  17588. if ( solid ) {
  17589. if ( tmpShape ) shapes.push( tmpShape );
  17590. tmpShape = new THREE.Shape();
  17591. tmpShape.actions = tmpPath.actions;
  17592. tmpShape.curves = tmpPath.curves;
  17593. } else {
  17594. tmpShape.holes.push( tmpPath );
  17595. }
  17596. }
  17597. shapes.push( tmpShape );
  17598. }
  17599. //console.log("shape", shapes);
  17600. return shapes;
  17601. };
  17602. /**
  17603. * @author zz85 / http://www.lab4games.net/zz85/blog
  17604. * Defines a 2d shape plane using paths.
  17605. **/
  17606. // STEP 1 Create a path.
  17607. // STEP 2 Turn path into shape.
  17608. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17609. // STEP 3a - Extract points from each shape, turn to vertices
  17610. // STEP 3b - Triangulate each shape, add faces.
  17611. THREE.Shape = function () {
  17612. THREE.Path.apply( this, arguments );
  17613. this.holes = [];
  17614. };
  17615. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17616. // Convenience method to return ExtrudeGeometry
  17617. THREE.Shape.prototype.extrude = function ( options ) {
  17618. var extruded = new THREE.ExtrudeGeometry( this, options );
  17619. return extruded;
  17620. };
  17621. // Convenience method to return ShapeGeometry
  17622. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17623. var geometry = new THREE.ShapeGeometry( this, options );
  17624. return geometry;
  17625. };
  17626. // Get points of holes
  17627. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17628. var i, il = this.holes.length, holesPts = [];
  17629. for ( i = 0; i < il; i ++ ) {
  17630. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17631. }
  17632. return holesPts;
  17633. };
  17634. // Get points of holes (spaced by regular distance)
  17635. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17636. var i, il = this.holes.length, holesPts = [];
  17637. for ( i = 0; i < il; i ++ ) {
  17638. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17639. }
  17640. return holesPts;
  17641. };
  17642. // Get points of shape and holes (keypoints based on segments parameter)
  17643. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17644. return {
  17645. shape: this.getTransformedPoints( divisions ),
  17646. holes: this.getPointsHoles( divisions )
  17647. };
  17648. };
  17649. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17650. if (this.useSpacedPoints) {
  17651. return this.extractAllSpacedPoints(divisions);
  17652. }
  17653. return this.extractAllPoints(divisions);
  17654. };
  17655. //
  17656. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17657. //
  17658. // return {
  17659. //
  17660. // shape: this.transform( bend, divisions ),
  17661. // holes: this.getPointsHoles( divisions, bend )
  17662. //
  17663. // };
  17664. //
  17665. // };
  17666. // Get points of shape and holes (spaced by regular distance)
  17667. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17668. return {
  17669. shape: this.getTransformedSpacedPoints( divisions ),
  17670. holes: this.getSpacedPointsHoles( divisions )
  17671. };
  17672. };
  17673. /**************************************************************
  17674. * Utils
  17675. **************************************************************/
  17676. THREE.Shape.Utils = {
  17677. /*
  17678. contour - array of vector2 for contour
  17679. holes - array of array of vector2
  17680. */
  17681. removeHoles: function ( contour, holes ) {
  17682. var shape = contour.concat(); // work on this shape
  17683. var allpoints = shape.concat();
  17684. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  17685. var prevShapeVert, nextShapeVert,
  17686. prevHoleVert, nextHoleVert,
  17687. holeIndex, shapeIndex,
  17688. shapeId, shapeGroup,
  17689. h, h2,
  17690. hole, shortest, d,
  17691. p, pts1, pts2,
  17692. tmpShape1, tmpShape2,
  17693. tmpHole1, tmpHole2,
  17694. verts = [];
  17695. for ( h = 0; h < holes.length; h ++ ) {
  17696. hole = holes[ h ];
  17697. /*
  17698. shapeholes[ h ].concat(); // preserves original
  17699. holes.push( hole );
  17700. */
  17701. Array.prototype.push.apply( allpoints, hole );
  17702. shortest = Number.POSITIVE_INFINITY;
  17703. // Find the shortest pair of pts between shape and hole
  17704. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  17705. // Using distanceToSquared() intead of distanceTo() should speed a little
  17706. // since running square roots operations are reduced.
  17707. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  17708. pts1 = hole[ h2 ];
  17709. var dist = [];
  17710. for ( p = 0; p < shape.length; p++ ) {
  17711. pts2 = shape[ p ];
  17712. d = pts1.distanceToSquared( pts2 );
  17713. dist.push( d );
  17714. if ( d < shortest ) {
  17715. shortest = d;
  17716. holeIndex = h2;
  17717. shapeIndex = p;
  17718. }
  17719. }
  17720. }
  17721. //console.log("shortest", shortest, dist);
  17722. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17723. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17724. var areaapts = [
  17725. hole[ holeIndex ],
  17726. shape[ shapeIndex ],
  17727. shape[ prevShapeVert ]
  17728. ];
  17729. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  17730. var areabpts = [
  17731. hole[ holeIndex ],
  17732. hole[ prevHoleVert ],
  17733. shape[ shapeIndex ]
  17734. ];
  17735. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  17736. var shapeOffset = 1;
  17737. var holeOffset = -1;
  17738. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  17739. shapeIndex += shapeOffset;
  17740. holeIndex += holeOffset;
  17741. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17742. shapeIndex %= shape.length;
  17743. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17744. holeIndex %= hole.length;
  17745. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17746. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17747. areaapts = [
  17748. hole[ holeIndex ],
  17749. shape[ shapeIndex ],
  17750. shape[ prevShapeVert ]
  17751. ];
  17752. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  17753. areabpts = [
  17754. hole[ holeIndex ],
  17755. hole[ prevHoleVert ],
  17756. shape[ shapeIndex ]
  17757. ];
  17758. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  17759. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  17760. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  17761. // In case areas are not correct.
  17762. //console.log("USE THIS");
  17763. shapeIndex = oldShapeIndex;
  17764. holeIndex = oldHoleIndex ;
  17765. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17766. shapeIndex %= shape.length;
  17767. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17768. holeIndex %= hole.length;
  17769. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17770. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17771. } else {
  17772. //console.log("USE THAT ")
  17773. }
  17774. tmpShape1 = shape.slice( 0, shapeIndex );
  17775. tmpShape2 = shape.slice( shapeIndex );
  17776. tmpHole1 = hole.slice( holeIndex );
  17777. tmpHole2 = hole.slice( 0, holeIndex );
  17778. // Should check orders here again?
  17779. var trianglea = [
  17780. hole[ holeIndex ],
  17781. shape[ shapeIndex ],
  17782. shape[ prevShapeVert ]
  17783. ];
  17784. var triangleb = [
  17785. hole[ holeIndex ] ,
  17786. hole[ prevHoleVert ],
  17787. shape[ shapeIndex ]
  17788. ];
  17789. verts.push( trianglea );
  17790. verts.push( triangleb );
  17791. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17792. }
  17793. return {
  17794. shape:shape, /* shape with no holes */
  17795. isolatedPts: verts, /* isolated faces */
  17796. allpoints: allpoints
  17797. }
  17798. },
  17799. triangulateShape: function ( contour, holes ) {
  17800. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  17801. var shape = shapeWithoutHoles.shape,
  17802. allpoints = shapeWithoutHoles.allpoints,
  17803. isolatedPts = shapeWithoutHoles.isolatedPts;
  17804. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  17805. // 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.
  17806. //console.log( "triangles",triangles, triangles.length );
  17807. //console.log( "allpoints",allpoints, allpoints.length );
  17808. var i, il, f, face,
  17809. key, index,
  17810. allPointsMap = {},
  17811. isolatedPointsMap = {};
  17812. // prepare all points map
  17813. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17814. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17815. if ( allPointsMap[ key ] !== undefined ) {
  17816. console.log( "Duplicate point", key );
  17817. }
  17818. allPointsMap[ key ] = i;
  17819. }
  17820. // check all face vertices against all points map
  17821. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17822. face = triangles[ i ];
  17823. for ( f = 0; f < 3; f ++ ) {
  17824. key = face[ f ].x + ":" + face[ f ].y;
  17825. index = allPointsMap[ key ];
  17826. if ( index !== undefined ) {
  17827. face[ f ] = index;
  17828. }
  17829. }
  17830. }
  17831. // check isolated points vertices against all points map
  17832. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  17833. face = isolatedPts[ i ];
  17834. for ( f = 0; f < 3; f ++ ) {
  17835. key = face[ f ].x + ":" + face[ f ].y;
  17836. index = allPointsMap[ key ];
  17837. if ( index !== undefined ) {
  17838. face[ f ] = index;
  17839. }
  17840. }
  17841. }
  17842. return triangles.concat( isolatedPts );
  17843. }, // end triangulate shapes
  17844. /*
  17845. triangulate2 : function( pts, holes ) {
  17846. // For use with Poly2Tri.js
  17847. var allpts = pts.concat();
  17848. var shape = [];
  17849. for (var p in pts) {
  17850. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  17851. }
  17852. var swctx = new js.poly2tri.SweepContext(shape);
  17853. for (var h in holes) {
  17854. var aHole = holes[h];
  17855. var newHole = []
  17856. for (i in aHole) {
  17857. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  17858. allpts.push(aHole[i]);
  17859. }
  17860. swctx.AddHole(newHole);
  17861. }
  17862. var find;
  17863. var findIndexForPt = function (pt) {
  17864. find = new THREE.Vector2(pt.x, pt.y);
  17865. var p;
  17866. for (p=0, pl = allpts.length; p<pl; p++) {
  17867. if (allpts[p].equals(find)) return p;
  17868. }
  17869. return -1;
  17870. };
  17871. // triangulate
  17872. js.poly2tri.sweep.Triangulate(swctx);
  17873. var triangles = swctx.GetTriangles();
  17874. var tr ;
  17875. var facesPts = [];
  17876. for (var t in triangles) {
  17877. tr = triangles[t];
  17878. facesPts.push([
  17879. findIndexForPt(tr.GetPoint(0)),
  17880. findIndexForPt(tr.GetPoint(1)),
  17881. findIndexForPt(tr.GetPoint(2))
  17882. ]);
  17883. }
  17884. // console.log(facesPts);
  17885. // console.log("triangles", triangles.length, triangles);
  17886. // Returns array of faces with 3 element each
  17887. return facesPts;
  17888. },
  17889. */
  17890. isClockWise: function ( pts ) {
  17891. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17892. },
  17893. // Bezier Curves formulas obtained from
  17894. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17895. // Quad Bezier Functions
  17896. b2p0: function ( t, p ) {
  17897. var k = 1 - t;
  17898. return k * k * p;
  17899. },
  17900. b2p1: function ( t, p ) {
  17901. return 2 * ( 1 - t ) * t * p;
  17902. },
  17903. b2p2: function ( t, p ) {
  17904. return t * t * p;
  17905. },
  17906. b2: function ( t, p0, p1, p2 ) {
  17907. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17908. },
  17909. // Cubic Bezier Functions
  17910. b3p0: function ( t, p ) {
  17911. var k = 1 - t;
  17912. return k * k * k * p;
  17913. },
  17914. b3p1: function ( t, p ) {
  17915. var k = 1 - t;
  17916. return 3 * k * k * t * p;
  17917. },
  17918. b3p2: function ( t, p ) {
  17919. var k = 1 - t;
  17920. return 3 * k * t * t * p;
  17921. },
  17922. b3p3: function ( t, p ) {
  17923. return t * t * t * p;
  17924. },
  17925. b3: function ( t, p0, p1, p2, p3 ) {
  17926. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17927. }
  17928. };
  17929. /**************************************************************
  17930. * Line
  17931. **************************************************************/
  17932. THREE.LineCurve = function ( v1, v2 ) {
  17933. this.v1 = v1;
  17934. this.v2 = v2;
  17935. };
  17936. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  17937. THREE.LineCurve.prototype.getPoint = function ( t ) {
  17938. var point = this.v2.clone().sub(this.v1);
  17939. point.multiplyScalar( t ).add( this.v1 );
  17940. return point;
  17941. };
  17942. // Line curve is linear, so we can overwrite default getPointAt
  17943. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  17944. return this.getPoint( u );
  17945. };
  17946. THREE.LineCurve.prototype.getTangent = function( t ) {
  17947. var tangent = this.v2.clone().sub(this.v1);
  17948. return tangent.normalize();
  17949. };
  17950. /**************************************************************
  17951. * Quadratic Bezier curve
  17952. **************************************************************/
  17953. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  17954. this.v0 = v0;
  17955. this.v1 = v1;
  17956. this.v2 = v2;
  17957. };
  17958. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17959. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  17960. var tx, ty;
  17961. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17962. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17963. return new THREE.Vector2( tx, ty );
  17964. };
  17965. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  17966. var tx, ty;
  17967. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  17968. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  17969. // returns unit vector
  17970. var tangent = new THREE.Vector2( tx, ty );
  17971. tangent.normalize();
  17972. return tangent;
  17973. };
  17974. /**************************************************************
  17975. * Cubic Bezier curve
  17976. **************************************************************/
  17977. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  17978. this.v0 = v0;
  17979. this.v1 = v1;
  17980. this.v2 = v2;
  17981. this.v3 = v3;
  17982. };
  17983. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17984. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  17985. var tx, ty;
  17986. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17987. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17988. return new THREE.Vector2( tx, ty );
  17989. };
  17990. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  17991. var tx, ty;
  17992. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17993. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17994. var tangent = new THREE.Vector2( tx, ty );
  17995. tangent.normalize();
  17996. return tangent;
  17997. };
  17998. /**************************************************************
  17999. * Spline curve
  18000. **************************************************************/
  18001. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  18002. this.points = (points == undefined) ? [] : points;
  18003. };
  18004. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  18005. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  18006. var v = new THREE.Vector2();
  18007. var c = [];
  18008. var points = this.points, point, intPoint, weight;
  18009. point = ( points.length - 1 ) * t;
  18010. intPoint = Math.floor( point );
  18011. weight = point - intPoint;
  18012. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18013. c[ 1 ] = intPoint;
  18014. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  18015. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  18016. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  18017. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  18018. return v;
  18019. };
  18020. /**************************************************************
  18021. * Ellipse curve
  18022. **************************************************************/
  18023. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  18024. aStartAngle, aEndAngle,
  18025. aClockwise ) {
  18026. this.aX = aX;
  18027. this.aY = aY;
  18028. this.xRadius = xRadius;
  18029. this.yRadius = yRadius;
  18030. this.aStartAngle = aStartAngle;
  18031. this.aEndAngle = aEndAngle;
  18032. this.aClockwise = aClockwise;
  18033. };
  18034. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  18035. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  18036. var deltaAngle = this.aEndAngle - this.aStartAngle;
  18037. if ( !this.aClockwise ) {
  18038. t = 1 - t;
  18039. }
  18040. var angle = this.aStartAngle + t * deltaAngle;
  18041. var tx = this.aX + this.xRadius * Math.cos( angle );
  18042. var ty = this.aY + this.yRadius * Math.sin( angle );
  18043. return new THREE.Vector2( tx, ty );
  18044. };
  18045. /**************************************************************
  18046. * Arc curve
  18047. **************************************************************/
  18048. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  18049. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  18050. };
  18051. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  18052. /**************************************************************
  18053. * Line3D
  18054. **************************************************************/
  18055. THREE.LineCurve3 = THREE.Curve.create(
  18056. function ( v1, v2 ) {
  18057. this.v1 = v1;
  18058. this.v2 = v2;
  18059. },
  18060. function ( t ) {
  18061. var r = new THREE.Vector3();
  18062. r.subVectors( this.v2, this.v1 ); // diff
  18063. r.multiplyScalar( t );
  18064. r.add( this.v1 );
  18065. return r;
  18066. }
  18067. );
  18068. /**************************************************************
  18069. * Quadratic Bezier 3D curve
  18070. **************************************************************/
  18071. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  18072. function ( v0, v1, v2 ) {
  18073. this.v0 = v0;
  18074. this.v1 = v1;
  18075. this.v2 = v2;
  18076. },
  18077. function ( t ) {
  18078. var tx, ty, tz;
  18079. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  18080. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  18081. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  18082. return new THREE.Vector3( tx, ty, tz );
  18083. }
  18084. );
  18085. /**************************************************************
  18086. * Cubic Bezier 3D curve
  18087. **************************************************************/
  18088. THREE.CubicBezierCurve3 = THREE.Curve.create(
  18089. function ( v0, v1, v2, v3 ) {
  18090. this.v0 = v0;
  18091. this.v1 = v1;
  18092. this.v2 = v2;
  18093. this.v3 = v3;
  18094. },
  18095. function ( t ) {
  18096. var tx, ty, tz;
  18097. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  18098. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  18099. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  18100. return new THREE.Vector3( tx, ty, tz );
  18101. }
  18102. );
  18103. /**************************************************************
  18104. * Spline 3D curve
  18105. **************************************************************/
  18106. THREE.SplineCurve3 = THREE.Curve.create(
  18107. function ( points /* array of Vector3 */) {
  18108. this.points = (points == undefined) ? [] : points;
  18109. },
  18110. function ( t ) {
  18111. var v = new THREE.Vector3();
  18112. var c = [];
  18113. var points = this.points, point, intPoint, weight;
  18114. point = ( points.length - 1 ) * t;
  18115. intPoint = Math.floor( point );
  18116. weight = point - intPoint;
  18117. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18118. c[ 1 ] = intPoint;
  18119. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  18120. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  18121. var pt0 = points[ c[0] ],
  18122. pt1 = points[ c[1] ],
  18123. pt2 = points[ c[2] ],
  18124. pt3 = points[ c[3] ];
  18125. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  18126. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  18127. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  18128. return v;
  18129. }
  18130. );
  18131. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  18132. // var v = new THREE.Vector3();
  18133. // var c = [];
  18134. // var points = this.points, point, intPoint, weight;
  18135. // point = ( points.length - 1 ) * t;
  18136. // intPoint = Math.floor( point );
  18137. // weight = point - intPoint;
  18138. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18139. // c[ 1 ] = intPoint;
  18140. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  18141. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  18142. // var pt0 = points[ c[0] ],
  18143. // pt1 = points[ c[1] ],
  18144. // pt2 = points[ c[2] ],
  18145. // pt3 = points[ c[3] ];
  18146. // // t = weight;
  18147. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  18148. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  18149. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  18150. // return v;
  18151. // }
  18152. /**************************************************************
  18153. * Closed Spline 3D curve
  18154. **************************************************************/
  18155. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  18156. function ( points /* array of Vector3 */) {
  18157. this.points = (points == undefined) ? [] : points;
  18158. },
  18159. function ( t ) {
  18160. var v = new THREE.Vector3();
  18161. var c = [];
  18162. var points = this.points, point, intPoint, weight;
  18163. point = ( points.length - 0 ) * t;
  18164. // This needs to be from 0-length +1
  18165. intPoint = Math.floor( point );
  18166. weight = point - intPoint;
  18167. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  18168. c[ 0 ] = ( intPoint - 1 ) % points.length;
  18169. c[ 1 ] = ( intPoint ) % points.length;
  18170. c[ 2 ] = ( intPoint + 1 ) % points.length;
  18171. c[ 3 ] = ( intPoint + 2 ) % points.length;
  18172. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  18173. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  18174. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  18175. return v;
  18176. }
  18177. );
  18178. /**
  18179. * @author mikael emtinger / http://gomo.se/
  18180. */
  18181. THREE.AnimationHandler = (function() {
  18182. var playing = [];
  18183. var library = {};
  18184. var that = {};
  18185. //--- update ---
  18186. that.update = function( deltaTimeMS ) {
  18187. for( var i = 0; i < playing.length; i ++ )
  18188. playing[ i ].update( deltaTimeMS );
  18189. };
  18190. //--- add ---
  18191. that.addToUpdate = function( animation ) {
  18192. if ( playing.indexOf( animation ) === -1 )
  18193. playing.push( animation );
  18194. };
  18195. //--- remove ---
  18196. that.removeFromUpdate = function( animation ) {
  18197. var index = playing.indexOf( animation );
  18198. if( index !== -1 )
  18199. playing.splice( index, 1 );
  18200. };
  18201. //--- add ---
  18202. that.add = function( data ) {
  18203. if ( library[ data.name ] !== undefined )
  18204. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  18205. library[ data.name ] = data;
  18206. initData( data );
  18207. };
  18208. //--- get ---
  18209. that.get = function( name ) {
  18210. if ( typeof name === "string" ) {
  18211. if ( library[ name ] ) {
  18212. return library[ name ];
  18213. } else {
  18214. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  18215. return null;
  18216. }
  18217. } else {
  18218. // todo: add simple tween library
  18219. }
  18220. };
  18221. //--- parse ---
  18222. that.parse = function( root ) {
  18223. // setup hierarchy
  18224. var hierarchy = [];
  18225. if ( root instanceof THREE.SkinnedMesh ) {
  18226. for( var b = 0; b < root.bones.length; b++ ) {
  18227. hierarchy.push( root.bones[ b ] );
  18228. }
  18229. } else {
  18230. parseRecurseHierarchy( root, hierarchy );
  18231. }
  18232. return hierarchy;
  18233. };
  18234. var parseRecurseHierarchy = function( root, hierarchy ) {
  18235. hierarchy.push( root );
  18236. for( var c = 0; c < root.children.length; c++ )
  18237. parseRecurseHierarchy( root.children[ c ], hierarchy );
  18238. }
  18239. //--- init data ---
  18240. var initData = function( data ) {
  18241. if( data.initialized === true )
  18242. return;
  18243. // loop through all keys
  18244. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  18245. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18246. // remove minus times
  18247. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  18248. data.hierarchy[ h ].keys[ k ].time = 0;
  18249. // create quaternions
  18250. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  18251. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  18252. var quat = data.hierarchy[ h ].keys[ k ].rot;
  18253. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  18254. }
  18255. }
  18256. // prepare morph target keys
  18257. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  18258. // get all used
  18259. var usedMorphTargets = {};
  18260. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18261. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18262. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  18263. usedMorphTargets[ morphTargetName ] = -1;
  18264. }
  18265. }
  18266. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  18267. // set all used on all frames
  18268. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18269. var influences = {};
  18270. for ( var morphTargetName in usedMorphTargets ) {
  18271. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18272. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  18273. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  18274. break;
  18275. }
  18276. }
  18277. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  18278. influences[ morphTargetName ] = 0;
  18279. }
  18280. }
  18281. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  18282. }
  18283. }
  18284. // remove all keys that are on the same time
  18285. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18286. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  18287. data.hierarchy[ h ].keys.splice( k, 1 );
  18288. k --;
  18289. }
  18290. }
  18291. // set index
  18292. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18293. data.hierarchy[ h ].keys[ k ].index = k;
  18294. }
  18295. }
  18296. // JIT
  18297. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  18298. data.JIT = {};
  18299. data.JIT.hierarchy = [];
  18300. for( var h = 0; h < data.hierarchy.length; h ++ )
  18301. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  18302. // done
  18303. data.initialized = true;
  18304. };
  18305. // interpolation types
  18306. that.LINEAR = 0;
  18307. that.CATMULLROM = 1;
  18308. that.CATMULLROM_FORWARD = 2;
  18309. return that;
  18310. }());
  18311. /**
  18312. * @author mikael emtinger / http://gomo.se/
  18313. * @author mrdoob / http://mrdoob.com/
  18314. * @author alteredq / http://alteredqualia.com/
  18315. */
  18316. THREE.Animation = function ( root, name, interpolationType ) {
  18317. this.root = root;
  18318. this.data = THREE.AnimationHandler.get( name );
  18319. this.hierarchy = THREE.AnimationHandler.parse( root );
  18320. this.currentTime = 0;
  18321. this.timeScale = 1;
  18322. this.isPlaying = false;
  18323. this.isPaused = true;
  18324. this.loop = true;
  18325. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  18326. this.points = [];
  18327. this.target = new THREE.Vector3();
  18328. };
  18329. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  18330. if ( this.isPlaying === false ) {
  18331. this.isPlaying = true;
  18332. this.loop = loop !== undefined ? loop : true;
  18333. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  18334. // reset key cache
  18335. var h, hl = this.hierarchy.length,
  18336. object;
  18337. for ( h = 0; h < hl; h ++ ) {
  18338. object = this.hierarchy[ h ];
  18339. object.matrixAutoUpdate = true;
  18340. if ( object.animationCache === undefined ) {
  18341. object.animationCache = {};
  18342. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  18343. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  18344. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18345. }
  18346. var prevKey = object.animationCache.prevKey;
  18347. var nextKey = object.animationCache.nextKey;
  18348. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  18349. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  18350. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  18351. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  18352. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  18353. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  18354. }
  18355. this.update( 0 );
  18356. }
  18357. this.isPaused = false;
  18358. THREE.AnimationHandler.addToUpdate( this );
  18359. };
  18360. THREE.Animation.prototype.pause = function() {
  18361. if ( this.isPaused === true ) {
  18362. THREE.AnimationHandler.addToUpdate( this );
  18363. } else {
  18364. THREE.AnimationHandler.removeFromUpdate( this );
  18365. }
  18366. this.isPaused = !this.isPaused;
  18367. };
  18368. THREE.Animation.prototype.stop = function() {
  18369. this.isPlaying = false;
  18370. this.isPaused = false;
  18371. THREE.AnimationHandler.removeFromUpdate( this );
  18372. };
  18373. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  18374. // early out
  18375. if ( this.isPlaying === false ) return;
  18376. // vars
  18377. var types = [ "pos", "rot", "scl" ];
  18378. var type;
  18379. var scale;
  18380. var vector;
  18381. var prevXYZ, nextXYZ;
  18382. var prevKey, nextKey;
  18383. var object;
  18384. var animationCache;
  18385. var frame;
  18386. var JIThierarchy = this.data.JIT.hierarchy;
  18387. var currentTime, unloopedCurrentTime;
  18388. var currentPoint, forwardPoint, angle;
  18389. this.currentTime += deltaTimeMS * this.timeScale;
  18390. unloopedCurrentTime = this.currentTime;
  18391. currentTime = this.currentTime = this.currentTime % this.data.length;
  18392. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18393. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18394. object = this.hierarchy[ h ];
  18395. animationCache = object.animationCache;
  18396. // loop through pos/rot/scl
  18397. for ( var t = 0; t < 3; t ++ ) {
  18398. // get keys
  18399. type = types[ t ];
  18400. prevKey = animationCache.prevKey[ type ];
  18401. nextKey = animationCache.nextKey[ type ];
  18402. // switch keys?
  18403. if ( nextKey.time <= unloopedCurrentTime ) {
  18404. // did we loop?
  18405. if ( currentTime < unloopedCurrentTime ) {
  18406. if ( this.loop ) {
  18407. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  18408. nextKey = this.getNextKeyWith( type, h, 1 );
  18409. while( nextKey.time < currentTime ) {
  18410. prevKey = nextKey;
  18411. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18412. }
  18413. } else {
  18414. this.stop();
  18415. return;
  18416. }
  18417. } else {
  18418. do {
  18419. prevKey = nextKey;
  18420. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18421. } while( nextKey.time < currentTime )
  18422. }
  18423. animationCache.prevKey[ type ] = prevKey;
  18424. animationCache.nextKey[ type ] = nextKey;
  18425. }
  18426. object.matrixAutoUpdate = true;
  18427. object.matrixWorldNeedsUpdate = true;
  18428. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  18429. prevXYZ = prevKey[ type ];
  18430. nextXYZ = nextKey[ type ];
  18431. // check scale error
  18432. if ( scale < 0 || scale > 1 ) {
  18433. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  18434. scale = scale < 0 ? 0 : 1;
  18435. }
  18436. // interpolate
  18437. if ( type === "pos" ) {
  18438. vector = object.position;
  18439. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  18440. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18441. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18442. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18443. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18444. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18445. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  18446. this.points[ 1 ] = prevXYZ;
  18447. this.points[ 2 ] = nextXYZ;
  18448. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  18449. scale = scale * 0.33 + 0.33;
  18450. currentPoint = this.interpolateCatmullRom( this.points, scale );
  18451. vector.x = currentPoint[ 0 ];
  18452. vector.y = currentPoint[ 1 ];
  18453. vector.z = currentPoint[ 2 ];
  18454. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18455. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  18456. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  18457. this.target.sub( vector );
  18458. this.target.y = 0;
  18459. this.target.normalize();
  18460. angle = Math.atan2( this.target.x, this.target.z );
  18461. object.rotation.set( 0, angle, 0 );
  18462. }
  18463. }
  18464. } else if ( type === "rot" ) {
  18465. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  18466. } else if ( type === "scl" ) {
  18467. vector = object.scale;
  18468. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18469. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18470. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18471. }
  18472. }
  18473. }
  18474. };
  18475. // Catmull-Rom spline
  18476. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  18477. var c = [], v3 = [],
  18478. point, intPoint, weight, w2, w3,
  18479. pa, pb, pc, pd;
  18480. point = ( points.length - 1 ) * scale;
  18481. intPoint = Math.floor( point );
  18482. weight = point - intPoint;
  18483. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  18484. c[ 1 ] = intPoint;
  18485. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  18486. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  18487. pa = points[ c[ 0 ] ];
  18488. pb = points[ c[ 1 ] ];
  18489. pc = points[ c[ 2 ] ];
  18490. pd = points[ c[ 3 ] ];
  18491. w2 = weight * weight;
  18492. w3 = weight * w2;
  18493. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  18494. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  18495. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  18496. return v3;
  18497. };
  18498. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  18499. var v0 = ( p2 - p0 ) * 0.5,
  18500. v1 = ( p3 - p1 ) * 0.5;
  18501. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18502. };
  18503. // Get next key with
  18504. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  18505. var keys = this.data.hierarchy[ h ].keys;
  18506. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18507. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18508. key = key < keys.length - 1 ? key : keys.length - 1;
  18509. } else {
  18510. key = key % keys.length;
  18511. }
  18512. for ( ; key < keys.length; key++ ) {
  18513. if ( keys[ key ][ type ] !== undefined ) {
  18514. return keys[ key ];
  18515. }
  18516. }
  18517. return this.data.hierarchy[ h ].keys[ 0 ];
  18518. };
  18519. // Get previous key with
  18520. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  18521. var keys = this.data.hierarchy[ h ].keys;
  18522. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18523. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18524. key = key > 0 ? key : 0;
  18525. } else {
  18526. key = key >= 0 ? key : key + keys.length;
  18527. }
  18528. for ( ; key >= 0; key -- ) {
  18529. if ( keys[ key ][ type ] !== undefined ) {
  18530. return keys[ key ];
  18531. }
  18532. }
  18533. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  18534. };
  18535. /**
  18536. * @author mikael emtinger / http://gomo.se/
  18537. * @author mrdoob / http://mrdoob.com/
  18538. * @author alteredq / http://alteredqualia.com/
  18539. * @author khang duong
  18540. * @author erik kitson
  18541. */
  18542. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  18543. this.root = root;
  18544. this.data = THREE.AnimationHandler.get( data );
  18545. this.hierarchy = THREE.AnimationHandler.parse( root );
  18546. this.currentTime = 0;
  18547. this.timeScale = 0.001;
  18548. this.isPlaying = false;
  18549. this.isPaused = true;
  18550. this.loop = true;
  18551. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  18552. // initialize to first keyframes
  18553. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18554. var keys = this.data.hierarchy[h].keys,
  18555. sids = this.data.hierarchy[h].sids,
  18556. obj = this.hierarchy[h];
  18557. if ( keys.length && sids ) {
  18558. for ( var s = 0; s < sids.length; s++ ) {
  18559. var sid = sids[ s ],
  18560. next = this.getNextKeyWith( sid, h, 0 );
  18561. if ( next ) {
  18562. next.apply( sid );
  18563. }
  18564. }
  18565. obj.matrixAutoUpdate = false;
  18566. this.data.hierarchy[h].node.updateMatrix();
  18567. obj.matrixWorldNeedsUpdate = true;
  18568. }
  18569. }
  18570. };
  18571. // Play
  18572. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  18573. if( !this.isPlaying ) {
  18574. this.isPlaying = true;
  18575. this.loop = loop !== undefined ? loop : true;
  18576. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  18577. this.startTimeMs = startTimeMS;
  18578. this.startTime = 10000000;
  18579. this.endTime = -this.startTime;
  18580. // reset key cache
  18581. var h, hl = this.hierarchy.length,
  18582. object,
  18583. node;
  18584. for ( h = 0; h < hl; h++ ) {
  18585. object = this.hierarchy[ h ];
  18586. node = this.data.hierarchy[ h ];
  18587. if ( node.animationCache === undefined ) {
  18588. node.animationCache = {};
  18589. node.animationCache.prevKey = null;
  18590. node.animationCache.nextKey = null;
  18591. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18592. }
  18593. var keys = this.data.hierarchy[h].keys;
  18594. if (keys.length) {
  18595. node.animationCache.prevKey = keys[ 0 ];
  18596. node.animationCache.nextKey = keys[ 1 ];
  18597. this.startTime = Math.min( keys[0].time, this.startTime );
  18598. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18599. }
  18600. }
  18601. this.update( 0 );
  18602. }
  18603. this.isPaused = false;
  18604. THREE.AnimationHandler.addToUpdate( this );
  18605. };
  18606. // Pause
  18607. THREE.KeyFrameAnimation.prototype.pause = function() {
  18608. if( this.isPaused ) {
  18609. THREE.AnimationHandler.addToUpdate( this );
  18610. } else {
  18611. THREE.AnimationHandler.removeFromUpdate( this );
  18612. }
  18613. this.isPaused = !this.isPaused;
  18614. };
  18615. // Stop
  18616. THREE.KeyFrameAnimation.prototype.stop = function() {
  18617. this.isPlaying = false;
  18618. this.isPaused = false;
  18619. THREE.AnimationHandler.removeFromUpdate( this );
  18620. // reset JIT matrix and remove cache
  18621. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  18622. var obj = this.hierarchy[ h ];
  18623. var node = this.data.hierarchy[ h ];
  18624. if ( node.animationCache !== undefined ) {
  18625. var original = node.animationCache.originalMatrix;
  18626. if( obj instanceof THREE.Bone ) {
  18627. original.copy( obj.skinMatrix );
  18628. obj.skinMatrix = original;
  18629. } else {
  18630. original.copy( obj.matrix );
  18631. obj.matrix = original;
  18632. }
  18633. delete node.animationCache;
  18634. }
  18635. }
  18636. };
  18637. // Update
  18638. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  18639. // early out
  18640. if( !this.isPlaying ) return;
  18641. // vars
  18642. var prevKey, nextKey;
  18643. var object;
  18644. var node;
  18645. var frame;
  18646. var JIThierarchy = this.data.JIT.hierarchy;
  18647. var currentTime, unloopedCurrentTime;
  18648. var looped;
  18649. // update
  18650. this.currentTime += deltaTimeMS * this.timeScale;
  18651. unloopedCurrentTime = this.currentTime;
  18652. currentTime = this.currentTime = this.currentTime % this.data.length;
  18653. // if looped around, the current time should be based on the startTime
  18654. if ( currentTime < this.startTimeMs ) {
  18655. currentTime = this.currentTime = this.startTimeMs + currentTime;
  18656. }
  18657. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18658. looped = currentTime < unloopedCurrentTime;
  18659. if ( looped && !this.loop ) {
  18660. // Set the animation to the last keyframes and stop
  18661. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18662. var keys = this.data.hierarchy[h].keys,
  18663. sids = this.data.hierarchy[h].sids,
  18664. end = keys.length-1,
  18665. obj = this.hierarchy[h];
  18666. if ( keys.length ) {
  18667. for ( var s = 0; s < sids.length; s++ ) {
  18668. var sid = sids[ s ],
  18669. prev = this.getPrevKeyWith( sid, h, end );
  18670. if ( prev ) {
  18671. prev.apply( sid );
  18672. }
  18673. }
  18674. this.data.hierarchy[h].node.updateMatrix();
  18675. obj.matrixWorldNeedsUpdate = true;
  18676. }
  18677. }
  18678. this.stop();
  18679. return;
  18680. }
  18681. // check pre-infinity
  18682. if ( currentTime < this.startTime ) {
  18683. return;
  18684. }
  18685. // update
  18686. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18687. object = this.hierarchy[ h ];
  18688. node = this.data.hierarchy[ h ];
  18689. var keys = node.keys,
  18690. animationCache = node.animationCache;
  18691. // use JIT?
  18692. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  18693. if( object instanceof THREE.Bone ) {
  18694. object.skinMatrix = JIThierarchy[ h ][ frame ];
  18695. object.matrixWorldNeedsUpdate = false;
  18696. } else {
  18697. object.matrix = JIThierarchy[ h ][ frame ];
  18698. object.matrixWorldNeedsUpdate = true;
  18699. }
  18700. // use interpolation
  18701. } else if ( keys.length ) {
  18702. // make sure so original matrix and not JIT matrix is set
  18703. if ( this.JITCompile && animationCache ) {
  18704. if( object instanceof THREE.Bone ) {
  18705. object.skinMatrix = animationCache.originalMatrix;
  18706. } else {
  18707. object.matrix = animationCache.originalMatrix;
  18708. }
  18709. }
  18710. prevKey = animationCache.prevKey;
  18711. nextKey = animationCache.nextKey;
  18712. if ( prevKey && nextKey ) {
  18713. // switch keys?
  18714. if ( nextKey.time <= unloopedCurrentTime ) {
  18715. // did we loop?
  18716. if ( looped && this.loop ) {
  18717. prevKey = keys[ 0 ];
  18718. nextKey = keys[ 1 ];
  18719. while ( nextKey.time < currentTime ) {
  18720. prevKey = nextKey;
  18721. nextKey = keys[ prevKey.index + 1 ];
  18722. }
  18723. } else if ( !looped ) {
  18724. var lastIndex = keys.length - 1;
  18725. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  18726. prevKey = nextKey;
  18727. nextKey = keys[ prevKey.index + 1 ];
  18728. }
  18729. }
  18730. animationCache.prevKey = prevKey;
  18731. animationCache.nextKey = nextKey;
  18732. }
  18733. if(nextKey.time >= currentTime)
  18734. prevKey.interpolate( nextKey, currentTime );
  18735. else
  18736. prevKey.interpolate( nextKey, nextKey.time);
  18737. }
  18738. this.data.hierarchy[h].node.updateMatrix();
  18739. object.matrixWorldNeedsUpdate = true;
  18740. }
  18741. }
  18742. // update JIT?
  18743. if ( this.JITCompile ) {
  18744. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  18745. this.hierarchy[ 0 ].updateMatrixWorld( true );
  18746. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  18747. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  18748. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  18749. } else {
  18750. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  18751. }
  18752. }
  18753. }
  18754. }
  18755. };
  18756. // Get next key with
  18757. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18758. var keys = this.data.hierarchy[ h ].keys;
  18759. key = key % keys.length;
  18760. for ( ; key < keys.length; key++ ) {
  18761. if ( keys[ key ].hasTarget( sid ) ) {
  18762. return keys[ key ];
  18763. }
  18764. }
  18765. return keys[ 0 ];
  18766. };
  18767. // Get previous key with
  18768. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18769. var keys = this.data.hierarchy[ h ].keys;
  18770. key = key >= 0 ? key : key + keys.length;
  18771. for ( ; key >= 0; key-- ) {
  18772. if ( keys[ key ].hasTarget( sid ) ) {
  18773. return keys[ key ];
  18774. }
  18775. }
  18776. return keys[ keys.length - 1 ];
  18777. };
  18778. /**
  18779. * Camera for rendering cube maps
  18780. * - renders scene into axis-aligned cube
  18781. *
  18782. * @author alteredq / http://alteredqualia.com/
  18783. */
  18784. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  18785. THREE.Object3D.call( this );
  18786. var fov = 90, aspect = 1;
  18787. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18788. cameraPX.up.set( 0, -1, 0 );
  18789. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  18790. this.add( cameraPX );
  18791. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18792. cameraNX.up.set( 0, -1, 0 );
  18793. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  18794. this.add( cameraNX );
  18795. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18796. cameraPY.up.set( 0, 0, 1 );
  18797. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  18798. this.add( cameraPY );
  18799. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18800. cameraNY.up.set( 0, 0, -1 );
  18801. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  18802. this.add( cameraNY );
  18803. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18804. cameraPZ.up.set( 0, -1, 0 );
  18805. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  18806. this.add( cameraPZ );
  18807. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18808. cameraNZ.up.set( 0, -1, 0 );
  18809. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  18810. this.add( cameraNZ );
  18811. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  18812. this.updateCubeMap = function ( renderer, scene ) {
  18813. var renderTarget = this.renderTarget;
  18814. var generateMipmaps = renderTarget.generateMipmaps;
  18815. renderTarget.generateMipmaps = false;
  18816. renderTarget.activeCubeFace = 0;
  18817. renderer.render( scene, cameraPX, renderTarget );
  18818. renderTarget.activeCubeFace = 1;
  18819. renderer.render( scene, cameraNX, renderTarget );
  18820. renderTarget.activeCubeFace = 2;
  18821. renderer.render( scene, cameraPY, renderTarget );
  18822. renderTarget.activeCubeFace = 3;
  18823. renderer.render( scene, cameraNY, renderTarget );
  18824. renderTarget.activeCubeFace = 4;
  18825. renderer.render( scene, cameraPZ, renderTarget );
  18826. renderTarget.generateMipmaps = generateMipmaps;
  18827. renderTarget.activeCubeFace = 5;
  18828. renderer.render( scene, cameraNZ, renderTarget );
  18829. };
  18830. };
  18831. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  18832. /*
  18833. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  18834. *
  18835. * A general perpose camera, for setting FOV, Lens Focal Length,
  18836. * and switching between perspective and orthographic views easily.
  18837. * Use this only if you do not wish to manage
  18838. * both a Orthographic and Perspective Camera
  18839. *
  18840. */
  18841. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  18842. THREE.Camera.call( this );
  18843. this.fov = fov;
  18844. this.left = -width / 2;
  18845. this.right = width / 2
  18846. this.top = height / 2;
  18847. this.bottom = -height / 2;
  18848. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  18849. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  18850. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  18851. this.zoom = 1;
  18852. this.toPerspective();
  18853. var aspect = width/height;
  18854. };
  18855. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  18856. THREE.CombinedCamera.prototype.toPerspective = function () {
  18857. // Switches to the Perspective Camera
  18858. this.near = this.cameraP.near;
  18859. this.far = this.cameraP.far;
  18860. this.cameraP.fov = this.fov / this.zoom ;
  18861. this.cameraP.updateProjectionMatrix();
  18862. this.projectionMatrix = this.cameraP.projectionMatrix;
  18863. this.inPerspectiveMode = true;
  18864. this.inOrthographicMode = false;
  18865. };
  18866. THREE.CombinedCamera.prototype.toOrthographic = function () {
  18867. // Switches to the Orthographic camera estimating viewport from Perspective
  18868. var fov = this.fov;
  18869. var aspect = this.cameraP.aspect;
  18870. var near = this.cameraP.near;
  18871. var far = this.cameraP.far;
  18872. // The size that we set is the mid plane of the viewing frustum
  18873. var hyperfocus = ( near + far ) / 2;
  18874. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  18875. var planeHeight = 2 * halfHeight;
  18876. var planeWidth = planeHeight * aspect;
  18877. var halfWidth = planeWidth / 2;
  18878. halfHeight /= this.zoom;
  18879. halfWidth /= this.zoom;
  18880. this.cameraO.left = -halfWidth;
  18881. this.cameraO.right = halfWidth;
  18882. this.cameraO.top = halfHeight;
  18883. this.cameraO.bottom = -halfHeight;
  18884. // this.cameraO.left = -farHalfWidth;
  18885. // this.cameraO.right = farHalfWidth;
  18886. // this.cameraO.top = farHalfHeight;
  18887. // this.cameraO.bottom = -farHalfHeight;
  18888. // this.cameraO.left = this.left / this.zoom;
  18889. // this.cameraO.right = this.right / this.zoom;
  18890. // this.cameraO.top = this.top / this.zoom;
  18891. // this.cameraO.bottom = this.bottom / this.zoom;
  18892. this.cameraO.updateProjectionMatrix();
  18893. this.near = this.cameraO.near;
  18894. this.far = this.cameraO.far;
  18895. this.projectionMatrix = this.cameraO.projectionMatrix;
  18896. this.inPerspectiveMode = false;
  18897. this.inOrthographicMode = true;
  18898. };
  18899. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  18900. this.cameraP.aspect = width / height;
  18901. this.left = -width / 2;
  18902. this.right = width / 2
  18903. this.top = height / 2;
  18904. this.bottom = -height / 2;
  18905. };
  18906. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  18907. this.fov = fov;
  18908. if ( this.inPerspectiveMode ) {
  18909. this.toPerspective();
  18910. } else {
  18911. this.toOrthographic();
  18912. }
  18913. };
  18914. // For mantaining similar API with PerspectiveCamera
  18915. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  18916. if ( this.inPerspectiveMode ) {
  18917. this.toPerspective();
  18918. } else {
  18919. this.toPerspective();
  18920. this.toOrthographic();
  18921. }
  18922. };
  18923. /*
  18924. * Uses Focal Length (in mm) to estimate and set FOV
  18925. * 35mm (fullframe) camera is used if frame size is not specified;
  18926. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  18927. */
  18928. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  18929. if ( frameHeight === undefined ) frameHeight = 24;
  18930. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  18931. this.setFov( fov );
  18932. return fov;
  18933. };
  18934. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  18935. this.zoom = zoom;
  18936. if ( this.inPerspectiveMode ) {
  18937. this.toPerspective();
  18938. } else {
  18939. this.toOrthographic();
  18940. }
  18941. };
  18942. THREE.CombinedCamera.prototype.toFrontView = function() {
  18943. this.rotation.x = 0;
  18944. this.rotation.y = 0;
  18945. this.rotation.z = 0;
  18946. // should we be modifing the matrix instead?
  18947. this.rotationAutoUpdate = false;
  18948. };
  18949. THREE.CombinedCamera.prototype.toBackView = function() {
  18950. this.rotation.x = 0;
  18951. this.rotation.y = Math.PI;
  18952. this.rotation.z = 0;
  18953. this.rotationAutoUpdate = false;
  18954. };
  18955. THREE.CombinedCamera.prototype.toLeftView = function() {
  18956. this.rotation.x = 0;
  18957. this.rotation.y = - Math.PI / 2;
  18958. this.rotation.z = 0;
  18959. this.rotationAutoUpdate = false;
  18960. };
  18961. THREE.CombinedCamera.prototype.toRightView = function() {
  18962. this.rotation.x = 0;
  18963. this.rotation.y = Math.PI / 2;
  18964. this.rotation.z = 0;
  18965. this.rotationAutoUpdate = false;
  18966. };
  18967. THREE.CombinedCamera.prototype.toTopView = function() {
  18968. this.rotation.x = - Math.PI / 2;
  18969. this.rotation.y = 0;
  18970. this.rotation.z = 0;
  18971. this.rotationAutoUpdate = false;
  18972. };
  18973. THREE.CombinedCamera.prototype.toBottomView = function() {
  18974. this.rotation.x = Math.PI / 2;
  18975. this.rotation.y = 0;
  18976. this.rotation.z = 0;
  18977. this.rotationAutoUpdate = false;
  18978. };
  18979. /**
  18980. * @author hughes
  18981. */
  18982. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18983. THREE.Geometry.call( this );
  18984. radius = radius || 50;
  18985. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18986. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18987. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18988. var i, uvs = [],
  18989. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18990. this.vertices.push(center);
  18991. uvs.push( centerUV );
  18992. for ( i = 0; i <= segments; i ++ ) {
  18993. var vertex = new THREE.Vector3();
  18994. var segment = thetaStart + i / segments * thetaLength;
  18995. vertex.x = radius * Math.cos( segment );
  18996. vertex.y = radius * Math.sin( segment );
  18997. this.vertices.push( vertex );
  18998. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, ( vertex.y / radius + 1 ) / 2 ) );
  18999. }
  19000. var n = new THREE.Vector3( 0, 0, 1 );
  19001. for ( i = 1; i <= segments; i ++ ) {
  19002. var v1 = i;
  19003. var v2 = i + 1 ;
  19004. var v3 = 0;
  19005. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  19006. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  19007. }
  19008. this.computeCentroids();
  19009. this.computeFaceNormals();
  19010. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19011. };
  19012. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19013. /**
  19014. * @author mrdoob / http://mrdoob.com/
  19015. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  19016. */
  19017. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  19018. THREE.Geometry.call( this );
  19019. var scope = this;
  19020. this.width = width;
  19021. this.height = height;
  19022. this.depth = depth;
  19023. this.widthSegments = widthSegments || 1;
  19024. this.heightSegments = heightSegments || 1;
  19025. this.depthSegments = depthSegments || 1;
  19026. var width_half = this.width / 2;
  19027. var height_half = this.height / 2;
  19028. var depth_half = this.depth / 2;
  19029. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  19030. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  19031. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  19032. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  19033. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  19034. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  19035. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  19036. var w, ix, iy,
  19037. gridX = scope.widthSegments,
  19038. gridY = scope.heightSegments,
  19039. width_half = width / 2,
  19040. height_half = height / 2,
  19041. offset = scope.vertices.length;
  19042. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  19043. w = 'z';
  19044. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  19045. w = 'y';
  19046. gridY = scope.depthSegments;
  19047. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  19048. w = 'x';
  19049. gridX = scope.depthSegments;
  19050. }
  19051. var gridX1 = gridX + 1,
  19052. gridY1 = gridY + 1,
  19053. segment_width = width / gridX,
  19054. segment_height = height / gridY,
  19055. normal = new THREE.Vector3();
  19056. normal[ w ] = depth > 0 ? 1 : - 1;
  19057. for ( iy = 0; iy < gridY1; iy ++ ) {
  19058. for ( ix = 0; ix < gridX1; ix ++ ) {
  19059. var vector = new THREE.Vector3();
  19060. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  19061. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  19062. vector[ w ] = depth;
  19063. scope.vertices.push( vector );
  19064. }
  19065. }
  19066. for ( iy = 0; iy < gridY; iy++ ) {
  19067. for ( ix = 0; ix < gridX; ix++ ) {
  19068. var a = ix + gridX1 * iy;
  19069. var b = ix + gridX1 * ( iy + 1 );
  19070. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  19071. var d = ( ix + 1 ) + gridX1 * iy;
  19072. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  19073. face.normal.copy( normal );
  19074. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  19075. face.materialIndex = materialIndex;
  19076. scope.faces.push( face );
  19077. scope.faceVertexUvs[ 0 ].push( [
  19078. new THREE.Vector2( ix / gridX, 1 - iy / gridY ),
  19079. new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  19080. new THREE.Vector2( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  19081. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY )
  19082. ] );
  19083. }
  19084. }
  19085. }
  19086. this.computeCentroids();
  19087. this.mergeVertices();
  19088. };
  19089. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19090. /**
  19091. * @author mrdoob / http://mrdoob.com/
  19092. */
  19093. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded ) {
  19094. THREE.Geometry.call( this );
  19095. this.radiusTop = radiusTop = radiusTop !== undefined ? radiusTop : 20;
  19096. this.radiusBottom = radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  19097. this.height = height = height !== undefined ? height : 100;
  19098. this.radialSegments = radialSegments = radialSegments || 8;
  19099. this.heightSegments = heightSegments = heightSegments || 1;
  19100. this.openEnded = openEnded = openEnded !== undefined ? openEnded : false;
  19101. var heightHalf = height / 2;
  19102. var x, y, vertices = [], uvs = [];
  19103. for ( y = 0; y <= heightSegments; y ++ ) {
  19104. var verticesRow = [];
  19105. var uvsRow = [];
  19106. var v = y / heightSegments;
  19107. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  19108. for ( x = 0; x <= radialSegments; x ++ ) {
  19109. var u = x / radialSegments;
  19110. var vertex = new THREE.Vector3();
  19111. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  19112. vertex.y = - v * height + heightHalf;
  19113. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  19114. this.vertices.push( vertex );
  19115. verticesRow.push( this.vertices.length - 1 );
  19116. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19117. }
  19118. vertices.push( verticesRow );
  19119. uvs.push( uvsRow );
  19120. }
  19121. var tanTheta = ( radiusBottom - radiusTop ) / height;
  19122. var na, nb;
  19123. for ( x = 0; x < radialSegments; x ++ ) {
  19124. if ( radiusTop !== 0 ) {
  19125. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  19126. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  19127. } else {
  19128. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  19129. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  19130. }
  19131. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  19132. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  19133. for ( y = 0; y < heightSegments; y ++ ) {
  19134. var v1 = vertices[ y ][ x ];
  19135. var v2 = vertices[ y + 1 ][ x ];
  19136. var v3 = vertices[ y + 1 ][ x + 1 ];
  19137. var v4 = vertices[ y ][ x + 1 ];
  19138. var n1 = na.clone();
  19139. var n2 = na.clone();
  19140. var n3 = nb.clone();
  19141. var n4 = nb.clone();
  19142. var uv1 = uvs[ y ][ x ].clone();
  19143. var uv2 = uvs[ y + 1 ][ x ].clone();
  19144. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  19145. var uv4 = uvs[ y ][ x + 1 ].clone();
  19146. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  19147. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  19148. }
  19149. }
  19150. // top cap
  19151. if ( openEnded === false && radiusTop > 0 ) {
  19152. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  19153. for ( x = 0; x < radialSegments; x ++ ) {
  19154. var v1 = vertices[ 0 ][ x ];
  19155. var v2 = vertices[ 0 ][ x + 1 ];
  19156. var v3 = this.vertices.length - 1;
  19157. var n1 = new THREE.Vector3( 0, 1, 0 );
  19158. var n2 = new THREE.Vector3( 0, 1, 0 );
  19159. var n3 = new THREE.Vector3( 0, 1, 0 );
  19160. var uv1 = uvs[ 0 ][ x ].clone();
  19161. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  19162. var uv3 = new THREE.Vector2( uv2.u, 0 );
  19163. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19164. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19165. }
  19166. }
  19167. // bottom cap
  19168. if ( openEnded === false && radiusBottom > 0 ) {
  19169. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  19170. for ( x = 0; x < radialSegments; x ++ ) {
  19171. var v1 = vertices[ y ][ x + 1 ];
  19172. var v2 = vertices[ y ][ x ];
  19173. var v3 = this.vertices.length - 1;
  19174. var n1 = new THREE.Vector3( 0, - 1, 0 );
  19175. var n2 = new THREE.Vector3( 0, - 1, 0 );
  19176. var n3 = new THREE.Vector3( 0, - 1, 0 );
  19177. var uv1 = uvs[ y ][ x + 1 ].clone();
  19178. var uv2 = uvs[ y ][ x ].clone();
  19179. var uv3 = new THREE.Vector2( uv2.u, 1 );
  19180. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19181. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19182. }
  19183. }
  19184. this.computeCentroids();
  19185. this.computeFaceNormals();
  19186. }
  19187. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19188. /**
  19189. * @author zz85 / http://www.lab4games.net/zz85/blog
  19190. *
  19191. * Creates extruded geometry from a path shape.
  19192. *
  19193. * parameters = {
  19194. *
  19195. * size: <float>, // size of the text
  19196. * height: <float>, // thickness to extrude text
  19197. * curveSegments: <int>, // number of points on the curves
  19198. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  19199. * amount: <int>, // Amount
  19200. *
  19201. * bevelEnabled: <bool>, // turn on bevel
  19202. * bevelThickness: <float>, // how deep into text bevel goes
  19203. * bevelSize: <float>, // how far from text outline is bevel
  19204. * bevelSegments: <int>, // number of bevel layers
  19205. *
  19206. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  19207. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  19208. *
  19209. * material: <int> // material index for front and back faces
  19210. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  19211. * uvGenerator: <Object> // object that provides UV generator functions
  19212. *
  19213. * }
  19214. **/
  19215. THREE.ExtrudeGeometry = function ( shapes, options ) {
  19216. if ( typeof( shapes ) === "undefined" ) {
  19217. shapes = [];
  19218. return;
  19219. }
  19220. THREE.Geometry.call( this );
  19221. shapes = shapes instanceof Array ? shapes : [ shapes ];
  19222. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19223. this.addShapeList( shapes, options );
  19224. this.computeCentroids();
  19225. this.computeFaceNormals();
  19226. // can't really use automatic vertex normals
  19227. // as then front and back sides get smoothed too
  19228. // should do separate smoothing just for sides
  19229. //this.computeVertexNormals();
  19230. //console.log( "took", ( Date.now() - startTime ) );
  19231. };
  19232. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19233. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19234. var sl = shapes.length;
  19235. for ( var s = 0; s < sl; s ++ ) {
  19236. var shape = shapes[ s ];
  19237. this.addShape( shape, options );
  19238. }
  19239. };
  19240. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  19241. var amount = options.amount !== undefined ? options.amount : 100;
  19242. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  19243. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  19244. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19245. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  19246. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19247. var steps = options.steps !== undefined ? options.steps : 1;
  19248. var extrudePath = options.extrudePath;
  19249. var extrudePts, extrudeByPath = false;
  19250. var material = options.material;
  19251. var extrudeMaterial = options.extrudeMaterial;
  19252. // Use default WorldUVGenerator if no UV generators are specified.
  19253. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  19254. var shapebb = this.shapebb;
  19255. //shapebb = shape.getBoundingBox();
  19256. var splineTube, binormal, normal, position2;
  19257. if ( extrudePath ) {
  19258. extrudePts = extrudePath.getSpacedPoints( steps );
  19259. extrudeByPath = true;
  19260. bevelEnabled = false; // bevels not supported for path extrusion
  19261. // SETUP TNB variables
  19262. // Reuse TNB from TubeGeomtry for now.
  19263. // TODO1 - have a .isClosed in spline?
  19264. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  19265. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19266. binormal = new THREE.Vector3();
  19267. normal = new THREE.Vector3();
  19268. position2 = new THREE.Vector3();
  19269. }
  19270. // Safeguards if bevels are not enabled
  19271. if ( ! bevelEnabled ) {
  19272. bevelSegments = 0;
  19273. bevelThickness = 0;
  19274. bevelSize = 0;
  19275. }
  19276. // Variables initalization
  19277. var ahole, h, hl; // looping of holes
  19278. var scope = this;
  19279. var bevelPoints = [];
  19280. var shapesOffset = this.vertices.length;
  19281. var shapePoints = shape.extractPoints( curveSegments );
  19282. var vertices = shapePoints.shape;
  19283. var holes = shapePoints.holes;
  19284. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  19285. if ( reverse ) {
  19286. vertices = vertices.reverse();
  19287. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19288. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19289. ahole = holes[ h ];
  19290. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  19291. holes[ h ] = ahole.reverse();
  19292. }
  19293. }
  19294. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  19295. }
  19296. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  19297. /* Vertices */
  19298. var contour = vertices; // vertices has all points but contour has only points of circumference
  19299. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19300. ahole = holes[ h ];
  19301. vertices = vertices.concat( ahole );
  19302. }
  19303. function scalePt2 ( pt, vec, size ) {
  19304. if ( !vec ) console.log( "die" );
  19305. return vec.clone().multiplyScalar( size ).add( pt );
  19306. }
  19307. var b, bs, t, z,
  19308. vert, vlen = vertices.length,
  19309. face, flen = faces.length,
  19310. cont, clen = contour.length;
  19311. // Find directions for point movement
  19312. var RAD_TO_DEGREES = 180 / Math.PI;
  19313. function getBevelVec( pt_i, pt_j, pt_k ) {
  19314. // Algorithm 2
  19315. return getBevelVec2( pt_i, pt_j, pt_k );
  19316. }
  19317. function getBevelVec1( pt_i, pt_j, pt_k ) {
  19318. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  19319. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  19320. if ( anglea > angleb ) {
  19321. angleb += Math.PI * 2;
  19322. }
  19323. var anglec = ( anglea + angleb ) / 2;
  19324. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  19325. var x = - Math.cos( anglec );
  19326. var y = - Math.sin( anglec );
  19327. var vec = new THREE.Vector2( x, y ); //.normalize();
  19328. return vec;
  19329. }
  19330. function getBevelVec2( pt_i, pt_j, pt_k ) {
  19331. var a = THREE.ExtrudeGeometry.__v1,
  19332. b = THREE.ExtrudeGeometry.__v2,
  19333. v_hat = THREE.ExtrudeGeometry.__v3,
  19334. w_hat = THREE.ExtrudeGeometry.__v4,
  19335. p = THREE.ExtrudeGeometry.__v5,
  19336. q = THREE.ExtrudeGeometry.__v6,
  19337. v, w,
  19338. v_dot_w_hat, q_sub_p_dot_w_hat,
  19339. s, intersection;
  19340. // good reading for line-line intersection
  19341. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  19342. // define a as vector j->i
  19343. // define b as vectot k->i
  19344. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  19345. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  19346. // get unit vectors
  19347. v = a.normalize();
  19348. w = b.normalize();
  19349. // normals from pt i
  19350. v_hat.set( -v.y, v.x );
  19351. w_hat.set( w.y, -w.x );
  19352. // pts from i
  19353. p.copy( pt_i ).add( v_hat );
  19354. q.copy( pt_i ).add( w_hat );
  19355. if ( p.equals( q ) ) {
  19356. //console.log("Warning: lines are straight");
  19357. return w_hat.clone();
  19358. }
  19359. // Points from j, k. helps prevents points cross overover most of the time
  19360. p.copy( pt_j ).add( v_hat );
  19361. q.copy( pt_k ).add( w_hat );
  19362. v_dot_w_hat = v.dot( w_hat );
  19363. q_sub_p_dot_w_hat = q.sub( p ).dot( w_hat );
  19364. // We should not reach these conditions
  19365. if ( v_dot_w_hat === 0 ) {
  19366. console.log( "Either infinite or no solutions!" );
  19367. if ( q_sub_p_dot_w_hat === 0 ) {
  19368. console.log( "Its finite solutions." );
  19369. } else {
  19370. console.log( "Too bad, no solutions." );
  19371. }
  19372. }
  19373. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  19374. if ( s < 0 ) {
  19375. // in case of emergecy, revert to algorithm 1.
  19376. return getBevelVec1( pt_i, pt_j, pt_k );
  19377. }
  19378. intersection = v.multiplyScalar( s ).add( p );
  19379. return intersection.sub( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  19380. }
  19381. var contourMovements = [];
  19382. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19383. if ( j === il ) j = 0;
  19384. if ( k === il ) k = 0;
  19385. // (j)---(i)---(k)
  19386. // console.log('i,j,k', i, j , k)
  19387. var pt_i = contour[ i ];
  19388. var pt_j = contour[ j ];
  19389. var pt_k = contour[ k ];
  19390. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  19391. }
  19392. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  19393. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19394. ahole = holes[ h ];
  19395. oneHoleMovements = [];
  19396. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19397. if ( j === il ) j = 0;
  19398. if ( k === il ) k = 0;
  19399. // (j)---(i)---(k)
  19400. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  19401. }
  19402. holesMovements.push( oneHoleMovements );
  19403. verticesMovements = verticesMovements.concat( oneHoleMovements );
  19404. }
  19405. // Loop bevelSegments, 1 for the front, 1 for the back
  19406. for ( b = 0; b < bevelSegments; b ++ ) {
  19407. //for ( b = bevelSegments; b > 0; b -- ) {
  19408. t = b / bevelSegments;
  19409. z = bevelThickness * ( 1 - t );
  19410. //z = bevelThickness * t;
  19411. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  19412. //bs = bevelSize * t ; // linear
  19413. // contract shape
  19414. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19415. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19416. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  19417. v( vert.x, vert.y, - z );
  19418. }
  19419. // expand holes
  19420. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  19421. ahole = holes[ h ];
  19422. oneHoleMovements = holesMovements[ h ];
  19423. for ( i = 0, il = ahole.length; i < il; i++ ) {
  19424. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19425. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  19426. v( vert.x, vert.y, -z );
  19427. }
  19428. }
  19429. }
  19430. bs = bevelSize;
  19431. // Back facing vertices
  19432. for ( i = 0; i < vlen; i ++ ) {
  19433. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19434. if ( !extrudeByPath ) {
  19435. v( vert.x, vert.y, 0 );
  19436. } else {
  19437. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19438. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  19439. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  19440. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  19441. v( position2.x, position2.y, position2.z );
  19442. }
  19443. }
  19444. // Add stepped vertices...
  19445. // Including front facing vertices
  19446. var s;
  19447. for ( s = 1; s <= steps; s ++ ) {
  19448. for ( i = 0; i < vlen; i ++ ) {
  19449. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19450. if ( !extrudeByPath ) {
  19451. v( vert.x, vert.y, amount / steps * s );
  19452. } else {
  19453. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19454. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  19455. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  19456. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  19457. v( position2.x, position2.y, position2.z );
  19458. }
  19459. }
  19460. }
  19461. // Add bevel segments planes
  19462. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19463. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  19464. t = b / bevelSegments;
  19465. z = bevelThickness * ( 1 - t );
  19466. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  19467. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  19468. // contract shape
  19469. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19470. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19471. v( vert.x, vert.y, amount + z );
  19472. }
  19473. // expand holes
  19474. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19475. ahole = holes[ h ];
  19476. oneHoleMovements = holesMovements[ h ];
  19477. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  19478. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19479. if ( !extrudeByPath ) {
  19480. v( vert.x, vert.y, amount + z );
  19481. } else {
  19482. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19483. }
  19484. }
  19485. }
  19486. }
  19487. /* Faces */
  19488. // Top and bottom faces
  19489. buildLidFaces();
  19490. // Sides faces
  19491. buildSideFaces();
  19492. ///// Internal functions
  19493. function buildLidFaces() {
  19494. if ( bevelEnabled ) {
  19495. var layer = 0 ; // steps + 1
  19496. var offset = vlen * layer;
  19497. // Bottom faces
  19498. for ( i = 0; i < flen; i ++ ) {
  19499. face = faces[ i ];
  19500. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  19501. }
  19502. layer = steps + bevelSegments * 2;
  19503. offset = vlen * layer;
  19504. // Top faces
  19505. for ( i = 0; i < flen; i ++ ) {
  19506. face = faces[ i ];
  19507. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  19508. }
  19509. } else {
  19510. // Bottom faces
  19511. for ( i = 0; i < flen; i++ ) {
  19512. face = faces[ i ];
  19513. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  19514. }
  19515. // Top faces
  19516. for ( i = 0; i < flen; i ++ ) {
  19517. face = faces[ i ];
  19518. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  19519. }
  19520. }
  19521. }
  19522. // Create faces for the z-sides of the shape
  19523. function buildSideFaces() {
  19524. var layeroffset = 0;
  19525. sidewalls( contour, layeroffset );
  19526. layeroffset += contour.length;
  19527. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19528. ahole = holes[ h ];
  19529. sidewalls( ahole, layeroffset );
  19530. //, true
  19531. layeroffset += ahole.length;
  19532. }
  19533. }
  19534. function sidewalls( contour, layeroffset ) {
  19535. var j, k;
  19536. i = contour.length;
  19537. while ( --i >= 0 ) {
  19538. j = i;
  19539. k = i - 1;
  19540. if ( k < 0 ) k = contour.length - 1;
  19541. //console.log('b', i,j, i-1, k,vertices.length);
  19542. var s = 0, sl = steps + bevelSegments * 2;
  19543. for ( s = 0; s < sl; s ++ ) {
  19544. var slen1 = vlen * s;
  19545. var slen2 = vlen * ( s + 1 );
  19546. var a = layeroffset + j + slen1,
  19547. b = layeroffset + k + slen1,
  19548. c = layeroffset + k + slen2,
  19549. d = layeroffset + j + slen2;
  19550. f4( a, b, c, d, contour, s, sl, j, k );
  19551. }
  19552. }
  19553. }
  19554. function v( x, y, z ) {
  19555. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  19556. }
  19557. function f3( a, b, c, isBottom ) {
  19558. a += shapesOffset;
  19559. b += shapesOffset;
  19560. c += shapesOffset;
  19561. // normal, color, material
  19562. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19563. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  19564. scope.faceVertexUvs[ 0 ].push( uvs );
  19565. }
  19566. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19567. a += shapesOffset;
  19568. b += shapesOffset;
  19569. c += shapesOffset;
  19570. d += shapesOffset;
  19571. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  19572. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  19573. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  19574. scope.faceVertexUvs[ 0 ].push( uvs );
  19575. }
  19576. };
  19577. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19578. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19579. var ax = geometry.vertices[ indexA ].x,
  19580. ay = geometry.vertices[ indexA ].y,
  19581. bx = geometry.vertices[ indexB ].x,
  19582. by = geometry.vertices[ indexB ].y,
  19583. cx = geometry.vertices[ indexC ].x,
  19584. cy = geometry.vertices[ indexC ].y;
  19585. return [
  19586. new THREE.Vector2( ax, ay ),
  19587. new THREE.Vector2( bx, by ),
  19588. new THREE.Vector2( cx, cy )
  19589. ];
  19590. },
  19591. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19592. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19593. },
  19594. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19595. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19596. contourIndex1, contourIndex2 ) {
  19597. var ax = geometry.vertices[ indexA ].x,
  19598. ay = geometry.vertices[ indexA ].y,
  19599. az = geometry.vertices[ indexA ].z,
  19600. bx = geometry.vertices[ indexB ].x,
  19601. by = geometry.vertices[ indexB ].y,
  19602. bz = geometry.vertices[ indexB ].z,
  19603. cx = geometry.vertices[ indexC ].x,
  19604. cy = geometry.vertices[ indexC ].y,
  19605. cz = geometry.vertices[ indexC ].z,
  19606. dx = geometry.vertices[ indexD ].x,
  19607. dy = geometry.vertices[ indexD ].y,
  19608. dz = geometry.vertices[ indexD ].z;
  19609. if ( Math.abs( ay - by ) < 0.01 ) {
  19610. return [
  19611. new THREE.Vector2( ax, 1 - az ),
  19612. new THREE.Vector2( bx, 1 - bz ),
  19613. new THREE.Vector2( cx, 1 - cz ),
  19614. new THREE.Vector2( dx, 1 - dz )
  19615. ];
  19616. } else {
  19617. return [
  19618. new THREE.Vector2( ay, 1 - az ),
  19619. new THREE.Vector2( by, 1 - bz ),
  19620. new THREE.Vector2( cy, 1 - cz ),
  19621. new THREE.Vector2( dy, 1 - dz )
  19622. ];
  19623. }
  19624. }
  19625. };
  19626. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19627. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19628. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19629. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19630. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19631. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19632. /**
  19633. * @author jonobr1 / http://jonobr1.com
  19634. *
  19635. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19636. * ExtrudeGeometry.
  19637. *
  19638. * parameters = {
  19639. *
  19640. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19641. *
  19642. * material: <int> // material index for front and back faces
  19643. * uvGenerator: <Object> // object that provides UV generator functions
  19644. *
  19645. * }
  19646. **/
  19647. THREE.ShapeGeometry = function ( shapes, options ) {
  19648. THREE.Geometry.call( this );
  19649. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19650. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19651. this.addShapeList( shapes, options );
  19652. this.computeCentroids();
  19653. this.computeFaceNormals();
  19654. };
  19655. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19656. /**
  19657. * Add an array of shapes to THREE.ShapeGeometry.
  19658. */
  19659. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19660. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19661. this.addShape( shapes[ i ], options );
  19662. }
  19663. return this;
  19664. };
  19665. /**
  19666. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19667. */
  19668. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19669. if ( options === undefined ) options = {};
  19670. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19671. var material = options.material;
  19672. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19673. var shapebb = this.shapebb;
  19674. //
  19675. var i, l, hole, s;
  19676. var shapesOffset = this.vertices.length;
  19677. var shapePoints = shape.extractPoints( curveSegments );
  19678. var vertices = shapePoints.shape;
  19679. var holes = shapePoints.holes;
  19680. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19681. if ( reverse ) {
  19682. vertices = vertices.reverse();
  19683. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19684. for ( i = 0, l = holes.length; i < l; i++ ) {
  19685. hole = holes[ i ];
  19686. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19687. holes[ i ] = hole.reverse();
  19688. }
  19689. }
  19690. reverse = false;
  19691. }
  19692. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19693. // Vertices
  19694. var contour = vertices;
  19695. for ( i = 0, l = holes.length; i < l; i++ ) {
  19696. hole = holes[ i ];
  19697. vertices = vertices.concat( hole );
  19698. }
  19699. //
  19700. var vert, vlen = vertices.length;
  19701. var face, flen = faces.length;
  19702. var cont, clen = contour.length;
  19703. for ( i = 0; i < vlen; i++ ) {
  19704. vert = vertices[ i ];
  19705. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19706. }
  19707. for ( i = 0; i < flen; i++ ) {
  19708. face = faces[ i ];
  19709. var a = face[ 0 ] + shapesOffset;
  19710. var b = face[ 1 ] + shapesOffset;
  19711. var c = face[ 2 ] + shapesOffset;
  19712. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19713. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19714. }
  19715. };
  19716. /**
  19717. * @author astrodud / http://astrodud.isgreat.org/
  19718. * @author zz85 / https://github.com/zz85
  19719. * @author bhouston / http://exocortex.com
  19720. */
  19721. // points - to create a closed torus, one must use a set of points
  19722. // like so: [ a, b, c, d, a ], see first is the same as last.
  19723. // segments - the number of circumference segments to create
  19724. // phiStart - the starting radian
  19725. // phiLength - the radian (0 to 2*PI) range of the lathed section
  19726. // 2*pi is a closed lathe, less than 2PI is a portion.
  19727. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  19728. THREE.Geometry.call( this );
  19729. segments = segments || 12;
  19730. phiStart = phiStart || 0;
  19731. phiLength = phiLength || 2 * Math.PI;
  19732. var inversePointLength = 1.0 / ( points.length - 1 );
  19733. var inverseSegments = 1.0 / segments;
  19734. for ( var i = 0, il = segments; i <= il; i ++ ) {
  19735. var phi = phiStart + i * inverseSegments * phiLength;
  19736. var c = Math.cos( phi ),
  19737. s = Math.sin( phi );
  19738. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  19739. var pt = points[ j ];
  19740. var vertex = new THREE.Vector3();
  19741. vertex.x = c * pt.x - s * pt.y;
  19742. vertex.y = s * pt.x + c * pt.y;
  19743. vertex.z = pt.z;
  19744. this.vertices.push( vertex );
  19745. }
  19746. }
  19747. var np = points.length;
  19748. for ( var i = 0, il = segments; i < il; i ++ ) {
  19749. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  19750. var base = j + np * i;
  19751. var a = base;
  19752. var b = base + np;
  19753. var c = base + 1 + np;
  19754. var d = base + 1;
  19755. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19756. var u0 = i * inverseSegments;
  19757. var v0 = j * inversePointLength;
  19758. var u1 = u0 + inverseSegments;
  19759. var v1 = v0 + inversePointLength;
  19760. this.faceVertexUvs[ 0 ].push( [
  19761. new THREE.Vector2( u0, v0 ),
  19762. new THREE.Vector2( u1, v0 ),
  19763. new THREE.Vector2( u1, v1 ),
  19764. new THREE.Vector2( u0, v1 )
  19765. ] );
  19766. }
  19767. }
  19768. this.mergeVertices();
  19769. this.computeCentroids();
  19770. this.computeFaceNormals();
  19771. this.computeVertexNormals();
  19772. };
  19773. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19774. /**
  19775. * @author mrdoob / http://mrdoob.com/
  19776. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19777. */
  19778. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19779. THREE.Geometry.call( this );
  19780. this.width = width;
  19781. this.height = height;
  19782. this.widthSegments = widthSegments || 1;
  19783. this.heightSegments = heightSegments || 1;
  19784. var ix, iz;
  19785. var width_half = width / 2;
  19786. var height_half = height / 2;
  19787. var gridX = this.widthSegments;
  19788. var gridZ = this.heightSegments;
  19789. var gridX1 = gridX + 1;
  19790. var gridZ1 = gridZ + 1;
  19791. var segment_width = this.width / gridX;
  19792. var segment_height = this.height / gridZ;
  19793. var normal = new THREE.Vector3( 0, 0, 1 );
  19794. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19795. for ( ix = 0; ix < gridX1; ix ++ ) {
  19796. var x = ix * segment_width - width_half;
  19797. var y = iz * segment_height - height_half;
  19798. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19799. }
  19800. }
  19801. for ( iz = 0; iz < gridZ; iz ++ ) {
  19802. for ( ix = 0; ix < gridX; ix ++ ) {
  19803. var a = ix + gridX1 * iz;
  19804. var b = ix + gridX1 * ( iz + 1 );
  19805. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19806. var d = ( ix + 1 ) + gridX1 * iz;
  19807. var face = new THREE.Face4( a, b, c, d );
  19808. face.normal.copy( normal );
  19809. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  19810. this.faces.push( face );
  19811. this.faceVertexUvs[ 0 ].push( [
  19812. new THREE.Vector2( ix / gridX, 1 - iz / gridZ ),
  19813. new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  19814. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  19815. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  19816. ] );
  19817. }
  19818. }
  19819. this.computeCentroids();
  19820. };
  19821. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19822. /**
  19823. * @author Kaleb Murphy
  19824. */
  19825. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19826. THREE.Geometry.call( this );
  19827. innerRadius = innerRadius || 0;
  19828. outerRadius = outerRadius || 50;
  19829. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19830. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19831. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  19832. phiSegments = phiSegments !== undefined ? Math.max( 3, phiSegments ) : 8;
  19833. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19834. for ( i = 0; i <= phiSegments; i ++ ) { // concentric circles inside ring
  19835. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19836. var vertex = new THREE.Vector3();
  19837. var segment = thetaStart + o / thetaSegments * thetaLength;
  19838. vertex.x = radius * Math.cos( segment );
  19839. vertex.y = radius * Math.sin( segment );
  19840. this.vertices.push( vertex );
  19841. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  19842. }
  19843. radius += radiusStep;
  19844. }
  19845. var n = new THREE.Vector3( 0, 0, 1 );
  19846. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  19847. var thetaSegment = i * thetaSegments;
  19848. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19849. var segment = o + thetaSegment;
  19850. var v1 = segment + i;
  19851. var v2 = segment + thetaSegments + i;
  19852. var v3 = segment + thetaSegments + 1 + i;
  19853. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  19854. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ], uvs[ v2 ], uvs[ v3 ] ]);
  19855. v1 = segment + i;
  19856. v2 = segment + thetaSegments + 1 + i;
  19857. v3 = segment + 1 + i;
  19858. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  19859. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ], uvs[ v2 ], uvs[ v3 ] ]);
  19860. }
  19861. }
  19862. this.computeCentroids();
  19863. this.computeFaceNormals();
  19864. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19865. };
  19866. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19867. /**
  19868. * @author mrdoob / http://mrdoob.com/
  19869. */
  19870. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19871. THREE.Geometry.call( this );
  19872. this.radius = radius = radius || 50;
  19873. this.widthSegments = widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19874. this.heightSegments = heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19875. this.phiStart = phiStart = phiStart !== undefined ? phiStart : 0;
  19876. this.phiLength = phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19877. this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19878. this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19879. var x, y, vertices = [], uvs = [];
  19880. for ( y = 0; y <= heightSegments; y ++ ) {
  19881. var verticesRow = [];
  19882. var uvsRow = [];
  19883. for ( x = 0; x <= widthSegments; x ++ ) {
  19884. var u = x / widthSegments;
  19885. var v = y / heightSegments;
  19886. var vertex = new THREE.Vector3();
  19887. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19888. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  19889. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19890. this.vertices.push( vertex );
  19891. verticesRow.push( this.vertices.length - 1 );
  19892. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19893. }
  19894. vertices.push( verticesRow );
  19895. uvs.push( uvsRow );
  19896. }
  19897. for ( y = 0; y < this.heightSegments; y ++ ) {
  19898. for ( x = 0; x < this.widthSegments; x ++ ) {
  19899. var v1 = vertices[ y ][ x + 1 ];
  19900. var v2 = vertices[ y ][ x ];
  19901. var v3 = vertices[ y + 1 ][ x ];
  19902. var v4 = vertices[ y + 1 ][ x + 1 ];
  19903. var n1 = this.vertices[ v1 ].clone().normalize();
  19904. var n2 = this.vertices[ v2 ].clone().normalize();
  19905. var n3 = this.vertices[ v3 ].clone().normalize();
  19906. var n4 = this.vertices[ v4 ].clone().normalize();
  19907. var uv1 = uvs[ y ][ x + 1 ].clone();
  19908. var uv2 = uvs[ y ][ x ].clone();
  19909. var uv3 = uvs[ y + 1 ][ x ].clone();
  19910. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19911. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  19912. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19913. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19914. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  19915. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19916. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19917. } else {
  19918. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  19919. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  19920. }
  19921. }
  19922. }
  19923. this.computeCentroids();
  19924. this.computeFaceNormals();
  19925. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19926. };
  19927. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19928. /**
  19929. * @author zz85 / http://www.lab4games.net/zz85/blog
  19930. * @author alteredq / http://alteredqualia.com/
  19931. *
  19932. * For creating 3D text geometry in three.js
  19933. *
  19934. * Text = 3D Text
  19935. *
  19936. * parameters = {
  19937. * size: <float>, // size of the text
  19938. * height: <float>, // thickness to extrude text
  19939. * curveSegments: <int>, // number of points on the curves
  19940. *
  19941. * font: <string>, // font name
  19942. * weight: <string>, // font weight (normal, bold)
  19943. * style: <string>, // font style (normal, italics)
  19944. *
  19945. * bevelEnabled: <bool>, // turn on bevel
  19946. * bevelThickness: <float>, // how deep into text bevel goes
  19947. * bevelSize: <float>, // how far from text outline is bevel
  19948. * }
  19949. *
  19950. */
  19951. /* Usage Examples
  19952. // TextGeometry wrapper
  19953. var text3d = new TextGeometry( text, options );
  19954. // Complete manner
  19955. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19956. var text3d = new ExtrudeGeometry( textShapes, options );
  19957. */
  19958. THREE.TextGeometry = function ( text, parameters ) {
  19959. parameters = parameters || {};
  19960. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19961. // translate parameters to ExtrudeGeometry API
  19962. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19963. // defaults
  19964. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19965. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19966. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19967. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19968. };
  19969. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19970. /**
  19971. * @author oosmoxiecode
  19972. * @author mrdoob / http://mrdoob.com/
  19973. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19974. */
  19975. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19976. THREE.Geometry.call( this );
  19977. var scope = this;
  19978. this.radius = radius || 100;
  19979. this.tube = tube || 40;
  19980. this.radialSegments = radialSegments || 8;
  19981. this.tubularSegments = tubularSegments || 6;
  19982. this.arc = arc || Math.PI * 2;
  19983. var center = new THREE.Vector3(), uvs = [], normals = [];
  19984. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  19985. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  19986. var u = i / this.tubularSegments * this.arc;
  19987. var v = j / this.radialSegments * Math.PI * 2;
  19988. center.x = this.radius * Math.cos( u );
  19989. center.y = this.radius * Math.sin( u );
  19990. var vertex = new THREE.Vector3();
  19991. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  19992. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  19993. vertex.z = this.tube * Math.sin( v );
  19994. this.vertices.push( vertex );
  19995. uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
  19996. normals.push( vertex.clone().sub( center ).normalize() );
  19997. }
  19998. }
  19999. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  20000. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  20001. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  20002. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  20003. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  20004. var d = ( this.tubularSegments + 1 ) * j + i;
  20005. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  20006. face.normal.add( normals[ a ] );
  20007. face.normal.add( normals[ b ] );
  20008. face.normal.add( normals[ c ] );
  20009. face.normal.add( normals[ d ] );
  20010. face.normal.normalize();
  20011. this.faces.push( face );
  20012. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  20013. }
  20014. }
  20015. this.computeCentroids();
  20016. };
  20017. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20018. /**
  20019. * @author oosmoxiecode
  20020. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  20021. */
  20022. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  20023. THREE.Geometry.call( this );
  20024. var scope = this;
  20025. this.radius = radius || 100;
  20026. this.tube = tube || 40;
  20027. this.radialSegments = radialSegments || 64;
  20028. this.tubularSegments = tubularSegments || 8;
  20029. this.p = p || 2;
  20030. this.q = q || 3;
  20031. this.heightScale = heightScale || 1;
  20032. this.grid = new Array( this.radialSegments );
  20033. var tang = new THREE.Vector3();
  20034. var n = new THREE.Vector3();
  20035. var bitan = new THREE.Vector3();
  20036. for ( var i = 0; i < this.radialSegments; ++ i ) {
  20037. this.grid[ i ] = new Array( this.tubularSegments );
  20038. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  20039. var p1 = getPos( u, this.q, this.p, this.radius, this.heightScale );
  20040. var p2 = getPos( u + 0.01, this.q, this.p, this.radius, this.heightScale );
  20041. tang.subVectors( p2, p1 );
  20042. n.addVectors( p2, p1 );
  20043. bitan.crossVectors( tang, n );
  20044. n.crossVectors( bitan, tang );
  20045. bitan.normalize();
  20046. n.normalize();
  20047. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  20048. var v = j / this.tubularSegments * 2 * Math.PI;
  20049. var cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  20050. var cy = this.tube * Math.sin( v );
  20051. var pos = new THREE.Vector3();
  20052. pos.x = p1.x + cx * n.x + cy * bitan.x;
  20053. pos.y = p1.y + cx * n.y + cy * bitan.y;
  20054. pos.z = p1.z + cx * n.z + cy * bitan.z;
  20055. this.grid[ i ][ j ] = scope.vertices.push( pos ) - 1;
  20056. }
  20057. }
  20058. for ( var i = 0; i < this.radialSegments; ++ i ) {
  20059. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  20060. var ip = ( i + 1 ) % this.radialSegments;
  20061. var jp = ( j + 1 ) % this.tubularSegments;
  20062. var a = this.grid[ i ][ j ];
  20063. var b = this.grid[ ip ][ j ];
  20064. var c = this.grid[ ip ][ jp ];
  20065. var d = this.grid[ i ][ jp ];
  20066. var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
  20067. var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  20068. var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  20069. var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  20070. this.faces.push( new THREE.Face4( a, b, c, d ) );
  20071. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  20072. }
  20073. }
  20074. this.computeCentroids();
  20075. this.computeFaceNormals();
  20076. this.computeVertexNormals();
  20077. function getPos( u, in_q, in_p, radius, heightScale ) {
  20078. var cu = Math.cos( u );
  20079. var su = Math.sin( u );
  20080. var quOverP = in_q / in_p * u;
  20081. var cs = Math.cos( quOverP );
  20082. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  20083. var ty = radius * ( 2 + cs ) * su * 0.5;
  20084. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  20085. return new THREE.Vector3( tx, ty, tz );
  20086. }
  20087. };
  20088. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20089. /**
  20090. * @author WestLangley / https://github.com/WestLangley
  20091. * @author zz85 / https://github.com/zz85
  20092. * @author miningold / https://github.com/miningold
  20093. *
  20094. * Modified from the TorusKnotGeometry by @oosmoxiecode
  20095. *
  20096. * Creates a tube which extrudes along a 3d spline
  20097. *
  20098. * Uses parallel transport frames as described in
  20099. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  20100. */
  20101. THREE.TubeGeometry = function( path, segments, radius, radialSegments, closed ) {
  20102. THREE.Geometry.call( this );
  20103. this.path = path;
  20104. this.segments = segments || 64;
  20105. this.radius = radius || 1;
  20106. this.radialSegments = radialSegments || 8;
  20107. this.closed = closed || false;
  20108. this.grid = [];
  20109. var scope = this,
  20110. tangent,
  20111. normal,
  20112. binormal,
  20113. numpoints = this.segments + 1,
  20114. x, y, z,
  20115. tx, ty, tz,
  20116. u, v,
  20117. cx, cy,
  20118. pos, pos2 = new THREE.Vector3(),
  20119. i, j,
  20120. ip, jp,
  20121. a, b, c, d,
  20122. uva, uvb, uvc, uvd;
  20123. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  20124. tangents = frames.tangents,
  20125. normals = frames.normals,
  20126. binormals = frames.binormals;
  20127. // proxy internals
  20128. this.tangents = tangents;
  20129. this.normals = normals;
  20130. this.binormals = binormals;
  20131. function vert( x, y, z ) {
  20132. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  20133. }
  20134. // consruct the grid
  20135. for ( i = 0; i < numpoints; i++ ) {
  20136. this.grid[ i ] = [];
  20137. u = i / ( numpoints - 1 );
  20138. pos = path.getPointAt( u );
  20139. tangent = tangents[ i ];
  20140. normal = normals[ i ];
  20141. binormal = binormals[ i ];
  20142. for ( j = 0; j < this.radialSegments; j++ ) {
  20143. v = j / this.radialSegments * 2 * Math.PI;
  20144. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  20145. cy = this.radius * Math.sin( v );
  20146. pos2.copy( pos );
  20147. pos2.x += cx * normal.x + cy * binormal.x;
  20148. pos2.y += cx * normal.y + cy * binormal.y;
  20149. pos2.z += cx * normal.z + cy * binormal.z;
  20150. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  20151. }
  20152. }
  20153. // construct the mesh
  20154. for ( i = 0; i < this.segments; i++ ) {
  20155. for ( j = 0; j < this.radialSegments; j++ ) {
  20156. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  20157. jp = (j + 1) % this.radialSegments;
  20158. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  20159. b = this.grid[ ip ][ j ];
  20160. c = this.grid[ ip ][ jp ];
  20161. d = this.grid[ i ][ jp ];
  20162. uva = new THREE.Vector2( i / this.segments, j / this.radialSegments );
  20163. uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radialSegments );
  20164. uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radialSegments );
  20165. uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radialSegments );
  20166. this.faces.push( new THREE.Face4( a, b, c, d ) );
  20167. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  20168. }
  20169. }
  20170. this.computeCentroids();
  20171. this.computeFaceNormals();
  20172. this.computeVertexNormals();
  20173. };
  20174. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20175. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  20176. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  20177. var tangent = new THREE.Vector3(),
  20178. normal = new THREE.Vector3(),
  20179. binormal = new THREE.Vector3(),
  20180. tangents = [],
  20181. normals = [],
  20182. binormals = [],
  20183. vec = new THREE.Vector3(),
  20184. mat = new THREE.Matrix4(),
  20185. numpoints = segments + 1,
  20186. theta,
  20187. epsilon = 0.0001,
  20188. smallest,
  20189. tx, ty, tz,
  20190. i, u, v;
  20191. // expose internals
  20192. this.tangents = tangents;
  20193. this.normals = normals;
  20194. this.binormals = binormals;
  20195. // compute the tangent vectors for each segment on the path
  20196. for ( i = 0; i < numpoints; i++ ) {
  20197. u = i / ( numpoints - 1 );
  20198. tangents[ i ] = path.getTangentAt( u );
  20199. tangents[ i ].normalize();
  20200. }
  20201. initialNormal3();
  20202. function initialNormal1(lastBinormal) {
  20203. // fixed start binormal. Has dangers of 0 vectors
  20204. normals[ 0 ] = new THREE.Vector3();
  20205. binormals[ 0 ] = new THREE.Vector3();
  20206. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  20207. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  20208. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20209. }
  20210. function initialNormal2() {
  20211. // This uses the Frenet-Serret formula for deriving binormal
  20212. var t2 = path.getTangentAt( epsilon );
  20213. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  20214. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  20215. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  20216. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20217. }
  20218. function initialNormal3() {
  20219. // select an initial normal vector perpenicular to the first tangent vector,
  20220. // and in the direction of the smallest tangent xyz component
  20221. normals[ 0 ] = new THREE.Vector3();
  20222. binormals[ 0 ] = new THREE.Vector3();
  20223. smallest = Number.MAX_VALUE;
  20224. tx = Math.abs( tangents[ 0 ].x );
  20225. ty = Math.abs( tangents[ 0 ].y );
  20226. tz = Math.abs( tangents[ 0 ].z );
  20227. if ( tx <= smallest ) {
  20228. smallest = tx;
  20229. normal.set( 1, 0, 0 );
  20230. }
  20231. if ( ty <= smallest ) {
  20232. smallest = ty;
  20233. normal.set( 0, 1, 0 );
  20234. }
  20235. if ( tz <= smallest ) {
  20236. normal.set( 0, 0, 1 );
  20237. }
  20238. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  20239. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  20240. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  20241. }
  20242. // compute the slowly-varying normal and binormal vectors for each segment on the path
  20243. for ( i = 1; i < numpoints; i++ ) {
  20244. normals[ i ] = normals[ i-1 ].clone();
  20245. binormals[ i ] = binormals[ i-1 ].clone();
  20246. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  20247. if ( vec.length() > epsilon ) {
  20248. vec.normalize();
  20249. theta = Math.acos( THREE.Math.clamp( tangents[ i-1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  20250. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  20251. }
  20252. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20253. }
  20254. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  20255. if ( closed ) {
  20256. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints-1 ] ), -1, 1 ) );
  20257. theta /= ( numpoints - 1 );
  20258. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  20259. theta = -theta;
  20260. }
  20261. for ( i = 1; i < numpoints; i++ ) {
  20262. // twist a little...
  20263. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  20264. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20265. }
  20266. }
  20267. };
  20268. /**
  20269. * @author clockworkgeek / https://github.com/clockworkgeek
  20270. * @author timothypratley / https://github.com/timothypratley
  20271. * @author WestLangley / http://github.com/WestLangley
  20272. */
  20273. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  20274. THREE.Geometry.call( this );
  20275. radius = radius || 1;
  20276. detail = detail || 0;
  20277. var that = this;
  20278. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  20279. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  20280. }
  20281. var midpoints = [], p = this.vertices;
  20282. var f = [];
  20283. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20284. var v1 = p[ faces[ i ][ 0 ] ];
  20285. var v2 = p[ faces[ i ][ 1 ] ];
  20286. var v3 = p[ faces[ i ][ 2 ] ];
  20287. f[ i ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  20288. }
  20289. for ( var i = 0, l = f.length; i < l; i ++ ) {
  20290. subdivide(f[ i ], detail);
  20291. }
  20292. // Handle case when face straddles the seam
  20293. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  20294. var uvs = this.faceVertexUvs[ 0 ][ i ];
  20295. var x0 = uvs[ 0 ].x;
  20296. var x1 = uvs[ 1 ].x;
  20297. var x2 = uvs[ 2 ].x;
  20298. var max = Math.max( x0, Math.max( x1, x2 ) );
  20299. var min = Math.min( x0, Math.min( x1, x2 ) );
  20300. if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
  20301. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  20302. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  20303. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  20304. }
  20305. }
  20306. // Apply radius
  20307. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  20308. this.vertices[ i ].multiplyScalar( radius );
  20309. }
  20310. // Merge vertices
  20311. this.mergeVertices();
  20312. this.computeCentroids();
  20313. this.computeFaceNormals();
  20314. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  20315. // Project vector onto sphere's surface
  20316. function prepare( vector ) {
  20317. var vertex = vector.normalize().clone();
  20318. vertex.index = that.vertices.push( vertex ) - 1;
  20319. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  20320. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  20321. var v = inclination( vector ) / Math.PI + 0.5;
  20322. vertex.uv = new THREE.Vector2( u, 1 - v );
  20323. return vertex;
  20324. }
  20325. // Approximate a curved face with recursively sub-divided triangles.
  20326. function make( v1, v2, v3 ) {
  20327. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  20328. face.centroid.add( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  20329. that.faces.push( face );
  20330. var azi = azimuth( face.centroid );
  20331. that.faceVertexUvs[ 0 ].push( [
  20332. correctUV( v1.uv, v1, azi ),
  20333. correctUV( v2.uv, v2, azi ),
  20334. correctUV( v3.uv, v3, azi )
  20335. ] );
  20336. }
  20337. // Analytically subdivide a face to the required detail level.
  20338. function subdivide(face, detail ) {
  20339. var cols = Math.pow(2, detail);
  20340. var cells = Math.pow(4, detail);
  20341. var a = prepare( that.vertices[ face.a ] );
  20342. var b = prepare( that.vertices[ face.b ] );
  20343. var c = prepare( that.vertices[ face.c ] );
  20344. var v = [];
  20345. // Construct all of the vertices for this subdivision.
  20346. for ( var i = 0 ; i <= cols; i ++ ) {
  20347. v[ i ] = [];
  20348. var aj = prepare( a.clone().lerp( c, i / cols ) );
  20349. var bj = prepare( b.clone().lerp( c, i / cols ) );
  20350. var rows = cols - i;
  20351. for ( var j = 0; j <= rows; j ++) {
  20352. if ( j == 0 && i == cols ) {
  20353. v[ i ][ j ] = aj;
  20354. } else {
  20355. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  20356. }
  20357. }
  20358. }
  20359. // Construct all of the faces.
  20360. for ( var i = 0; i < cols ; i ++ ) {
  20361. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  20362. var k = Math.floor( j / 2 );
  20363. if ( j % 2 == 0 ) {
  20364. make(
  20365. v[ i ][ k + 1],
  20366. v[ i + 1 ][ k ],
  20367. v[ i ][ k ]
  20368. );
  20369. } else {
  20370. make(
  20371. v[ i ][ k + 1 ],
  20372. v[ i + 1][ k + 1],
  20373. v[ i + 1 ][ k ]
  20374. );
  20375. }
  20376. }
  20377. }
  20378. }
  20379. // Angle around the Y axis, counter-clockwise when looking from above.
  20380. function azimuth( vector ) {
  20381. return Math.atan2( vector.z, -vector.x );
  20382. }
  20383. // Angle above the XZ plane.
  20384. function inclination( vector ) {
  20385. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20386. }
  20387. // Texture fixing helper. Spheres have some odd behaviours.
  20388. function correctUV( uv, vector, azimuth ) {
  20389. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  20390. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  20391. return uv.clone();
  20392. }
  20393. };
  20394. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20395. /**
  20396. * @author timothypratley / https://github.com/timothypratley
  20397. */
  20398. THREE.IcosahedronGeometry = function ( radius, detail ) {
  20399. this.radius = radius;
  20400. this.detail = detail;
  20401. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20402. var vertices = [
  20403. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  20404. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  20405. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  20406. ];
  20407. var faces = [
  20408. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  20409. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  20410. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  20411. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  20412. ];
  20413. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20414. };
  20415. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20416. /**
  20417. * @author timothypratley / https://github.com/timothypratley
  20418. */
  20419. THREE.OctahedronGeometry = function ( radius, detail ) {
  20420. var vertices = [
  20421. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  20422. ];
  20423. var faces = [
  20424. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  20425. ];
  20426. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20427. };
  20428. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20429. /**
  20430. * @author timothypratley / https://github.com/timothypratley
  20431. */
  20432. THREE.TetrahedronGeometry = function ( radius, detail ) {
  20433. var vertices = [
  20434. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  20435. ];
  20436. var faces = [
  20437. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  20438. ];
  20439. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20440. };
  20441. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20442. /**
  20443. * @author zz85 / https://github.com/zz85
  20444. * Parametric Surfaces Geometry
  20445. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  20446. *
  20447. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  20448. *
  20449. */
  20450. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  20451. THREE.Geometry.call( this );
  20452. var verts = this.vertices;
  20453. var faces = this.faces;
  20454. var uvs = this.faceVertexUvs[ 0 ];
  20455. useTris = (useTris === undefined) ? false : useTris;
  20456. var i, il, j, p;
  20457. var u, v;
  20458. var stackCount = stacks + 1;
  20459. var sliceCount = slices + 1;
  20460. for ( i = 0; i <= stacks; i ++ ) {
  20461. v = i / stacks;
  20462. for ( j = 0; j <= slices; j ++ ) {
  20463. u = j / slices;
  20464. p = func( u, v );
  20465. verts.push( p );
  20466. }
  20467. }
  20468. var a, b, c, d;
  20469. var uva, uvb, uvc, uvd;
  20470. for ( i = 0; i < stacks; i ++ ) {
  20471. for ( j = 0; j < slices; j ++ ) {
  20472. a = i * sliceCount + j;
  20473. b = i * sliceCount + j + 1;
  20474. c = (i + 1) * sliceCount + j;
  20475. d = (i + 1) * sliceCount + j + 1;
  20476. uva = new THREE.Vector2( j / slices, i / stacks );
  20477. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  20478. uvc = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  20479. uvd = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  20480. if ( useTris ) {
  20481. faces.push( new THREE.Face3( a, b, c ) );
  20482. faces.push( new THREE.Face3( b, d, c ) );
  20483. uvs.push( [ uva, uvb, uvc ] );
  20484. uvs.push( [ uvb, uvd, uvc ] );
  20485. } else {
  20486. faces.push( new THREE.Face4( a, b, d, c ) );
  20487. uvs.push( [ uva, uvb, uvd, uvc ] );
  20488. }
  20489. }
  20490. }
  20491. // console.log(this);
  20492. // magic bullet
  20493. // var diff = this.mergeVertices();
  20494. // console.log('removed ', diff, ' vertices by merging');
  20495. this.computeCentroids();
  20496. this.computeFaceNormals();
  20497. this.computeVertexNormals();
  20498. };
  20499. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20500. /**
  20501. * @author qiao / https://github.com/qiao
  20502. * @fileoverview This is a convex hull generator using the incremental method.
  20503. * The complexity is O(n^2) where n is the number of vertices.
  20504. * O(nlogn) algorithms do exist, but they are much more complicated.
  20505. *
  20506. * Benchmark:
  20507. *
  20508. * Platform: CPU: P7350 @2.00GHz Engine: V8
  20509. *
  20510. * Num Vertices Time(ms)
  20511. *
  20512. * 10 1
  20513. * 20 3
  20514. * 30 19
  20515. * 40 48
  20516. * 50 107
  20517. */
  20518. THREE.ConvexGeometry = function( vertices ) {
  20519. THREE.Geometry.call( this );
  20520. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  20521. for ( var i = 3; i < vertices.length; i++ ) {
  20522. addPoint( i );
  20523. }
  20524. function addPoint( vertexId ) {
  20525. var vertex = vertices[ vertexId ].clone();
  20526. var mag = vertex.length();
  20527. vertex.x += mag * randomOffset();
  20528. vertex.y += mag * randomOffset();
  20529. vertex.z += mag * randomOffset();
  20530. var hole = [];
  20531. for ( var f = 0; f < faces.length; ) {
  20532. var face = faces[ f ];
  20533. // for each face, if the vertex can see it,
  20534. // then we try to add the face's edges into the hole.
  20535. if ( visible( face, vertex ) ) {
  20536. for ( var e = 0; e < 3; e++ ) {
  20537. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  20538. var boundary = true;
  20539. // remove duplicated edges.
  20540. for ( var h = 0; h < hole.length; h++ ) {
  20541. if ( equalEdge( hole[ h ], edge ) ) {
  20542. hole[ h ] = hole[ hole.length - 1 ];
  20543. hole.pop();
  20544. boundary = false;
  20545. break;
  20546. }
  20547. }
  20548. if ( boundary ) {
  20549. hole.push( edge );
  20550. }
  20551. }
  20552. // remove faces[ f ]
  20553. faces[ f ] = faces[ faces.length - 1 ];
  20554. faces.pop();
  20555. } else { // not visible
  20556. f++;
  20557. }
  20558. }
  20559. // construct the new faces formed by the edges of the hole and the vertex
  20560. for ( var h = 0; h < hole.length; h++ ) {
  20561. faces.push( [
  20562. hole[ h ][ 0 ],
  20563. hole[ h ][ 1 ],
  20564. vertexId
  20565. ] );
  20566. }
  20567. }
  20568. /**
  20569. * Whether the face is visible from the vertex
  20570. */
  20571. function visible( face, vertex ) {
  20572. var va = vertices[ face[ 0 ] ];
  20573. var vb = vertices[ face[ 1 ] ];
  20574. var vc = vertices[ face[ 2 ] ];
  20575. var n = normal( va, vb, vc );
  20576. // distance from face to origin
  20577. var dist = n.dot( va );
  20578. return n.dot( vertex ) >= dist;
  20579. }
  20580. /**
  20581. * Face normal
  20582. */
  20583. function normal( va, vb, vc ) {
  20584. var cb = new THREE.Vector3();
  20585. var ab = new THREE.Vector3();
  20586. cb.subVectors( vc, vb );
  20587. ab.subVectors( va, vb );
  20588. cb.cross( ab );
  20589. cb.normalize();
  20590. return cb;
  20591. }
  20592. /**
  20593. * Detect whether two edges are equal.
  20594. * Note that when constructing the convex hull, two same edges can only
  20595. * be of the negative direction.
  20596. */
  20597. function equalEdge( ea, eb ) {
  20598. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  20599. }
  20600. /**
  20601. * Create a random offset between -1e-6 and 1e-6.
  20602. */
  20603. function randomOffset() {
  20604. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  20605. }
  20606. /**
  20607. * XXX: Not sure if this is the correct approach. Need someone to review.
  20608. */
  20609. function vertexUv( vertex ) {
  20610. var mag = vertex.length();
  20611. return new THREE.Vector2( vertex.x / mag, vertex.y / mag );
  20612. }
  20613. // Push vertices into `this.vertices`, skipping those inside the hull
  20614. var id = 0;
  20615. var newId = new Array( vertices.length ); // map from old vertex id to new id
  20616. for ( var i = 0; i < faces.length; i++ ) {
  20617. var face = faces[ i ];
  20618. for ( var j = 0; j < 3; j++ ) {
  20619. if ( newId[ face[ j ] ] === undefined ) {
  20620. newId[ face[ j ] ] = id++;
  20621. this.vertices.push( vertices[ face[ j ] ] );
  20622. }
  20623. face[ j ] = newId[ face[ j ] ];
  20624. }
  20625. }
  20626. // Convert faces into instances of THREE.Face3
  20627. for ( var i = 0; i < faces.length; i++ ) {
  20628. this.faces.push( new THREE.Face3(
  20629. faces[ i ][ 0 ],
  20630. faces[ i ][ 1 ],
  20631. faces[ i ][ 2 ]
  20632. ) );
  20633. }
  20634. // Compute UVs
  20635. for ( var i = 0; i < this.faces.length; i++ ) {
  20636. var face = this.faces[ i ];
  20637. this.faceVertexUvs[ 0 ].push( [
  20638. vertexUv( this.vertices[ face.a ] ),
  20639. vertexUv( this.vertices[ face.b ] ),
  20640. vertexUv( this.vertices[ face.c ])
  20641. ] );
  20642. }
  20643. this.computeCentroids();
  20644. this.computeFaceNormals();
  20645. this.computeVertexNormals();
  20646. };
  20647. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20648. /**
  20649. * @author sroucheray / http://sroucheray.org/
  20650. * @author mrdoob / http://mrdoob.com/
  20651. */
  20652. THREE.AxisHelper = function ( size ) {
  20653. size = size || 1;
  20654. var geometry = new THREE.Geometry();
  20655. geometry.vertices.push(
  20656. new THREE.Vector3(), new THREE.Vector3( size, 0, 0 ),
  20657. new THREE.Vector3(), new THREE.Vector3( 0, size, 0 ),
  20658. new THREE.Vector3(), new THREE.Vector3( 0, 0, size )
  20659. );
  20660. geometry.colors.push(
  20661. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  20662. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  20663. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  20664. );
  20665. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20666. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20667. };
  20668. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20669. /**
  20670. * @author WestLangley / http://github.com/WestLangley
  20671. * @author zz85 / http://github.com/zz85
  20672. * @author bhouston / http://exocortex.com
  20673. *
  20674. * Creates an arrow for visualizing directions
  20675. *
  20676. * Parameters:
  20677. * dir - Vector3
  20678. * origin - Vector3
  20679. * length - Number
  20680. * hex - color in hex value
  20681. */
  20682. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  20683. // dir is assumed to be normalized
  20684. THREE.Object3D.call( this );
  20685. if ( hex === undefined ) hex = 0xffff00;
  20686. if ( length === undefined ) length = 1;
  20687. this.position = origin;
  20688. var lineGeometry = new THREE.Geometry();
  20689. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  20690. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  20691. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  20692. this.line.matrixAutoUpdate = false;
  20693. this.add( this.line );
  20694. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  20695. coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, 0.875, 0 ) );
  20696. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  20697. this.cone.matrixAutoUpdate = false;
  20698. this.add( this.cone );
  20699. this.setDirection( dir );
  20700. this.setLength( length );
  20701. };
  20702. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20703. THREE.ArrowHelper.prototype.setDirection = function () {
  20704. var axis = new THREE.Vector3();
  20705. var radians;
  20706. return function ( dir ) {
  20707. // dir is assumed to be normalized
  20708. if ( dir.y > 0.99999 ) {
  20709. this.quaternion.set( 0, 0, 0, 1 );
  20710. } else if ( dir.y < - 0.99999 ) {
  20711. this.quaternion.set( 1, 0, 0, 0 );
  20712. } else {
  20713. axis.set( dir.z, 0, - dir.x ).normalize();
  20714. radians = Math.acos( dir.y );
  20715. this.quaternion.setFromAxisAngle( axis, radians );
  20716. }
  20717. };
  20718. }();
  20719. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  20720. this.scale.set( length, length, length );
  20721. };
  20722. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  20723. this.line.material.color.setHex( hex );
  20724. this.cone.material.color.setHex( hex );
  20725. };
  20726. /**
  20727. * @author mrdoob / http://mrdoob.com/
  20728. */
  20729. THREE.BoxHelper = function ( object ) {
  20730. // 5____4
  20731. // 1/___0/|
  20732. // | 6__|_7
  20733. // 2/___3/
  20734. var vertices = [
  20735. new THREE.Vector3( 1, 1, 1 ),
  20736. new THREE.Vector3( - 1, 1, 1 ),
  20737. new THREE.Vector3( - 1, - 1, 1 ),
  20738. new THREE.Vector3( 1, - 1, 1 ),
  20739. new THREE.Vector3( 1, 1, - 1 ),
  20740. new THREE.Vector3( - 1, 1, - 1 ),
  20741. new THREE.Vector3( - 1, - 1, - 1 ),
  20742. new THREE.Vector3( 1, - 1, - 1 )
  20743. ];
  20744. this.vertices = vertices;
  20745. // TODO: Wouldn't be nice if Line had .segments?
  20746. var geometry = new THREE.Geometry();
  20747. geometry.vertices.push(
  20748. vertices[ 0 ], vertices[ 1 ],
  20749. vertices[ 1 ], vertices[ 2 ],
  20750. vertices[ 2 ], vertices[ 3 ],
  20751. vertices[ 3 ], vertices[ 0 ],
  20752. vertices[ 4 ], vertices[ 5 ],
  20753. vertices[ 5 ], vertices[ 6 ],
  20754. vertices[ 6 ], vertices[ 7 ],
  20755. vertices[ 7 ], vertices[ 4 ],
  20756. vertices[ 0 ], vertices[ 4 ],
  20757. vertices[ 1 ], vertices[ 5 ],
  20758. vertices[ 2 ], vertices[ 6 ],
  20759. vertices[ 3 ], vertices[ 7 ]
  20760. );
  20761. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces );
  20762. if ( object !== undefined ) {
  20763. this.update( object );
  20764. }
  20765. };
  20766. THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype );
  20767. THREE.BoxHelper.prototype.update = function ( object ) {
  20768. var geometry = object.geometry;
  20769. if ( geometry.boundingBox === null ) {
  20770. geometry.computeBoundingBox();
  20771. }
  20772. var min = geometry.boundingBox.min;
  20773. var max = geometry.boundingBox.max;
  20774. var vertices = this.vertices;
  20775. vertices[ 0 ].set( max.x, max.y, max.z );
  20776. vertices[ 1 ].set( min.x, max.y, max.z );
  20777. vertices[ 2 ].set( min.x, min.y, max.z );
  20778. vertices[ 3 ].set( max.x, min.y, max.z );
  20779. vertices[ 4 ].set( max.x, max.y, min.z );
  20780. vertices[ 5 ].set( min.x, max.y, min.z );
  20781. vertices[ 6 ].set( min.x, min.y, min.z );
  20782. vertices[ 7 ].set( max.x, min.y, min.z );
  20783. this.geometry.computeBoundingSphere();
  20784. this.geometry.verticesNeedUpdate = true;
  20785. this.matrixAutoUpdate = false;
  20786. this.matrixWorld = object.matrixWorld;
  20787. };
  20788. /**
  20789. * @author WestLangley / http://github.com/WestLangley
  20790. */
  20791. // a helper to show the world-axis-aligned bounding box for an object
  20792. THREE.BoundingBoxHelper = function ( object, hex ) {
  20793. var color = hex || 0x888888;
  20794. this.object = object;
  20795. this.box = new THREE.Box3();
  20796. THREE.Mesh.call( this, new THREE.CubeGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  20797. };
  20798. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  20799. THREE.BoundingBoxHelper.prototype.update = function () {
  20800. this.box.setFromObject( this.object );
  20801. this.box.size( this.scale );
  20802. this.box.center( this.position );
  20803. };
  20804. /**
  20805. * @author alteredq / http://alteredqualia.com/
  20806. *
  20807. * - shows frustum, line of sight and up of the camera
  20808. * - suitable for fast updates
  20809. * - based on frustum visualization in lightgl.js shadowmap example
  20810. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20811. */
  20812. THREE.CameraHelper = function ( camera ) {
  20813. THREE.Line.call( this );
  20814. var geometry = new THREE.Geometry();
  20815. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20816. var pointMap = {};
  20817. // colors
  20818. var hexFrustum = 0xffaa00;
  20819. var hexCone = 0xff0000;
  20820. var hexUp = 0x00aaff;
  20821. var hexTarget = 0xffffff;
  20822. var hexCross = 0x333333;
  20823. // near
  20824. addLine( "n1", "n2", hexFrustum );
  20825. addLine( "n2", "n4", hexFrustum );
  20826. addLine( "n4", "n3", hexFrustum );
  20827. addLine( "n3", "n1", hexFrustum );
  20828. // far
  20829. addLine( "f1", "f2", hexFrustum );
  20830. addLine( "f2", "f4", hexFrustum );
  20831. addLine( "f4", "f3", hexFrustum );
  20832. addLine( "f3", "f1", hexFrustum );
  20833. // sides
  20834. addLine( "n1", "f1", hexFrustum );
  20835. addLine( "n2", "f2", hexFrustum );
  20836. addLine( "n3", "f3", hexFrustum );
  20837. addLine( "n4", "f4", hexFrustum );
  20838. // cone
  20839. addLine( "p", "n1", hexCone );
  20840. addLine( "p", "n2", hexCone );
  20841. addLine( "p", "n3", hexCone );
  20842. addLine( "p", "n4", hexCone );
  20843. // up
  20844. addLine( "u1", "u2", hexUp );
  20845. addLine( "u2", "u3", hexUp );
  20846. addLine( "u3", "u1", hexUp );
  20847. // target
  20848. addLine( "c", "t", hexTarget );
  20849. addLine( "p", "c", hexCross );
  20850. // cross
  20851. addLine( "cn1", "cn2", hexCross );
  20852. addLine( "cn3", "cn4", hexCross );
  20853. addLine( "cf1", "cf2", hexCross );
  20854. addLine( "cf3", "cf4", hexCross );
  20855. function addLine( a, b, hex ) {
  20856. addPoint( a, hex );
  20857. addPoint( b, hex );
  20858. }
  20859. function addPoint( id, hex ) {
  20860. geometry.vertices.push( new THREE.Vector3() );
  20861. geometry.colors.push( new THREE.Color( hex ) );
  20862. if ( pointMap[ id ] === undefined ) {
  20863. pointMap[ id ] = [];
  20864. }
  20865. pointMap[ id ].push( geometry.vertices.length - 1 );
  20866. }
  20867. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20868. this.camera = camera;
  20869. this.matrixWorld = camera.matrixWorld;
  20870. this.matrixAutoUpdate = false;
  20871. this.pointMap = pointMap;
  20872. this.update();
  20873. };
  20874. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20875. THREE.CameraHelper.prototype.update = function () {
  20876. var vector = new THREE.Vector3();
  20877. var camera = new THREE.Camera();
  20878. var projector = new THREE.Projector();
  20879. return function () {
  20880. var scope = this;
  20881. var w = 1, h = 1;
  20882. // we need just camera projection matrix
  20883. // world matrix must be identity
  20884. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  20885. // center / target
  20886. setPoint( "c", 0, 0, -1 );
  20887. setPoint( "t", 0, 0, 1 );
  20888. // near
  20889. setPoint( "n1", -w, -h, -1 );
  20890. setPoint( "n2", w, -h, -1 );
  20891. setPoint( "n3", -w, h, -1 );
  20892. setPoint( "n4", w, h, -1 );
  20893. // far
  20894. setPoint( "f1", -w, -h, 1 );
  20895. setPoint( "f2", w, -h, 1 );
  20896. setPoint( "f3", -w, h, 1 );
  20897. setPoint( "f4", w, h, 1 );
  20898. // up
  20899. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  20900. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  20901. setPoint( "u3", 0, h * 2, -1 );
  20902. // cross
  20903. setPoint( "cf1", -w, 0, 1 );
  20904. setPoint( "cf2", w, 0, 1 );
  20905. setPoint( "cf3", 0, -h, 1 );
  20906. setPoint( "cf4", 0, h, 1 );
  20907. setPoint( "cn1", -w, 0, -1 );
  20908. setPoint( "cn2", w, 0, -1 );
  20909. setPoint( "cn3", 0, -h, -1 );
  20910. setPoint( "cn4", 0, h, -1 );
  20911. function setPoint( point, x, y, z ) {
  20912. vector.set( x, y, z );
  20913. projector.unprojectVector( vector, camera );
  20914. var points = scope.pointMap[ point ];
  20915. if ( points !== undefined ) {
  20916. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20917. scope.geometry.vertices[ points[ i ] ].copy( vector );
  20918. }
  20919. }
  20920. }
  20921. this.geometry.verticesNeedUpdate = true;
  20922. };
  20923. }();
  20924. /**
  20925. * @author alteredq / http://alteredqualia.com/
  20926. * @author mrdoob / http://mrdoob.com/
  20927. */
  20928. THREE.DirectionalLightHelper = function ( light, sphereSize ) {
  20929. THREE.Object3D.call( this );
  20930. this.matrixAutoUpdate = false;
  20931. this.light = light;
  20932. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20933. var material = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  20934. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20935. this.lightSphere = new THREE.Mesh( geometry, material );
  20936. this.lightSphere.matrixWorld = this.light.matrixWorld;
  20937. this.lightSphere.matrixAutoUpdate = false;
  20938. this.add( this.lightSphere );
  20939. /*
  20940. this.targetSphere = new THREE.Mesh( geometry, material );
  20941. this.targetSphere.position = this.light.target.position;
  20942. this.add( this.targetSphere );
  20943. */
  20944. geometry = new THREE.Geometry();
  20945. geometry.vertices.push( this.light.position );
  20946. geometry.vertices.push( this.light.target.position );
  20947. geometry.computeLineDistances();
  20948. material = new THREE.LineDashedMaterial( { dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20949. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20950. this.targetLine = new THREE.Line( geometry, material );
  20951. this.add( this.targetLine );
  20952. }
  20953. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20954. THREE.DirectionalLightHelper.prototype.update = function () {
  20955. this.lightSphere.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20956. this.targetLine.geometry.computeLineDistances();
  20957. this.targetLine.geometry.verticesNeedUpdate = true;
  20958. this.targetLine.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20959. };
  20960. /**
  20961. * @author mrdoob / http://mrdoob.com/
  20962. * @author WestLangley / http://github.com/WestLangley
  20963. */
  20964. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  20965. this.object = object;
  20966. this.size = size || 1;
  20967. var color = hex || 0xffff00;
  20968. var width = linewidth || 1;
  20969. var geometry = new THREE.Geometry();
  20970. var faces = this.object.geometry.faces;
  20971. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20972. geometry.vertices.push( new THREE.Vector3() );
  20973. geometry.vertices.push( new THREE.Vector3() );
  20974. }
  20975. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20976. this.matrixAutoUpdate = false;
  20977. this.normalMatrix = new THREE.Matrix3();
  20978. this.update();
  20979. };
  20980. THREE.FaceNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20981. THREE.FaceNormalsHelper.prototype.update = ( function ( object ) {
  20982. var v1 = new THREE.Vector3();
  20983. return function( object ) {
  20984. this.object.updateMatrixWorld( true );
  20985. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  20986. var vertices = this.geometry.vertices;
  20987. var faces = this.object.geometry.faces;
  20988. var worldMatrix = this.object.matrixWorld;
  20989. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20990. var face = faces[ i ];
  20991. v1.copy( face.normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  20992. var idx = 2 * i;
  20993. vertices[ idx ].copy( face.centroid ).applyMatrix4( worldMatrix );
  20994. vertices[ idx + 1 ].addVectors( vertices[ idx ], v1 );
  20995. }
  20996. this.geometry.verticesNeedUpdate = true;
  20997. return this;
  20998. }
  20999. }());
  21000. /**
  21001. * @author mrdoob / http://mrdoob.com/
  21002. */
  21003. THREE.GridHelper = function ( size, step ) {
  21004. var geometry = new THREE.Geometry();
  21005. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  21006. this.color1 = new THREE.Color( 0x444444 );
  21007. this.color2 = new THREE.Color( 0x888888 );
  21008. for ( var i = - size; i <= size; i += step ) {
  21009. geometry.vertices.push(
  21010. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  21011. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  21012. );
  21013. var color = i === 0 ? this.color1 : this.color2;
  21014. geometry.colors.push( color, color, color, color );
  21015. }
  21016. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  21017. };
  21018. THREE.GridHelper.prototype = Object.create( THREE.Line.prototype );
  21019. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  21020. this.color1.set( colorCenterLine );
  21021. this.color2.set( colorGrid );
  21022. this.geometry.colorsNeedUpdate = true;
  21023. }
  21024. /**
  21025. * @author alteredq / http://alteredqualia.com/
  21026. * @author mrdoob / http://mrdoob.com/
  21027. */
  21028. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  21029. THREE.Object3D.call( this );
  21030. this.light = light;
  21031. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  21032. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  21033. for ( var i = 0, il = 8; i < il; i ++ ) {
  21034. geometry.faces[ i ].materialIndex = i < 4 ? 0 : 1;
  21035. }
  21036. var materialSky = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  21037. materialSky.color.copy( light.color ).multiplyScalar( light.intensity );
  21038. var materialGround = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  21039. materialGround.color.copy( light.groundColor ).multiplyScalar( light.intensity );
  21040. this.lightSphere = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( [ materialSky, materialGround ] ) );
  21041. this.lightSphere.position = light.position;
  21042. this.lightSphere.lookAt( new THREE.Vector3() );
  21043. this.add( this.lightSphere );
  21044. };
  21045. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  21046. THREE.HemisphereLightHelper.prototype.update = function () {
  21047. this.lightSphere.lookAt( new THREE.Vector3() );
  21048. this.lightSphere.material.materials[ 0 ].color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21049. this.lightSphere.material.materials[ 1 ].color.copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  21050. };
  21051. /**
  21052. * @author alteredq / http://alteredqualia.com/
  21053. * @author mrdoob / http://mrdoob.com/
  21054. */
  21055. THREE.PointLightHelper = function ( light, sphereSize ) {
  21056. THREE.Object3D.call( this );
  21057. this.matrixAutoUpdate = false;
  21058. this.light = light;
  21059. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  21060. var material = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  21061. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21062. this.lightSphere = new THREE.Mesh( geometry, material );
  21063. this.lightSphere.matrixWorld = this.light.matrixWorld;
  21064. this.lightSphere.matrixAutoUpdate = false;
  21065. this.add( this.lightSphere );
  21066. /*
  21067. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  21068. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  21069. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  21070. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  21071. var d = light.distance;
  21072. if ( d === 0.0 ) {
  21073. this.lightDistance.visible = false;
  21074. } else {
  21075. this.lightDistance.scale.set( d, d, d );
  21076. }
  21077. this.add( this.lightDistance );
  21078. */
  21079. };
  21080. THREE.PointLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  21081. THREE.PointLightHelper.prototype.update = function () {
  21082. this.lightSphere.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21083. /*
  21084. this.lightDistance.material.color.copy( this.color );
  21085. var d = this.light.distance;
  21086. if ( d === 0.0 ) {
  21087. this.lightDistance.visible = false;
  21088. } else {
  21089. this.lightDistance.visible = true;
  21090. this.lightDistance.scale.set( d, d, d );
  21091. }
  21092. */
  21093. };
  21094. /**
  21095. * @author alteredq / http://alteredqualia.com/
  21096. * @author mrdoob / http://mrdoob.com/
  21097. * @author WestLangley / http://github.com/WestLangley
  21098. */
  21099. THREE.SpotLightHelper = function ( light ) {
  21100. // spotlight helper must be a child of the scene
  21101. this.light = light;
  21102. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  21103. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, -0.5, 0 ) );
  21104. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  21105. var material = new THREE.MeshBasicMaterial( { wireframe: true, opacity: 0.3, transparent: true } );
  21106. THREE.Mesh.call( this, geometry, material );
  21107. this.update();
  21108. };
  21109. THREE.SpotLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  21110. THREE.SpotLightHelper.prototype.update = ( function () {
  21111. var targetPosition = new THREE.Vector3();
  21112. return function() {
  21113. var coneLength = this.light.distance ? this.light.distance : 10000;
  21114. var coneWidth = coneLength * Math.tan( this.light.angle );
  21115. this.scale.set( coneWidth, coneWidth, coneLength );
  21116. this.light.updateMatrixWorld( true );
  21117. this.position.getPositionFromMatrix( this.light.matrixWorld );
  21118. this.light.target.updateMatrixWorld( true );
  21119. targetPosition.getPositionFromMatrix( this.light.target.matrixWorld );
  21120. this.lookAt( targetPosition );
  21121. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21122. }
  21123. }());
  21124. /**
  21125. * @author mrdoob / http://mrdoob.com/
  21126. * @author WestLangley / http://github.com/WestLangley
  21127. */
  21128. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  21129. this.object = object;
  21130. this.size = size || 1;
  21131. var color = hex || 0xff0000;
  21132. var width = linewidth || 1;
  21133. var geometry = new THREE.Geometry();
  21134. var vertices = object.geometry.vertices;
  21135. var faces = object.geometry.faces;
  21136. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21137. var face = faces[ i ];
  21138. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  21139. geometry.vertices.push( new THREE.Vector3() );
  21140. geometry.vertices.push( new THREE.Vector3() );
  21141. }
  21142. }
  21143. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21144. this.matrixAutoUpdate = false;
  21145. this.normalMatrix = new THREE.Matrix3();
  21146. this.update();
  21147. };
  21148. THREE.VertexNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  21149. THREE.VertexNormalsHelper.prototype.update = ( function ( object ) {
  21150. var v1 = new THREE.Vector3();
  21151. return function( object ) {
  21152. var keys = [ 'a', 'b', 'c', 'd' ];
  21153. this.object.updateMatrixWorld( true );
  21154. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  21155. var vertices = this.geometry.vertices;
  21156. var verts = this.object.geometry.vertices;
  21157. var faces = this.object.geometry.faces;
  21158. var worldMatrix = this.object.matrixWorld;
  21159. var idx = 0;
  21160. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21161. var face = faces[ i ];
  21162. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  21163. var vertexId = face[ keys[ j ] ];
  21164. var vertex = verts[ vertexId ];
  21165. var normal = face.vertexNormals[ j ];
  21166. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  21167. v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  21168. v1.add( vertices[ idx ] );
  21169. idx = idx + 1;
  21170. vertices[ idx ].copy( v1 );
  21171. idx = idx + 1;
  21172. }
  21173. }
  21174. this.geometry.verticesNeedUpdate = true;
  21175. return this;
  21176. }
  21177. }());
  21178. /**
  21179. * @author mrdoob / http://mrdoob.com/
  21180. * @author WestLangley / http://github.com/WestLangley
  21181. */
  21182. THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) {
  21183. this.object = object;
  21184. this.size = size || 1;
  21185. var color = hex || 0x0000ff;
  21186. var width = linewidth || 1;
  21187. var geometry = new THREE.Geometry();
  21188. var vertices = object.geometry.vertices;
  21189. var faces = object.geometry.faces;
  21190. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21191. var face = faces[ i ];
  21192. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  21193. geometry.vertices.push( new THREE.Vector3() );
  21194. geometry.vertices.push( new THREE.Vector3() );
  21195. }
  21196. }
  21197. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21198. this.matrixAutoUpdate = false;
  21199. this.update();
  21200. };
  21201. THREE.VertexTangentsHelper.prototype = Object.create( THREE.Line.prototype );
  21202. THREE.VertexTangentsHelper.prototype.update = ( function ( object ) {
  21203. var v1 = new THREE.Vector3();
  21204. return function( object ) {
  21205. var keys = [ 'a', 'b', 'c', 'd' ];
  21206. this.object.updateMatrixWorld( true );
  21207. var vertices = this.geometry.vertices;
  21208. var verts = this.object.geometry.vertices;
  21209. var faces = this.object.geometry.faces;
  21210. var worldMatrix = this.object.matrixWorld;
  21211. var idx = 0;
  21212. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21213. var face = faces[ i ];
  21214. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  21215. var vertexId = face[ keys[ j ] ];
  21216. var vertex = verts[ vertexId ];
  21217. var tangent = face.vertexTangents[ j ];
  21218. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  21219. v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size );
  21220. v1.add( vertices[ idx ] );
  21221. idx = idx + 1;
  21222. vertices[ idx ].copy( v1 );
  21223. idx = idx + 1;
  21224. }
  21225. }
  21226. this.geometry.verticesNeedUpdate = true;
  21227. return this;
  21228. }
  21229. }());
  21230. /**
  21231. * @author mrdoob / http://mrdoob.com/
  21232. */
  21233. THREE.WireframeHelper = function ( object ) {
  21234. var edge = [ 0, 0 ], hash = {};
  21235. var sortFunction = function ( a, b ) { return a - b };
  21236. var keys = [ 'a', 'b', 'c', 'd' ];
  21237. var geometry = new THREE.Geometry();
  21238. var vertices = object.geometry.vertices;
  21239. var faces = object.geometry.faces;
  21240. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21241. var face = faces[ i ];
  21242. var length = face instanceof THREE.Face4 ? 4 : 3;
  21243. for ( var j = 0; j < length; j ++ ) {
  21244. edge[ 0 ] = face[ keys[ j ] ];
  21245. edge[ 1 ] = face[ keys[ ( j + 1 ) % length ] ];
  21246. edge.sort( sortFunction );
  21247. var key = edge.toString();
  21248. if ( hash[ key ] === undefined ) {
  21249. geometry.vertices.push( vertices[ edge[ 0 ] ] );
  21250. geometry.vertices.push( vertices[ edge[ 1 ] ] );
  21251. hash[ key ] = true;
  21252. }
  21253. }
  21254. }
  21255. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffffff } ), THREE.LinePieces );
  21256. this.matrixAutoUpdate = false;
  21257. this.matrixWorld = object.matrixWorld;
  21258. };
  21259. THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype );
  21260. /**
  21261. * @author alteredq / http://alteredqualia.com/
  21262. */
  21263. THREE.ImmediateRenderObject = function () {
  21264. THREE.Object3D.call( this );
  21265. this.render = function ( renderCallback ) { };
  21266. };
  21267. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  21268. /**
  21269. * @author mikael emtinger / http://gomo.se/
  21270. * @author alteredq / http://alteredqualia.com/
  21271. */
  21272. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  21273. THREE.Object3D.call( this );
  21274. this.lensFlares = [];
  21275. this.positionScreen = new THREE.Vector3();
  21276. this.customUpdateCallback = undefined;
  21277. if( texture !== undefined ) {
  21278. this.add( texture, size, distance, blending, color );
  21279. }
  21280. };
  21281. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  21282. /*
  21283. * Add: adds another flare
  21284. */
  21285. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  21286. if( size === undefined ) size = -1;
  21287. if( distance === undefined ) distance = 0;
  21288. if( opacity === undefined ) opacity = 1;
  21289. if( color === undefined ) color = new THREE.Color( 0xffffff );
  21290. if( blending === undefined ) blending = THREE.NormalBlending;
  21291. distance = Math.min( distance, Math.max( 0, distance ) );
  21292. this.lensFlares.push( { texture: texture, // THREE.Texture
  21293. size: size, // size in pixels (-1 = use texture.width)
  21294. distance: distance, // distance (0-1) from light source (0=at light source)
  21295. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  21296. scale: 1, // scale
  21297. rotation: 1, // rotation
  21298. opacity: opacity, // opacity
  21299. color: color, // color
  21300. blending: blending } ); // blending
  21301. };
  21302. /*
  21303. * Update lens flares update positions on all flares based on the screen position
  21304. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  21305. */
  21306. THREE.LensFlare.prototype.updateLensFlares = function () {
  21307. var f, fl = this.lensFlares.length;
  21308. var flare;
  21309. var vecX = -this.positionScreen.x * 2;
  21310. var vecY = -this.positionScreen.y * 2;
  21311. for( f = 0; f < fl; f ++ ) {
  21312. flare = this.lensFlares[ f ];
  21313. flare.x = this.positionScreen.x + vecX * flare.distance;
  21314. flare.y = this.positionScreen.y + vecY * flare.distance;
  21315. flare.wantedRotation = flare.x * Math.PI * 0.25;
  21316. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  21317. }
  21318. };
  21319. /**
  21320. * @author alteredq / http://alteredqualia.com/
  21321. */
  21322. THREE.MorphBlendMesh = function( geometry, material ) {
  21323. THREE.Mesh.call( this, geometry, material );
  21324. this.animationsMap = {};
  21325. this.animationsList = [];
  21326. // prepare default animation
  21327. // (all frames played together in 1 second)
  21328. var numFrames = this.geometry.morphTargets.length;
  21329. var name = "__default";
  21330. var startFrame = 0;
  21331. var endFrame = numFrames - 1;
  21332. var fps = numFrames / 1;
  21333. this.createAnimation( name, startFrame, endFrame, fps );
  21334. this.setAnimationWeight( name, 1 );
  21335. };
  21336. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  21337. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  21338. var animation = {
  21339. startFrame: start,
  21340. endFrame: end,
  21341. length: end - start + 1,
  21342. fps: fps,
  21343. duration: ( end - start ) / fps,
  21344. lastFrame: 0,
  21345. currentFrame: 0,
  21346. active: false,
  21347. time: 0,
  21348. direction: 1,
  21349. weight: 1,
  21350. directionBackwards: false,
  21351. mirroredLoop: false
  21352. };
  21353. this.animationsMap[ name ] = animation;
  21354. this.animationsList.push( animation );
  21355. };
  21356. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  21357. var pattern = /([a-z]+)(\d+)/;
  21358. var firstAnimation, frameRanges = {};
  21359. var geometry = this.geometry;
  21360. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  21361. var morph = geometry.morphTargets[ i ];
  21362. var chunks = morph.name.match( pattern );
  21363. if ( chunks && chunks.length > 1 ) {
  21364. var name = chunks[ 1 ];
  21365. var num = chunks[ 2 ];
  21366. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  21367. var range = frameRanges[ name ];
  21368. if ( i < range.start ) range.start = i;
  21369. if ( i > range.end ) range.end = i;
  21370. if ( ! firstAnimation ) firstAnimation = name;
  21371. }
  21372. }
  21373. for ( var name in frameRanges ) {
  21374. var range = frameRanges[ name ];
  21375. this.createAnimation( name, range.start, range.end, fps );
  21376. }
  21377. this.firstAnimation = firstAnimation;
  21378. };
  21379. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  21380. var animation = this.animationsMap[ name ];
  21381. if ( animation ) {
  21382. animation.direction = 1;
  21383. animation.directionBackwards = false;
  21384. }
  21385. };
  21386. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  21387. var animation = this.animationsMap[ name ];
  21388. if ( animation ) {
  21389. animation.direction = -1;
  21390. animation.directionBackwards = true;
  21391. }
  21392. };
  21393. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  21394. var animation = this.animationsMap[ name ];
  21395. if ( animation ) {
  21396. animation.fps = fps;
  21397. animation.duration = ( animation.end - animation.start ) / animation.fps;
  21398. }
  21399. };
  21400. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  21401. var animation = this.animationsMap[ name ];
  21402. if ( animation ) {
  21403. animation.duration = duration;
  21404. animation.fps = ( animation.end - animation.start ) / animation.duration;
  21405. }
  21406. };
  21407. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  21408. var animation = this.animationsMap[ name ];
  21409. if ( animation ) {
  21410. animation.weight = weight;
  21411. }
  21412. };
  21413. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  21414. var animation = this.animationsMap[ name ];
  21415. if ( animation ) {
  21416. animation.time = time;
  21417. }
  21418. };
  21419. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  21420. var time = 0;
  21421. var animation = this.animationsMap[ name ];
  21422. if ( animation ) {
  21423. time = animation.time;
  21424. }
  21425. return time;
  21426. };
  21427. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  21428. var duration = -1;
  21429. var animation = this.animationsMap[ name ];
  21430. if ( animation ) {
  21431. duration = animation.duration;
  21432. }
  21433. return duration;
  21434. };
  21435. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  21436. var animation = this.animationsMap[ name ];
  21437. if ( animation ) {
  21438. animation.time = 0;
  21439. animation.active = true;
  21440. } else {
  21441. console.warn( "animation[" + name + "] undefined" );
  21442. }
  21443. };
  21444. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  21445. var animation = this.animationsMap[ name ];
  21446. if ( animation ) {
  21447. animation.active = false;
  21448. }
  21449. };
  21450. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  21451. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  21452. var animation = this.animationsList[ i ];
  21453. if ( ! animation.active ) continue;
  21454. var frameTime = animation.duration / animation.length;
  21455. animation.time += animation.direction * delta;
  21456. if ( animation.mirroredLoop ) {
  21457. if ( animation.time > animation.duration || animation.time < 0 ) {
  21458. animation.direction *= -1;
  21459. if ( animation.time > animation.duration ) {
  21460. animation.time = animation.duration;
  21461. animation.directionBackwards = true;
  21462. }
  21463. if ( animation.time < 0 ) {
  21464. animation.time = 0;
  21465. animation.directionBackwards = false;
  21466. }
  21467. }
  21468. } else {
  21469. animation.time = animation.time % animation.duration;
  21470. if ( animation.time < 0 ) animation.time += animation.duration;
  21471. }
  21472. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  21473. var weight = animation.weight;
  21474. if ( keyframe !== animation.currentFrame ) {
  21475. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  21476. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  21477. this.morphTargetInfluences[ keyframe ] = 0;
  21478. animation.lastFrame = animation.currentFrame;
  21479. animation.currentFrame = keyframe;
  21480. }
  21481. var mix = ( animation.time % frameTime ) / frameTime;
  21482. if ( animation.directionBackwards ) mix = 1 - mix;
  21483. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  21484. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  21485. }
  21486. };
  21487. /**
  21488. * @author mikael emtinger / http://gomo.se/
  21489. * @author alteredq / http://alteredqualia.com/
  21490. */
  21491. THREE.LensFlarePlugin = function () {
  21492. var _gl, _renderer, _precision, _lensFlare = {};
  21493. this.init = function ( renderer ) {
  21494. _gl = renderer.context;
  21495. _renderer = renderer;
  21496. _precision = renderer.getPrecision();
  21497. _lensFlare.vertices = new Float32Array( 8 + 8 );
  21498. _lensFlare.faces = new Uint16Array( 6 );
  21499. var i = 0;
  21500. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  21501. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  21502. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  21503. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  21504. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21505. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21506. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  21507. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  21508. i = 0;
  21509. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  21510. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  21511. // buffers
  21512. _lensFlare.vertexBuffer = _gl.createBuffer();
  21513. _lensFlare.elementBuffer = _gl.createBuffer();
  21514. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21515. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  21516. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21517. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  21518. // textures
  21519. _lensFlare.tempTexture = _gl.createTexture();
  21520. _lensFlare.occlusionTexture = _gl.createTexture();
  21521. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21522. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  21523. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21524. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21525. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21526. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21527. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21528. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  21529. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21530. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21531. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21532. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21533. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  21534. _lensFlare.hasVertexTexture = false;
  21535. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  21536. } else {
  21537. _lensFlare.hasVertexTexture = true;
  21538. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  21539. }
  21540. _lensFlare.attributes = {};
  21541. _lensFlare.uniforms = {};
  21542. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  21543. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  21544. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  21545. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  21546. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  21547. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  21548. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  21549. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  21550. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  21551. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  21552. };
  21553. /*
  21554. * Render lens flares
  21555. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  21556. * reads these back and calculates occlusion.
  21557. * Then _lensFlare.update_lensFlares() is called to re-position and
  21558. * update transparency of flares. Then they are rendered.
  21559. *
  21560. */
  21561. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21562. var flares = scene.__webglFlares,
  21563. nFlares = flares.length;
  21564. if ( ! nFlares ) return;
  21565. var tempPosition = new THREE.Vector3();
  21566. var invAspect = viewportHeight / viewportWidth,
  21567. halfViewportWidth = viewportWidth * 0.5,
  21568. halfViewportHeight = viewportHeight * 0.5;
  21569. var size = 16 / viewportHeight,
  21570. scale = new THREE.Vector2( size * invAspect, size );
  21571. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  21572. screenPositionPixels = new THREE.Vector2( 1, 1 );
  21573. var uniforms = _lensFlare.uniforms,
  21574. attributes = _lensFlare.attributes;
  21575. // set _lensFlare program and reset blending
  21576. _gl.useProgram( _lensFlare.program );
  21577. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  21578. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  21579. // loop through all lens flares to update their occlusion and positions
  21580. // setup gl and common used attribs/unforms
  21581. _gl.uniform1i( uniforms.occlusionMap, 0 );
  21582. _gl.uniform1i( uniforms.map, 1 );
  21583. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21584. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21585. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21586. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21587. _gl.disable( _gl.CULL_FACE );
  21588. _gl.depthMask( false );
  21589. var i, j, jl, flare, sprite;
  21590. for ( i = 0; i < nFlares; i ++ ) {
  21591. size = 16 / viewportHeight;
  21592. scale.set( size * invAspect, size );
  21593. // calc object screen position
  21594. flare = flares[ i ];
  21595. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  21596. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  21597. tempPosition.applyProjection( camera.projectionMatrix );
  21598. // setup arrays for gl programs
  21599. screenPosition.copy( tempPosition )
  21600. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  21601. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  21602. // screen cull
  21603. if ( _lensFlare.hasVertexTexture || (
  21604. screenPositionPixels.x > 0 &&
  21605. screenPositionPixels.x < viewportWidth &&
  21606. screenPositionPixels.y > 0 &&
  21607. screenPositionPixels.y < viewportHeight ) ) {
  21608. // save current RGB to temp texture
  21609. _gl.activeTexture( _gl.TEXTURE1 );
  21610. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21611. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21612. // render pink quad
  21613. _gl.uniform1i( uniforms.renderType, 0 );
  21614. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21615. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21616. _gl.disable( _gl.BLEND );
  21617. _gl.enable( _gl.DEPTH_TEST );
  21618. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21619. // copy result to occlusionMap
  21620. _gl.activeTexture( _gl.TEXTURE0 );
  21621. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21622. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21623. // restore graphics
  21624. _gl.uniform1i( uniforms.renderType, 1 );
  21625. _gl.disable( _gl.DEPTH_TEST );
  21626. _gl.activeTexture( _gl.TEXTURE1 );
  21627. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21628. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21629. // update object positions
  21630. flare.positionScreen.copy( screenPosition )
  21631. if ( flare.customUpdateCallback ) {
  21632. flare.customUpdateCallback( flare );
  21633. } else {
  21634. flare.updateLensFlares();
  21635. }
  21636. // render flares
  21637. _gl.uniform1i( uniforms.renderType, 2 );
  21638. _gl.enable( _gl.BLEND );
  21639. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21640. sprite = flare.lensFlares[ j ];
  21641. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21642. screenPosition.x = sprite.x;
  21643. screenPosition.y = sprite.y;
  21644. screenPosition.z = sprite.z;
  21645. size = sprite.size * sprite.scale / viewportHeight;
  21646. scale.x = size * invAspect;
  21647. scale.y = size;
  21648. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21649. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21650. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21651. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21652. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21653. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21654. _renderer.setTexture( sprite.texture, 1 );
  21655. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21656. }
  21657. }
  21658. }
  21659. }
  21660. // restore gl
  21661. _gl.enable( _gl.CULL_FACE );
  21662. _gl.enable( _gl.DEPTH_TEST );
  21663. _gl.depthMask( true );
  21664. };
  21665. function createProgram ( shader, precision ) {
  21666. var program = _gl.createProgram();
  21667. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21668. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21669. var prefix = "precision " + precision + " float;\n";
  21670. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21671. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21672. _gl.compileShader( fragmentShader );
  21673. _gl.compileShader( vertexShader );
  21674. _gl.attachShader( program, fragmentShader );
  21675. _gl.attachShader( program, vertexShader );
  21676. _gl.linkProgram( program );
  21677. return program;
  21678. };
  21679. };
  21680. /**
  21681. * @author alteredq / http://alteredqualia.com/
  21682. */
  21683. THREE.ShadowMapPlugin = function () {
  21684. var _gl,
  21685. _renderer,
  21686. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21687. _frustum = new THREE.Frustum(),
  21688. _projScreenMatrix = new THREE.Matrix4(),
  21689. _min = new THREE.Vector3(),
  21690. _max = new THREE.Vector3(),
  21691. _matrixPosition = new THREE.Vector3();
  21692. this.init = function ( renderer ) {
  21693. _gl = renderer.context;
  21694. _renderer = renderer;
  21695. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21696. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21697. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21698. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21699. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21700. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21701. _depthMaterial._shadowPass = true;
  21702. _depthMaterialMorph._shadowPass = true;
  21703. _depthMaterialSkin._shadowPass = true;
  21704. _depthMaterialMorphSkin._shadowPass = true;
  21705. };
  21706. this.render = function ( scene, camera ) {
  21707. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21708. this.update( scene, camera );
  21709. };
  21710. this.update = function ( scene, camera ) {
  21711. var i, il, j, jl, n,
  21712. shadowMap, shadowMatrix, shadowCamera,
  21713. program, buffer, material,
  21714. webglObject, object, light,
  21715. renderList,
  21716. lights = [],
  21717. k = 0,
  21718. fog = null;
  21719. // set GL state for depth map
  21720. _gl.clearColor( 1, 1, 1, 1 );
  21721. _gl.disable( _gl.BLEND );
  21722. _gl.enable( _gl.CULL_FACE );
  21723. _gl.frontFace( _gl.CCW );
  21724. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21725. _gl.cullFace( _gl.FRONT );
  21726. } else {
  21727. _gl.cullFace( _gl.BACK );
  21728. }
  21729. _renderer.setDepthTest( true );
  21730. // preprocess lights
  21731. // - skip lights that are not casting shadows
  21732. // - create virtual lights for cascaded shadow maps
  21733. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21734. light = scene.__lights[ i ];
  21735. if ( ! light.castShadow ) continue;
  21736. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21737. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21738. var virtualLight;
  21739. if ( ! light.shadowCascadeArray[ n ] ) {
  21740. virtualLight = createVirtualLight( light, n );
  21741. virtualLight.originalCamera = camera;
  21742. var gyro = new THREE.Gyroscope();
  21743. gyro.position = light.shadowCascadeOffset;
  21744. gyro.add( virtualLight );
  21745. gyro.add( virtualLight.target );
  21746. camera.add( gyro );
  21747. light.shadowCascadeArray[ n ] = virtualLight;
  21748. console.log( "Created virtualLight", virtualLight );
  21749. } else {
  21750. virtualLight = light.shadowCascadeArray[ n ];
  21751. }
  21752. updateVirtualLight( light, n );
  21753. lights[ k ] = virtualLight;
  21754. k ++;
  21755. }
  21756. } else {
  21757. lights[ k ] = light;
  21758. k ++;
  21759. }
  21760. }
  21761. // render depth map
  21762. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21763. light = lights[ i ];
  21764. if ( ! light.shadowMap ) {
  21765. var shadowFilter = THREE.LinearFilter;
  21766. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  21767. shadowFilter = THREE.NearestFilter;
  21768. }
  21769. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  21770. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21771. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21772. light.shadowMatrix = new THREE.Matrix4();
  21773. }
  21774. if ( ! light.shadowCamera ) {
  21775. if ( light instanceof THREE.SpotLight ) {
  21776. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21777. } else if ( light instanceof THREE.DirectionalLight ) {
  21778. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21779. } else {
  21780. console.error( "Unsupported light type for shadow" );
  21781. continue;
  21782. }
  21783. scene.add( light.shadowCamera );
  21784. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21785. }
  21786. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21787. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21788. light.shadowCamera.add( light.cameraHelper );
  21789. }
  21790. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21791. updateShadowCamera( camera, light );
  21792. }
  21793. shadowMap = light.shadowMap;
  21794. shadowMatrix = light.shadowMatrix;
  21795. shadowCamera = light.shadowCamera;
  21796. shadowCamera.position.getPositionFromMatrix( light.matrixWorld );
  21797. _matrixPosition.getPositionFromMatrix( light.target.matrixWorld );
  21798. shadowCamera.lookAt( _matrixPosition );
  21799. shadowCamera.updateMatrixWorld();
  21800. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21801. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  21802. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21803. // compute shadow matrix
  21804. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21805. 0.0, 0.5, 0.0, 0.5,
  21806. 0.0, 0.0, 0.5, 0.5,
  21807. 0.0, 0.0, 0.0, 1.0 );
  21808. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  21809. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  21810. // update camera matrices and frustum
  21811. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21812. _frustum.setFromMatrix( _projScreenMatrix );
  21813. // render shadow map
  21814. _renderer.setRenderTarget( shadowMap );
  21815. _renderer.clear();
  21816. // set object matrices & frustum culling
  21817. renderList = scene.__webglObjects;
  21818. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21819. webglObject = renderList[ j ];
  21820. object = webglObject.object;
  21821. webglObject.render = false;
  21822. if ( object.visible && object.castShadow ) {
  21823. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21824. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21825. webglObject.render = true;
  21826. }
  21827. }
  21828. }
  21829. // render regular objects
  21830. var objectMaterial, useMorphing, useSkinning;
  21831. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21832. webglObject = renderList[ j ];
  21833. if ( webglObject.render ) {
  21834. object = webglObject.object;
  21835. buffer = webglObject.buffer;
  21836. // culling is overriden globally for all objects
  21837. // while rendering depth map
  21838. // need to deal with MeshFaceMaterial somehow
  21839. // in that case just use the first of material.materials for now
  21840. // (proper solution would require to break objects by materials
  21841. // similarly to regular rendering and then set corresponding
  21842. // depth materials per each chunk instead of just once per object)
  21843. objectMaterial = getObjectMaterial( object );
  21844. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21845. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21846. if ( object.customDepthMaterial ) {
  21847. material = object.customDepthMaterial;
  21848. } else if ( useSkinning ) {
  21849. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21850. } else if ( useMorphing ) {
  21851. material = _depthMaterialMorph;
  21852. } else {
  21853. material = _depthMaterial;
  21854. }
  21855. if ( buffer instanceof THREE.BufferGeometry ) {
  21856. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21857. } else {
  21858. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21859. }
  21860. }
  21861. }
  21862. // set matrices and render immediate objects
  21863. renderList = scene.__webglObjectsImmediate;
  21864. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21865. webglObject = renderList[ j ];
  21866. object = webglObject.object;
  21867. if ( object.visible && object.castShadow ) {
  21868. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21869. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21870. }
  21871. }
  21872. }
  21873. // restore GL state
  21874. var clearColor = _renderer.getClearColor(),
  21875. clearAlpha = _renderer.getClearAlpha();
  21876. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21877. _gl.enable( _gl.BLEND );
  21878. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21879. _gl.cullFace( _gl.BACK );
  21880. }
  21881. };
  21882. function createVirtualLight( light, cascade ) {
  21883. var virtualLight = new THREE.DirectionalLight();
  21884. virtualLight.isVirtual = true;
  21885. virtualLight.onlyShadow = true;
  21886. virtualLight.castShadow = true;
  21887. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21888. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21889. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21890. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21891. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21892. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21893. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21894. virtualLight.shadowDarkness = light.shadowDarkness;
  21895. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21896. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21897. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21898. virtualLight.pointsWorld = [];
  21899. virtualLight.pointsFrustum = [];
  21900. var pointsWorld = virtualLight.pointsWorld,
  21901. pointsFrustum = virtualLight.pointsFrustum;
  21902. for ( var i = 0; i < 8; i ++ ) {
  21903. pointsWorld[ i ] = new THREE.Vector3();
  21904. pointsFrustum[ i ] = new THREE.Vector3();
  21905. }
  21906. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21907. var farZ = light.shadowCascadeFarZ[ cascade ];
  21908. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21909. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21910. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21911. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21912. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21913. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21914. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21915. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21916. return virtualLight;
  21917. }
  21918. // Synchronize virtual light with the original light
  21919. function updateVirtualLight( light, cascade ) {
  21920. var virtualLight = light.shadowCascadeArray[ cascade ];
  21921. virtualLight.position.copy( light.position );
  21922. virtualLight.target.position.copy( light.target.position );
  21923. virtualLight.lookAt( virtualLight.target );
  21924. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21925. virtualLight.shadowDarkness = light.shadowDarkness;
  21926. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21927. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21928. var farZ = light.shadowCascadeFarZ[ cascade ];
  21929. var pointsFrustum = virtualLight.pointsFrustum;
  21930. pointsFrustum[ 0 ].z = nearZ;
  21931. pointsFrustum[ 1 ].z = nearZ;
  21932. pointsFrustum[ 2 ].z = nearZ;
  21933. pointsFrustum[ 3 ].z = nearZ;
  21934. pointsFrustum[ 4 ].z = farZ;
  21935. pointsFrustum[ 5 ].z = farZ;
  21936. pointsFrustum[ 6 ].z = farZ;
  21937. pointsFrustum[ 7 ].z = farZ;
  21938. }
  21939. // Fit shadow camera's ortho frustum to camera frustum
  21940. function updateShadowCamera( camera, light ) {
  21941. var shadowCamera = light.shadowCamera,
  21942. pointsFrustum = light.pointsFrustum,
  21943. pointsWorld = light.pointsWorld;
  21944. _min.set( Infinity, Infinity, Infinity );
  21945. _max.set( -Infinity, -Infinity, -Infinity );
  21946. for ( var i = 0; i < 8; i ++ ) {
  21947. var p = pointsWorld[ i ];
  21948. p.copy( pointsFrustum[ i ] );
  21949. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21950. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  21951. if ( p.x < _min.x ) _min.x = p.x;
  21952. if ( p.x > _max.x ) _max.x = p.x;
  21953. if ( p.y < _min.y ) _min.y = p.y;
  21954. if ( p.y > _max.y ) _max.y = p.y;
  21955. if ( p.z < _min.z ) _min.z = p.z;
  21956. if ( p.z > _max.z ) _max.z = p.z;
  21957. }
  21958. shadowCamera.left = _min.x;
  21959. shadowCamera.right = _max.x;
  21960. shadowCamera.top = _max.y;
  21961. shadowCamera.bottom = _min.y;
  21962. // can't really fit near/far
  21963. //shadowCamera.near = _min.z;
  21964. //shadowCamera.far = _max.z;
  21965. shadowCamera.updateProjectionMatrix();
  21966. }
  21967. // For the moment just ignore objects that have multiple materials with different animation methods
  21968. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  21969. function getObjectMaterial( object ) {
  21970. return object.material instanceof THREE.MeshFaceMaterial
  21971. ? object.material.materials[ 0 ]
  21972. : object.material;
  21973. };
  21974. };
  21975. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21976. /**
  21977. * @author mikael emtinger / http://gomo.se/
  21978. * @author alteredq / http://alteredqualia.com/
  21979. */
  21980. THREE.SpritePlugin = function () {
  21981. var _gl, _renderer, _precision, _sprite = {};
  21982. this.init = function ( renderer ) {
  21983. _gl = renderer.context;
  21984. _renderer = renderer;
  21985. _precision = renderer.getPrecision();
  21986. _sprite.vertices = new Float32Array( 8 + 8 );
  21987. _sprite.faces = new Uint16Array( 6 );
  21988. var i = 0;
  21989. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  21990. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  21991. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  21992. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  21993. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  21994. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  21995. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  21996. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  21997. i = 0;
  21998. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  21999. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  22000. _sprite.vertexBuffer = _gl.createBuffer();
  22001. _sprite.elementBuffer = _gl.createBuffer();
  22002. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  22003. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  22004. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  22005. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  22006. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ], _precision );
  22007. _sprite.attributes = {};
  22008. _sprite.uniforms = {};
  22009. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  22010. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  22011. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  22012. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  22013. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  22014. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  22015. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  22016. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  22017. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  22018. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  22019. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  22020. _sprite.uniforms.sizeAttenuation = _gl.getUniformLocation( _sprite.program, "sizeAttenuation" );
  22021. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  22022. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  22023. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  22024. _sprite.uniforms.fogType = _gl.getUniformLocation( _sprite.program, "fogType" );
  22025. _sprite.uniforms.fogDensity = _gl.getUniformLocation( _sprite.program, "fogDensity" );
  22026. _sprite.uniforms.fogNear = _gl.getUniformLocation( _sprite.program, "fogNear" );
  22027. _sprite.uniforms.fogFar = _gl.getUniformLocation( _sprite.program, "fogFar" );
  22028. _sprite.uniforms.fogColor = _gl.getUniformLocation( _sprite.program, "fogColor" );
  22029. _sprite.uniforms.alphaTest = _gl.getUniformLocation( _sprite.program, "alphaTest" );
  22030. };
  22031. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  22032. var sprites = scene.__webglSprites,
  22033. nSprites = sprites.length;
  22034. if ( ! nSprites ) return;
  22035. var attributes = _sprite.attributes,
  22036. uniforms = _sprite.uniforms;
  22037. var invAspect = viewportHeight / viewportWidth;
  22038. var halfViewportWidth = viewportWidth * 0.5,
  22039. halfViewportHeight = viewportHeight * 0.5;
  22040. // setup gl
  22041. _gl.useProgram( _sprite.program );
  22042. _gl.enableVertexAttribArray( attributes.position );
  22043. _gl.enableVertexAttribArray( attributes.uv );
  22044. _gl.disable( _gl.CULL_FACE );
  22045. _gl.enable( _gl.BLEND );
  22046. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  22047. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  22048. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  22049. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  22050. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  22051. _gl.activeTexture( _gl.TEXTURE0 );
  22052. _gl.uniform1i( uniforms.map, 0 );
  22053. var oldFogType = 0;
  22054. var sceneFogType = 0;
  22055. var fog = scene.fog;
  22056. if ( fog ) {
  22057. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  22058. if ( fog instanceof THREE.Fog ) {
  22059. _gl.uniform1f( uniforms.fogNear, fog.near );
  22060. _gl.uniform1f( uniforms.fogFar, fog.far );
  22061. _gl.uniform1i( uniforms.fogType, 1 );
  22062. oldFogType = 1;
  22063. sceneFogType = 1;
  22064. } else if ( fog instanceof THREE.FogExp2 ) {
  22065. _gl.uniform1f( uniforms.fogDensity, fog.density );
  22066. _gl.uniform1i( uniforms.fogType, 2 );
  22067. oldFogType = 2;
  22068. sceneFogType = 2;
  22069. }
  22070. } else {
  22071. _gl.uniform1i( uniforms.fogType, 0 );
  22072. oldFogType = 0;
  22073. sceneFogType = 0;
  22074. }
  22075. // update positions and sort
  22076. var i, sprite, material, screenPosition, size, fogType, scale = [];
  22077. for( i = 0; i < nSprites; i ++ ) {
  22078. sprite = sprites[ i ];
  22079. material = sprite.material;
  22080. if ( ! sprite.visible || material.opacity === 0 ) continue;
  22081. if ( ! material.useScreenCoordinates ) {
  22082. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  22083. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  22084. } else {
  22085. sprite.z = - sprite.position.z;
  22086. }
  22087. }
  22088. sprites.sort( painterSortStable );
  22089. // render all sprites
  22090. for( i = 0; i < nSprites; i ++ ) {
  22091. sprite = sprites[ i ];
  22092. material = sprite.material;
  22093. if ( ! sprite.visible || material.opacity === 0 ) continue;
  22094. if ( material.map && material.map.image && material.map.image.width ) {
  22095. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  22096. if ( material.useScreenCoordinates === true ) {
  22097. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  22098. _gl.uniform3f(
  22099. uniforms.screenPosition,
  22100. ( ( sprite.position.x * _renderer.devicePixelRatio ) - halfViewportWidth ) / halfViewportWidth,
  22101. ( halfViewportHeight - ( sprite.position.y * _renderer.devicePixelRatio ) ) / halfViewportHeight,
  22102. Math.max( 0, Math.min( 1, sprite.position.z ) )
  22103. );
  22104. scale[ 0 ] = _renderer.devicePixelRatio;
  22105. scale[ 1 ] = _renderer.devicePixelRatio;
  22106. } else {
  22107. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  22108. _gl.uniform1i( uniforms.sizeAttenuation, material.sizeAttenuation ? 1 : 0 );
  22109. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  22110. scale[ 0 ] = 1;
  22111. scale[ 1 ] = 1;
  22112. }
  22113. if ( scene.fog && material.fog ) {
  22114. fogType = sceneFogType;
  22115. } else {
  22116. fogType = 0;
  22117. }
  22118. if ( oldFogType !== fogType ) {
  22119. _gl.uniform1i( uniforms.fogType, fogType );
  22120. oldFogType = fogType;
  22121. }
  22122. size = 1 / ( material.scaleByViewport ? viewportHeight : 1 );
  22123. scale[ 0 ] *= size * invAspect * sprite.scale.x
  22124. scale[ 1 ] *= size * sprite.scale.y;
  22125. _gl.uniform2f( uniforms.uvScale, material.uvScale.x, material.uvScale.y );
  22126. _gl.uniform2f( uniforms.uvOffset, material.uvOffset.x, material.uvOffset.y );
  22127. _gl.uniform2f( uniforms.alignment, material.alignment.x, material.alignment.y );
  22128. _gl.uniform1f( uniforms.opacity, material.opacity );
  22129. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  22130. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  22131. _gl.uniform2fv( uniforms.scale, scale );
  22132. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  22133. _renderer.setDepthTest( material.depthTest );
  22134. _renderer.setDepthWrite( material.depthWrite );
  22135. _renderer.setTexture( material.map, 0 );
  22136. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  22137. }
  22138. }
  22139. // restore gl
  22140. _gl.enable( _gl.CULL_FACE );
  22141. };
  22142. function createProgram ( shader, precision ) {
  22143. var program = _gl.createProgram();
  22144. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  22145. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  22146. var prefix = "precision " + precision + " float;\n";
  22147. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  22148. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  22149. _gl.compileShader( fragmentShader );
  22150. _gl.compileShader( vertexShader );
  22151. _gl.attachShader( program, fragmentShader );
  22152. _gl.attachShader( program, vertexShader );
  22153. _gl.linkProgram( program );
  22154. return program;
  22155. };
  22156. function painterSortStable ( a, b ) {
  22157. if ( a.z !== b.z ) {
  22158. return b.z - a.z;
  22159. } else {
  22160. return b.id - a.id;
  22161. }
  22162. };
  22163. };
  22164. /**
  22165. * @author alteredq / http://alteredqualia.com/
  22166. */
  22167. THREE.DepthPassPlugin = function () {
  22168. this.enabled = false;
  22169. this.renderTarget = null;
  22170. var _gl,
  22171. _renderer,
  22172. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  22173. _frustum = new THREE.Frustum(),
  22174. _projScreenMatrix = new THREE.Matrix4();
  22175. this.init = function ( renderer ) {
  22176. _gl = renderer.context;
  22177. _renderer = renderer;
  22178. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  22179. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  22180. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  22181. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  22182. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  22183. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  22184. _depthMaterial._shadowPass = true;
  22185. _depthMaterialMorph._shadowPass = true;
  22186. _depthMaterialSkin._shadowPass = true;
  22187. _depthMaterialMorphSkin._shadowPass = true;
  22188. };
  22189. this.render = function ( scene, camera ) {
  22190. if ( ! this.enabled ) return;
  22191. this.update( scene, camera );
  22192. };
  22193. this.update = function ( scene, camera ) {
  22194. var i, il, j, jl, n,
  22195. program, buffer, material,
  22196. webglObject, object, light,
  22197. renderList,
  22198. fog = null;
  22199. // set GL state for depth map
  22200. _gl.clearColor( 1, 1, 1, 1 );
  22201. _gl.disable( _gl.BLEND );
  22202. _renderer.setDepthTest( true );
  22203. // update scene
  22204. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  22205. // update camera matrices and frustum
  22206. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  22207. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  22208. _frustum.setFromMatrix( _projScreenMatrix );
  22209. // render depth map
  22210. _renderer.setRenderTarget( this.renderTarget );
  22211. _renderer.clear();
  22212. // set object matrices & frustum culling
  22213. renderList = scene.__webglObjects;
  22214. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22215. webglObject = renderList[ j ];
  22216. object = webglObject.object;
  22217. webglObject.render = false;
  22218. if ( object.visible ) {
  22219. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  22220. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  22221. webglObject.render = true;
  22222. }
  22223. }
  22224. }
  22225. // render regular objects
  22226. var objectMaterial, useMorphing, useSkinning;
  22227. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22228. webglObject = renderList[ j ];
  22229. if ( webglObject.render ) {
  22230. object = webglObject.object;
  22231. buffer = webglObject.buffer;
  22232. // todo: create proper depth material for particles
  22233. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  22234. objectMaterial = getObjectMaterial( object );
  22235. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  22236. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  22237. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  22238. if ( object.customDepthMaterial ) {
  22239. material = object.customDepthMaterial;
  22240. } else if ( useSkinning ) {
  22241. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  22242. } else if ( useMorphing ) {
  22243. material = _depthMaterialMorph;
  22244. } else {
  22245. material = _depthMaterial;
  22246. }
  22247. if ( buffer instanceof THREE.BufferGeometry ) {
  22248. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  22249. } else {
  22250. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  22251. }
  22252. }
  22253. }
  22254. // set matrices and render immediate objects
  22255. renderList = scene.__webglObjectsImmediate;
  22256. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22257. webglObject = renderList[ j ];
  22258. object = webglObject.object;
  22259. if ( object.visible ) {
  22260. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  22261. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  22262. }
  22263. }
  22264. // restore GL state
  22265. var clearColor = _renderer.getClearColor(),
  22266. clearAlpha = _renderer.getClearAlpha();
  22267. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  22268. _gl.enable( _gl.BLEND );
  22269. };
  22270. // For the moment just ignore objects that have multiple materials with different animation methods
  22271. // Only the first material will be taken into account for deciding which depth material to use
  22272. function getObjectMaterial( object ) {
  22273. return object.material instanceof THREE.MeshFaceMaterial
  22274. ? object.material.materials[ 0 ]
  22275. : object.material;
  22276. };
  22277. };
  22278. /**
  22279. * @author mikael emtinger / http://gomo.se/
  22280. */
  22281. THREE.ShaderFlares = {
  22282. 'lensFlareVertexTexture': {
  22283. vertexShader: [
  22284. "uniform lowp int renderType;",
  22285. "uniform vec3 screenPosition;",
  22286. "uniform vec2 scale;",
  22287. "uniform float rotation;",
  22288. "uniform sampler2D occlusionMap;",
  22289. "attribute vec2 position;",
  22290. "attribute vec2 uv;",
  22291. "varying vec2 vUV;",
  22292. "varying float vVisibility;",
  22293. "void main() {",
  22294. "vUV = uv;",
  22295. "vec2 pos = position;",
  22296. "if( renderType == 2 ) {",
  22297. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  22298. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  22299. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  22300. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  22301. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  22302. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  22303. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  22304. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  22305. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  22306. "vVisibility = visibility.r / 9.0;",
  22307. "vVisibility *= 1.0 - visibility.g / 9.0;",
  22308. "vVisibility *= visibility.b / 9.0;",
  22309. "vVisibility *= 1.0 - visibility.a / 9.0;",
  22310. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22311. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22312. "}",
  22313. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22314. "}"
  22315. ].join( "\n" ),
  22316. fragmentShader: [
  22317. "uniform lowp int renderType;",
  22318. "uniform sampler2D map;",
  22319. "uniform float opacity;",
  22320. "uniform vec3 color;",
  22321. "varying vec2 vUV;",
  22322. "varying float vVisibility;",
  22323. "void main() {",
  22324. // pink square
  22325. "if( renderType == 0 ) {",
  22326. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  22327. // restore
  22328. "} else if( renderType == 1 ) {",
  22329. "gl_FragColor = texture2D( map, vUV );",
  22330. // flare
  22331. "} else {",
  22332. "vec4 texture = texture2D( map, vUV );",
  22333. "texture.a *= opacity * vVisibility;",
  22334. "gl_FragColor = texture;",
  22335. "gl_FragColor.rgb *= color;",
  22336. "}",
  22337. "}"
  22338. ].join( "\n" )
  22339. },
  22340. 'lensFlare': {
  22341. vertexShader: [
  22342. "uniform lowp int renderType;",
  22343. "uniform vec3 screenPosition;",
  22344. "uniform vec2 scale;",
  22345. "uniform float rotation;",
  22346. "attribute vec2 position;",
  22347. "attribute vec2 uv;",
  22348. "varying vec2 vUV;",
  22349. "void main() {",
  22350. "vUV = uv;",
  22351. "vec2 pos = position;",
  22352. "if( renderType == 2 ) {",
  22353. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22354. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22355. "}",
  22356. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22357. "}"
  22358. ].join( "\n" ),
  22359. fragmentShader: [
  22360. "precision mediump float;",
  22361. "uniform lowp int renderType;",
  22362. "uniform sampler2D map;",
  22363. "uniform sampler2D occlusionMap;",
  22364. "uniform float opacity;",
  22365. "uniform vec3 color;",
  22366. "varying vec2 vUV;",
  22367. "void main() {",
  22368. // pink square
  22369. "if( renderType == 0 ) {",
  22370. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  22371. // restore
  22372. "} else if( renderType == 1 ) {",
  22373. "gl_FragColor = texture2D( map, vUV );",
  22374. // flare
  22375. "} else {",
  22376. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  22377. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  22378. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  22379. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  22380. "visibility = ( 1.0 - visibility / 4.0 );",
  22381. "vec4 texture = texture2D( map, vUV );",
  22382. "texture.a *= opacity * visibility;",
  22383. "gl_FragColor = texture;",
  22384. "gl_FragColor.rgb *= color;",
  22385. "}",
  22386. "}"
  22387. ].join( "\n" )
  22388. }
  22389. };
  22390. /**
  22391. * @author mikael emtinger / http://gomo.se/
  22392. * @author alteredq / http://alteredqualia.com/
  22393. *
  22394. */
  22395. THREE.ShaderSprite = {
  22396. 'sprite': {
  22397. vertexShader: [
  22398. "uniform int useScreenCoordinates;",
  22399. "uniform int sizeAttenuation;",
  22400. "uniform vec3 screenPosition;",
  22401. "uniform mat4 modelViewMatrix;",
  22402. "uniform mat4 projectionMatrix;",
  22403. "uniform float rotation;",
  22404. "uniform vec2 scale;",
  22405. "uniform vec2 alignment;",
  22406. "uniform vec2 uvOffset;",
  22407. "uniform vec2 uvScale;",
  22408. "attribute vec2 position;",
  22409. "attribute vec2 uv;",
  22410. "varying vec2 vUV;",
  22411. "void main() {",
  22412. "vUV = uvOffset + uv * uvScale;",
  22413. "vec2 alignedPosition = position + alignment;",
  22414. "vec2 rotatedPosition;",
  22415. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  22416. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  22417. "vec4 finalPosition;",
  22418. "if( useScreenCoordinates != 0 ) {",
  22419. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  22420. "} else {",
  22421. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  22422. "finalPosition.xy += rotatedPosition * ( sizeAttenuation == 1 ? 1.0 : finalPosition.z );",
  22423. "}",
  22424. "gl_Position = finalPosition;",
  22425. "}"
  22426. ].join( "\n" ),
  22427. fragmentShader: [
  22428. "uniform vec3 color;",
  22429. "uniform sampler2D map;",
  22430. "uniform float opacity;",
  22431. "uniform int fogType;",
  22432. "uniform vec3 fogColor;",
  22433. "uniform float fogDensity;",
  22434. "uniform float fogNear;",
  22435. "uniform float fogFar;",
  22436. "uniform float alphaTest;",
  22437. "varying vec2 vUV;",
  22438. "void main() {",
  22439. "vec4 texture = texture2D( map, vUV );",
  22440. "if ( texture.a < alphaTest ) discard;",
  22441. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  22442. "if ( fogType > 0 ) {",
  22443. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  22444. "float fogFactor = 0.0;",
  22445. "if ( fogType == 1 ) {",
  22446. "fogFactor = smoothstep( fogNear, fogFar, depth );",
  22447. "} else {",
  22448. "const float LOG2 = 1.442695;",
  22449. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  22450. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  22451. "}",
  22452. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  22453. "}",
  22454. "}"
  22455. ].join( "\n" )
  22456. }
  22457. };